Let us talk about one of the surprising behaviors of Javascript.
Do you know that the unusual thing about variables in JavaScript is that you can refer to a variable declared later in the code, without getting an exception!!!
Yes you can...
This concept is known as hoisting. variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.
Do you know that the unusual thing about variables in JavaScript is that you can refer to a variable declared later in the code, without getting an exception!!!
Yes you can...
This concept is known as hoisting. variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.
console.log(x === undefined); // logs "true"
var x = 3;
var x = 3;
The above example will be interpreted same as:
var x;
console.log(x === undefined); // logs "true"
x = 3;
console.log(x === undefined); // logs "true"
x = 3;
Now look at the following code snippet, how many times do you think the code will alert "hello"?
var foo = "hello";
function fxn() {
alert(foo);
var foo = "bai";
}
fxn();
alert(foo);
function fxn() {
alert(foo);
var foo = "bai";
}
fxn();
alert(foo);
The answer is only once.
This code first alerts undefined then hello.
Remember that var statements are hoisted in Javascript. As I have already mentioned that variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement.
If a function anywhere inside has a var statement any variables with the same name in a higher scope will be shadowed (unaccessable,unless of course you change the variables name on the inside). Once inside the function 'foo' is defined inside and marked as undefined. When it hits the alert it still isn't defined. The next statement assigns foo to 'bai'.
The above example will be interpreted the same as:
var foo = "hello";
function fxn() {
var foo; //same name variable declared but it is not initialized
alert(foo); //local variable foo shadows the global variable
foo = "bai";
}
fxn();
alert(foo);
function fxn() {
var foo; //same name variable declared but it is not initialized
alert(foo); //local variable foo shadows the global variable
foo = "bai";
}
fxn();
alert(foo);