Javascript 006: Expressions

程天佑
2023-12-01

An expression is a phrase of JavaScript that can be evaluated to produce a value.

Primary Expr

Do NOT include any simpler expressions

  • constant or literal values
  • Language keywords (reserved words)
  • Variable references

Constant and Literals

1.23         // A number literal
"hello"      // A string literal
/pattern/    // A regular expression literal

Reserved Words

true       // Evalutes to the boolean true value
false      // Evaluates to the boolean false value
null       // Evaluates to the null value
this       // Evaluates to the "current" object

More on "this": Within the body of a method, this evaluates to the object on which the method was invoked.

References

Include references to a variable, constant, or property of the global object:

i             // Evaluates to the value of the variable i.
sum           // Evaluates to the value of the variable sum.
undefined     // The value of the "undefined" property of the global object

Array Initializer Expr

An array initializer is a comma-separated list of expressions contained within square brackets.

Examples

[]         // An empty array: no expressions inside brackets means no elements

[1+2, 3+4]  // A 2-element array.  First element is 3, second is 7

let matrix = [[1,2,3], [4,5,6], [7,8,9]]; // nested array

let sparseArray = [1,,,,5]; // 3 undefined elements -- omitting a value between commas.

Object Initializer Expr

An object initializer is a comma-separated list of name-value pairs contained within curly braces.

Examples

let p = { x: 2.3, y: -1.2 };  // An object with 2 properties

let q = {};                   // An empty object with no properties

q.x = 2.3; q.y = -1.2;        // Adding properties

let rectangle = {

    upperLeft: { x: 2, y: 2 },

    lowerRight: { x: 4, y: 5 }

};                                                // Nested object

Function Initializer Expr

A function initializer consistsw of keyword "function" followed by a comma-separated list of zero or more identifiers.

* An alternative to function statements or the compact new “arrow function” syntax

Example

let square = function(x) { return x * x; };

Property Access Expr

Evaluates to the value of an object property or an array element.

2 alternatives -- dot or brackets

  • expression . identifier

  • expression [ expression ]

  • identifier specifies the name of the desired property
  • 2nd expression specifies the name of the desired property or the index of the desired array element
  • If the value is null or undefined, the expression throws a TypeError

Example

let o = {x: 1, y: {z: 3}}; // An example object

let a = [o, 4, [5, 6]];    // An example array that contains the object

o.x                        // => 1: property x of expression o

o.y.z                      // => 3: property z of expression o.y

o["x"]                     // => 1: property x of object o

a[1]                       // => 4: element at index 1 of expression a

a[2]["1"]                  // => 6: element at index 1 of expression a[2]

a[0].x                     // => 1: property x of expression a[0]

Conditional Property Access

  • ?. and ?.[]
  • Prevent TypeError: In a regular property access expression using . or [], you get a TypeError if the expression on the left evaluates to null or undefined.
  • Instead you get undefined

Example

a?.b: If a is null or undefined, then the expression evaluates to undefined, If a is some other value, then a?.b evaluates to whatever a.b would evaluate to

Optional Chaining

A chain of property access.

e.g. "a.b.c.d"

  • If a is undefined, or it has no property b, the expr evalues to TypeError
  •  To prevent this, we use ?. or ?[]

Short Circuiting

“optional chaining” is “short-circuiting”: if the subexpression to the left of ?. evaluates to null or undefined, then the entire expression immediately evaluates to undefined without any further property access attempts.

  • Only short circuiting the left of ?.
  • Stop evaluation immediately
  • Return undefined

Example

a?.[b][c] // if the value of a is null or undefined, then the entire expression immediately evaluates to undefined.

a?.[index++]    // => undefined: because a is undefined
index           // => 1: not incremented because ?.[] short-circuits
a[index++]      // !TypeError: can't index undefined.

Function/Method Invocation

f(0)            // f is the function expression; 0 is the argument expression.
Math.max(x,y,z) // Math.max is the function; x, y, and z are the arguments.
a.sort()        // a.sort is the function; there are no arguments.

  • If the value of the function expression is not a function, a TypeError is thrown.
  • Non-return function expr evaluates to undefined

Conditional Invocation

  • ?.()
  • Prevent TypeErrorIf the expression to the left of the parentheses is null or undefined or any other non-function, a TypeError is thrown.
  • Instead you get undefined
  • Supports shortcuting
  • Without conditional invocation, we need to check if a function is defined before using it.

function square(x, log) { // The second argument is an optional function
    if (log) {            // If the optional function is passed
        log(x);           // Invoke it
    }
    return x * x;         // Return the square of the argument
}

  • With conditional invocation

function square(x, log) { // The second argument is an optional function
    log?.(x);             // Call the function if there is one
    return x * x;         // Return the square of the argument
}

Object Creation Expr

new Object()        // syntax
new Point(2,3)     // with arguments

new Date            // without arguments

 类似资料: