When using var
, the following code is possible.
The variables declared using var
keyword are hoisted to the top of the function scope:
function myMethod() { console.log(age); var age = 12; } myMethod(); // undefined
This does not throw an error because the Javascript treats it like this:
function myMethod() { var age; console.log(age); age = 12; } myMethod(); // undefined
This is called "hoisting" where the interpreter pulls all variable declarations to the top of its scope.
var
also allows us to use redundant var declarations:
function myMethod() { var age = 16; var age = 26; var age = 36; console.log(age); } myMethod(); // 36