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);
Related
This question already has answers here:
Return multiple values in JavaScript?
(20 answers)
JavaScript: How do I return two values from a function and call those two variables in another function?
(9 answers)
Object destructuring without var, let or const
(4 answers)
Closed 1 year ago.
I need to reassign the value of two differents variables. My code is like this:
const func = () => {
do something;
return {a, b}
}
Then I declare the two variables outside a if/else block with let :
let a = b = '';
And in the if/else i need to assign to the two variables the value returned form the function:
if(condition) {
a, b = func();
}
How can i reassign the value returned from the function to the variables?
You simply need to add parentheses around the assignment to have it parse as an expression rather than a block. MDN gives this example:
let a, b;
({a, b} = {a: 1, b: 2});
So in your case you would need
// For example
let a, b;
const func = () => ({a: 1, b: 2});
({a, b} = func());
You are mentioning errors, we don't see that, please make https://stackoverflow.com/help/minimal-reproducible-example for next time.
This is how it can be done:
const func = () => {
return ["a", "b"]
}
let a, b
if (true) {
const res = func()
a = res[0]
b = res[1]
console.log(a)
console.log(b)
}
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)).
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
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
This question already has answers here:
Javascript a=b=c statements
(6 answers)
Closed 9 years ago.
I saw this code somewhere, but what does it mean? (all a, b, c are defined previously)
var a = b = c;
It quickly assigns multiple variables to a single value.
In your example, a and b are now equal set to the value of c.
It's also often used for a mass assign of null to clean up.
a = b = c = d = null;
Assign c to b.
Assign b to a.
So if I say var a = b = 1;
>>> var a = b = 1;
undefined
>>> a
1
>>> b
1
This means a, b and c are the same reference.
For example:
var c = {hello: "world"};
var a = b = c;
// now all three variables are the same object
It's a shorthand for:
var a;
var b;
b=c;
a=b;
It's meant as a combination of assigning the same value to two or more other variables, and declaring these variables in local scope at the same time.
You can also use this syntax independently of the var declaration:
var a;
var b;
a=b=c;