• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/ucode/tests/custom/00_syntax/23_optional_chaining

  1 Optional chaining operators allow accessing nested object properties
  2 in a secure manner, without the need to check the entire reference
  3 chain for validity.
  4 
  5 
  6 1. The `?.` operator can be used to lookup a named property in a
  7 left-hand side expression without having to check whether the lhs
  8 value is a proper object.
  9 
 10 -- Expect stdout --
 11 true
 12 true
 13 -- End --
 14 
 15 -- Testcase --
 16 {%
 17         obj = { foo: 1 };
 18 
 19         print(obj.bar?.baz == null, "\n");      // obj.bar is null
 20         print(obj.foo?.bar == null, "\n");      // obj.foo is not an object
 21 %}
 22 -- End --
 23 
 24 
 25 2. The `?.[…]` operator complements the `?.` one and applies the
 26 same semantics to computed property accesses.
 27 
 28 -- Expect stdout --
 29 true
 30 true
 31 true
 32 true
 33 -- End --
 34 
 35 -- Testcase --
 36 {%
 37         obj = { foo: 1 };
 38         arr = [ 1, 2 ];
 39 
 40         print(obj["bar"]?.["baz"] == null, "\n");       // obj.bar is null
 41         print(obj["foo"]?.["bar"] == null, "\n");       // obj.foo is not an object
 42         print(arr[0]?.["foo"] == null, "\n");           // arr[0] is not an object
 43         print(foo?.[1] == null, "\n");                          // foo is not an array
 44 %}
 45 -- End --
 46 
 47 
 48 3. The `?.(…)` function call operator yields `null` when the left-hand
 49 side value is not a callable function value.
 50 
 51 -- Expect stdout --
 52 true
 53 true
 54 -- End --
 55 
 56 -- Testcase --
 57 {%
 58         foo = 1;
 59 
 60         print(foo?.(1, 2, 3) == null, "\n");    // foo is not a function
 61         print(bar?.("test") == null, "\n");             // bar is null
 62 %}
 63 -- End --
 64 
 65 
 66 4. Optional chaining operators cannot be used on the left-hand side of
 67 an assignment or increment/decrement expression.
 68 
 69 -- Expect stderr --
 70 Syntax error: Invalid left-hand side expression for assignment
 71 In line 2, byte 13:
 72 
 73  `    obj?.foo = 1;`
 74   Near here -----^
 75 
 76 
 77 -- End --
 78 
 79 -- Testcase --
 80 {%
 81         obj?.foo = 1;
 82 %}
 83 -- End --
 84 
 85 -- Expect stderr --
 86 Syntax error: Invalid increment/decrement operand
 87 In line 2, byte 7:
 88 
 89  `    obj?.foo++;`
 90            ^-- Near here
 91 
 92 
 93 -- End --
 94 
 95 -- Testcase --
 96 {%
 97         obj?.foo++;
 98 %}
 99 -- End --

This page was automatically generated by LXR 0.3.1.  •  OpenWrt