What happens if a JavaScript variable is re-initialized? - javascript

I'm new to javascript and I'm not sure if there is anything called re-initialization in javascript, so please excuse if there is no such concept.
What happens if a javascript variable is re-initialized?
Ex:
function foo()
{
var x = 10;
.... //do something
.... //do something
.... //do something
var x = 20;
console.log("x: " + x);
}
What would be the value of x here?

x will be 20. var is "hoisted" (more below), which means that the variable gets declared as of the beginning of the function, before any step-by-step code is run. Any initializer on a var statement is actually just an assignment statement.
So your code:
function foo() {
var x = 10;
//do something
var x = 20;
console.log("x: " + x);
}
is treated as though it were like this:
function foo() {
var x;
x = 10;
//do something
x = 20;
console.log("x: " + x);
}
When you call a function, the JavaScript engine does several things before it starts executing the step-by-step code in the question. one of the things it does is look through the code and process any var statements. (Although it's called the var statement, var is more of a declaration.)
It's quite fun, your code could also be written this way:
function foo() {
x = 10;
//do something
x = 20;
console.log("x: " + x);
return;
var x;
}
It would still be valid, and it would do exactly the same thing.
More (on my blog): Poor, misunderstood var
ES6 will introduce let, which behaves differently (amongst other things, it is scoped to the block it's in, whereas var is scoped to the function as a whole even if declared within a block); details on MDN.

The var keyword essentially just determines the scope of the variable and is handled before any of the code is actually executed (look up "hoisting"). Using var twice for the variable is redundant, but doesn't really do anything in particular. In the end you're just assigning 10 to x and later you assign 20 to x; nothing more, nothing less.

You can always run simple test to check that. var means it's this variable is in current scope. So in your example x will be equal to 20
var x = 10;
var x = 20;
var y = 10;
function Test() {
var x = 30;
y = 20;
alert('X in function: ' + x);
alert('Y is global, so it\'s ' + y);
}
Test();
alert('X outside of function: ' + x + ', also Y = ' + y);

Related

Javascript and Hoisting

In my code, the x value is undefined. If I remove if block, the x value is displayed as 77. I don't understand why if block is modifying the x value.
var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x);
}
fn();
var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x); // undefind
}
fn();
In the intermediate phase, x will be hoisted to its scope:
var x = 77;
function fn() {
//var x = undefind; intermediate phase
if (false) {
var x = 55;
}
console.log(x);
}
fn();
var x = 77;
function fn() {
if (false) {
x = 55;
}
console.log(x); // 77
}
fn();
The x variable is redeclared and hoisted inside the function, but never set because if (false) will never be reached thus undefined. The outer x is known inside the function if you remove the inner declaration.
This can be solved by using const or let (ES6) instead of var. const and let is not hoisted and lives only inside of the brackets they are declared:
const x = 77;
function fn() {
if (false) {
const x = 55;
}
console.log(x); // 77
}
fn()
Another solution is to just use two different variable names or remove the var inside the if statement depending on your needs...
Inside the scope of the function, the variable x is hoisted to the top as follows var x; If you print it, you get undefined. It is never assigned a variable as it is not going inside the if block
Simply remove the var inside the if-statement. That will fix the hoisting issue.
var x = 77;
function fn() {
if(false) {
x = 55;
}
console.log(x); // 77
}
fn();
You can also use let keyword.
let x = 77;
function fn() {
if (false) {
let x = 55;
}
console.log(x); // 77
}
fn()
one should use wither ES6 define syntax const OR let while assigning the variable, if needs to mutate the variable then use let, otherwise use const , stop using var .
In your scenario while using var there, it means you are trying to re initialize the x, it gets hoisted
var x = 77; means
var x; outside the block.
So one should not need to re initialize the x just pass the value or either use let or const .
function fn() {
if (false) {
//
x = 55;
}
console.log(x);
}
fn();

JavaScript var keyword: redefining a variable's value inside a closure

What am I missing here? This behaves as expected:
var x = 1;
(function(){
// x === 1
})();
But,
var x = 1;
(function(){
var x = x;
// x is undefined
})();
I would think that x should be 1. It seems as though the var x = x nukes the value of x before it is assigned. Is this a bug? This doesn't seem very intuitive.
Was this behavior changed? I remember doing something like this in the past.
For reference:
var x = 1;
(function(){
var y = x;
// y === 1
})();
And:
var x = 1;
(function(){
x = x;
// x === 1
})();
var x = 1;
(function(){
var x = x;
})();
After variable hoisting becomes:
var x = 1;
(function(){
var x;
x = x;
})();
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
That's why sometimes in plugins you see code like
var i,j,abc, d;
//code
In you example, the code is transformed like this:
function() {
var x;
x = x;
}
The example with function arguments is different, you just change the function argument itself and the var declaration is ignored.
If a scoped variable is declared with let, it will only move up to the beginning of that scope and not of the function, so this code works:
var x = 1;
(function(){
var y = x;
{
let x = y;
console.log(x);
}
})();
As pointed out, it's a new feature, so not supported everywhere.
And finally, here:
var x = 1;
(function(){
x = x;
// x === 1
})();
You do not declare x locally, so if you edit it, it'll also edit it at global scope.
In JavaScript all variables declared in global scope or in scope of whole function where it declared. Consider example:
var x = 1;
function f()
{
console.log(x);
if (true) {
var x;
}
}
f();
This is weird programming language design but this code also prints "undefined" because of this rule.
Everytime you type var you are reassigning a new variable. When you just reference x inside the function it looks up to the assignment statement above.
function f(){
var x = x; //this tries to reassign var x to undefined.
}
what you are doing here is setting x as a global variable and then setting it to reference itself, overwriting the 1, making x => x which would be undefined.

about a javascript scope issues. why the result is undifined

I want to know why alert x is a 'undifined', why is not 10.
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
var x = 20;
foo.call(); //10
})();
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
// var x = 20; // Comment this variable
foo.call(); //10
})();
when you define variable name x and assign some value then this function is call and in all other alert you define as like window, this but when you give alert only x then in jquery it will not able to which x you want alert
and in jquery window.x it will take that first x value same in first function "foo" but in second function where x is define after alert so alert is undefined
if you give alert on x then it will give undefined because you also define same variable after alert in that function
This caused because of a feature of javascript called variable hoisting link.
So when the interpreter is interpreting your code, this occurs at runtime.
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
var x;
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
x = 20;
foo.call(); //10
})();
As you can see from above, the variable declaration var x is moved to the top leaving the assignment. Therefore, when you call alert("x---" + x) the variable x is not yet defined.

Colon operator ":" before function call (javascript)

I was looking at the source to a website and I saw this strange href attribute in a link and I can't figure out what it's doing. It doesn't look like valid javascript. I thought maybe the colon operator here was being used as a way to access the function property popDocWin in the object javascript but when I tried to emulate that syntax on a test function it wouldn't work.
Exterior Adjustable
javascript: is a psuedo-protocol meaning "run the code following this." You can use it (in a browser context) anywhere a URL is valid. In this case, clicking the link "follows" the link, and the act of following the link runs the JavaScript rather than going anywhere. (This is also how bookmarklets work.) So the javascript: part of that isn't JavaScript, just the part after it.
However, something that looks like that is valid JavaScript: If it weren't in a URL, it would create a labelled statement. The primary use of labelled statements in JavaScript is breaking outer loops from within inner ones, like this:
var x, y;
outer: for (x = 0; x < 5; ++x) {
for (y = 0; y < 5; ++y) {
if (x === 2 && y === 3) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
Output:
x = 0, y = 0
x = 0, y = 1
x = 0, y = 2
x = 1, y = 0
Note how the x loop was terminated from within the y loop.
var snippet = {
show: function(msg) {
document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>");
}
};
var x, y;
outer: for (x = 0; x < 3; ++x) {
for (y = 0; y < 3; ++y) {
if (x === 1 && y === 1) {
break outer;
}
snippet.show("x = " + x + ", y = " + y);
}
}
The colon is not before the function call, its after the word javascript!
It is telling your browser it should execute the javasript code after the colon.
Well, href isn't a place where your browser would expect javascript code, so javascript: tells the browser that it should treat whatever is after it as javascript.

var x, y = 'foo'; Can this be accomplished?

Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;

Categories

Resources