What does the square bracket after the number mean in javascript? [duplicate] - javascript

This question already has answers here:
Why is a semicolon needed here? [duplicate]
(1 answer)
Interesting error based on automatic semicolon insertion JS rules. Explanation required
(2 answers)
Use of semicolons in ES6 [duplicate]
(1 answer)
Closed 2 years ago.
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?

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)).

Related

Destructing assignment to swap the values in ES6

I am revising JavaScript and came to following ES6 example.
let a = 8, b = 6;
// change code below this line
[a,b] = [b,a];
// change code above this line
console.log(a); // a is 6
console.log(b); // b is 8
Not able to figure out how this is working, as we have assignment operator with both side arrays.
Destructuring basically separates an array or an object into separate variables. That is what happens on the left side. Exemple:
var foo = [1, 2]
var [a, b] = foo; // creates new variables a and b with values from the array foo
console.log(a); // prints "1"
console.log(b); // prints "2"
On the right side, you are creating an array with the values [b, a] which will be destructured. As a result, the two variables are switched.

Unexpected Javascript array behavior [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 3 years ago.
I signed the variable bubbleL1 to 1, but why the first variable in the bubbles list, which is bubbleL1 still shows undefined? I know this maybe a stupid question, but I really don't know why.
let bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3;
let bubbles = [bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3];
bubbleL1 = 1;
console.log(bubbleL1) // 1
console.log(bubbles) // [undefined, undefined, undefined, undefined, undefined, undefined]
What I want is a list with a specific name for each item in it (for the declared reason, I really don't just use bubbles[0], bubbles[1]...)
Let's say we have a list named bubbles, and we also have six variables called bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3. I want to put all these six variables into the bubbles list, so later I can assign values to each variables that in the list, like this:
bubbles.forEach((bubble) => {
bubble = "something";
})
bubbleL1 is a primitive and therefore copied by value.
let x = 3;
let sum = x;
sum = 3 + 5;
console.log(x); // 3
Objects and arrays, on the other hand, will exhibit your expected copy-by-ref behavior:
let x = {a: 3};
let sum = x;
sum.a = 3 + 5;
console.log(x.a); // 8

Why is there a relationship between copied arrays? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 3 years ago.
I need some help understand why a relationship is created between arrays when I replicate an array by reference. Take the following example:
let a = [1,2,3];
let b = a;
b.push(4);
console.log(b); // [1,2,3,4]
console.log(a); // [1,2,3,4]
a === b; // true
For some reason, {a} changes when I modify {b}, when I expected them to be independant arrays.
This kind of relationship is not true for variables, it appears. Take the following example:
let a = 'test';
let b = a;
b = 'test1';
console.log(b); // "test1"
console.log(a); // "test"
a === b; // false
Does anyone know the reasoning behind the behavior for arrays?
Arrays are copied by reference so when you write:
let b = a;
You are referencing a in b.
The correct way:
let b = [...a]
or
let b = a.slice(0);

How to set one variable to another in same line without globalizing [duplicate]

This question already has answers here:
Assign two variables to the same value with one expression? [duplicate]
(5 answers)
Closed 4 years ago.
In this situation:
(function() {
const a = b = 10;
})();
console.log('a:', a); // ReferenceError: a is not defined
console.log('b:', b); // 10
The b gets defined as a var in the global scope. Is it possible o do this equals trick but make b a const as well in the same scope? Just like a?
You could set b as a parameter to your IIFE function. That way b won't be accessible outside of function scope.
(function(b) {
const a = b = 10;
console.log(b)
})();
console.log('b:', b);
I don't think so. This "trick" is possible because b = 10 returns 10. However, const b = 10 returns undefined.
Why not just use:
const a = 10;
const b = a;
?
It's not slower, and it's more readable, even if you could nest the assignments I don't really see a reason to do it

how does this two varibles exchange using one line? [duplicate]

This question already has answers here:
How does [b][b = a,0] swap between a and b?
(2 answers)
Closed 9 years ago.
I do not know how to learn demo 2,because it's difficult for me.
//demo1.js
var a = 1;
var b = 2;
var c;
c = b;
b = a;
a = c;
log(a); // a = 2
log(b); // b = 1 I can read this one.
//demo 2.js
var a = 1, b = 2;
a = [b][b = a, 0]; // why? '0' is a varible?
console.log(a,b) //output a = 2, b =1
// v---- 1. v---- 3.
a = [b][b = a, 0];
// ^---^-- 2.
Put the value of the b variable in a new Array.
The next set of square brackets is the member operator used for getting the index. In this case, that space is being used to reassign the value of the a variable to the b variable. This can be done because the original value of b is safely in the Array (from step 1.).
Separated by comma operator, the 0 index is then used as the actual value of the Array being retrieved, which if you'll recall is the original b value. This is then assigned to a via the first = assignment on the line.
So to summarize, b is put in the Array, and is retrieved via the 0 index and assigned to a on the left, but not before a is assigned to b (borrowing the space of the [] member operator).
This could also be written like this:
a = [b, b = a][0];
Only difference now is that the second index of the Array is used to do the assignment. Probably a little clearer like this.
The comma operator in Javascript evaluates its left operand, throws it away and returns its right operand after evaluating. Its only use is when the left operand has a side-effect (like modifying a variable's value) but you don't want its result.
[b] defines an array containing b.
[b = a, 0] evaluates b = a - so b now contains the value of a. Then it throws it away. Then it takes the element at index 0 of [b] - returning b. a now contains the value of b that was stored there, rather than the up-to-date value of b, so our swap is successful (albeit obfuscated).

Categories

Resources