In which order are variables assigned in Javascript? - javascript

Apparently this is identical in my Firebug console:
var x = "A", y = x;
x + y === "AA";
and
var x = y, y = "A";
x + y === "AA";
Is this standard ECMAScript behaviour, that the order doesn't play a role in comma-separated var assignments?
Edit: The "mystery" is solved. I tested the first example first, then cleared the console and ran the second. However, at this time, y and x were already defined. If you run the JSFiddle provided by David Thomas you always get an "undefinedA". Case settled.

var x = y; will raise an exception if y is not defined.
However, the window object is the default context for Javascript interpreters embedded in browsers. If you previously issued:
y = "A";
Then you actually assigned "A" to window.y, therefore var x = y; becomes valid and assigns window.y to x.

Related

Quick noob question about variables in JavaScript

Stupid question,
but if I have code like this:
var x;
var y;
var z = x + y;
And then through the program I update the variables for x and y, but when I use the console to check var z, it gives me NaN. So the program is doing that calculation once at the beginning and not updating Z as it continues. So what's the solution to keep checking Z for the variable changes? Do I have to do a loop with setInterval to keep checking the new updated Z variable? Thanks
Yeah, your comment is right. JavaScript doesn't provide a way to create a live binging.
So what's the solution to keep checking Z for the variable changes?
All depends on what you are trying to do.
What you think about the code:
var x = 1;
var y = 2;
var z = x + y;
console.log("The value of z variable: ", z);
PS. Preferably you should use let:
let x = 1;
let y = 2;
let z = x + y;
console.log("The value of z variable: ", z);

Javascript replace/modify the object that a variable points to?

I have a variable pointing to an object and would like to replace that object with another modified one. Is there any Javascript function that can do what my hypothetical "assign" function does in the example console session below?
var x = [[1,2,3], [4,[8,2,[1,4,"Delete Me"],4],6]]
var y = getSubArrayWithString(x) // Equivalent to y = x[1][1][2] in this case
JSON.stringify(y)
>>> "[1,4,"Delete Me"]"
var newY = y.filter(item => item !== "Delete Me")
y.assign(newY) // Equivalent to x[1][1][2] = newY
JSON.stringify(x)
>>> "[[1,2,3],[4,[8,2,[1,4],4],6]]"
If I do y = newY that just reassigns the y variable to point at the newY object, it doesn't modify x.
I know I could modify y in place using splice, but that won't work when I'm applying more complex changes to get newY
Ideally getSubArrayWithString() would return a reference to the parent of the array you are interested in modifying (and maybe even the index you want). Then it's easy:
var x = [[1,2,3], [4,[8,2,[1,4,"Delete Me"],4],6]]
var [y, ind] = [x[1][1], 2] // getSubArrayWithString returns parent and index
y[ind] = y[ind].filter(item => item !== "Delete Me")
console.log(x)
If your really stuck with just the array reference, you can use splice() to alter the array rather than overwrite it. You could even splice() everything and reassign the new values, but this seems pretty inefficient:
var x = [[1,2,3], [4,[8,2,[1,4,"Delete Me"],4],6]]
var y = x[1][1][2]
var newY = y.filter(item => item !== "Delete Me")
y.splice(0,y.length) // sketchy, but works
Object.assign(y, newY)
console.log(x)

Why doesn't this for loop read this in passed argument properly?

Below is my code
function generateGrid(spacing, boundBox, geometry) {
console.log(spacing);
console.log(boundBox);
var grid = [];
console.log(spacing);
for (var x = boundBox[0]; x < boundBox[2]; x = x + spacing) {
for (var y = boundBox[1]; y < boundBox[3]; y = y + spacing) {
if(geometry.intersectsCoordinate([x, y])) grid.push([x, y]);
console.log(boundBox[3] - y)
}
console.log(boundBox[1] - x)
}
console.log(grid);
}
If spacing is replaced by a number like 10000 the for loop executes fine.
From your Console screenshot it looks like the passed in argument is the string "10000" rather than the number 10000.
Either check the code that's calling your function, or convert to an integer inside the function, for example by using parseInt(spacing).
As a tip to help with spotting any similar issues in the future, Chrome's console.log shows numeric values in blue and string values in black.
x is a number so use String(x) so you use operator + between two strings, that would give you "15" + "1" = "151", but that is probably not what you wanted

Scope of variables in functions using javascript

Why the y is leaked outside the function as scope in JavaScript are bound to functions.
A detailed explanation would be fruitful.
var x = 0;
function f(){
var x = y = 1; // x is declared locally. y is not!
};
f();
console.log(x, y); // 0, 1
It's just syntax error.
The line var x = y = 1; Means:
Declare local variable x,
y = 1,
Declare global variable y (since it's not declared)
x = y;
Replace
var x = y = 1;
with
var x = 1, y = 1;
or
var x = 1;
var y = 1;
and you will get local variable y
http://www.w3schools.com/js/js_variables.asp
The reason the y variable is global is that in Javascript if you omit the var keyword from an assignment statement, the variable the value is assigned to is declared on the global object.
That means that if you wrote the f() function this way, declaring both x and y with the var keyword:
function f(){
var x, y;
x = y = 1;
};
Then both x and y would be local variables (local x shadowing the global one).
It's bad practice to assign a variable without declaring it (with the var keyword).
New versions of JS will throw an error on this. You can use EC5's strict mode to take advantage of this behavior:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
so you'd write your function this way:
function f(){
'use strict'
var x, y;
x = y = 1;
};
now if you forget to declare y you get an error yelling at you to do so.

Is variable updated "by reference"?

I have the following simple script.
<script>
SPC = {
a : [10],
b : 10,
t: function()
{
y = this.a;
z = this.b;
y[0]++;
z++;
alert('this.a[0] = ' + this.a[0] + '\nthis.b = ' + this.b)
}
}
SPC.t();
SPC.t();
</script>
Running it in your browser will display two alert boxes with:
this.a[0] = 11
this.b = 10
and
this.a[0] = 12
this.b = 10
The question is, why does the value of this.a[0] increment? I'm assigning "y = this.a" and updating element of "y" as "y[0]++;"?
At the same time, exactly the same thing is happening with "b": "z = this.b; z++". Yet, "this.b" remains equal to 10.
How can I change value of "y[0]" in the local scope without affecting "this.a"?
Any ideas?
Thanks!
a is an array, and you're simply copying a reference to the array into y. You need to copy the array a's contents into a new array y instead (using Array.slice() (y = a.slice() in your case) is the easiest way).
(Or, if you only need a[0], you can set y = a[0]. Subsequent changes to y will not affect a[0], since you are copying the value.)
See the "Javascript Arrays Are Assigned By Reference" and "Passing Arrays As Values" sections of this article for more information.
Try Array.slice() function.
y = this.a.slice()
This will create a copy of a array and assign it to y. So modification of y won't affect a.
you are assigning the address value of array a and b into y and z.
therefore, y, and z become the exact copy of a and b.
instead of assigning address value into y and z.
you just need to take content value of a and b and assign them into y and z
y = a[0]
z = b[0]
and then y++

Categories

Resources