0

Such as 2[a], whose value is undefined.

The code bellow will get an error Cannot access 'b' before initialization

let a = 1, b = 2
[a, b] = [b, a];

I know it caused by the missing semicolon after the b = 2. And after the semicolon has been added

let a = 1, b = 2;
[a, b] = [b, a];

It works fine. Is it caused by the square bracket after the number? If so, what is the meaning of it in javascript?

1 Answers1

1

Is it caused by the square bracket after the number?

Yes.

If so, what is the meaning of it in javascript?

It's a property access operation, just like:

const array = [1, 2, 3];

const b = array[1];
//             ^^^−−−−−−−−−−−−−−−−−−−−−−−−−

console.log(b); // 2

You can do property access operations on primitives, and in fact you often do. For instance, on a string primitive:

console.log("hi".toUpperCase()); // "HI"

// or

const fiftyFifty = Math.random() < 0.5;
const method = fiftyFifty ? "toUpperCase" : "toLowerCase";

console.log("Hi"[method]()); // "hi" or "HI"

Or using a number primitive:

console.log(2["toString"]()); // "2"

const n = 2;
console.log(n.toString());    // "2"

console.log(2..toString());   // "2"

When you do, the relevant prototype is used (String.prototype, Number.prototype, etc.) and in loose mode in some situations a temporary object is created (e.g., new String("hi") or new Number(2)).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875