I can\'t understand why variables act so strange when declared inside a function.
In the first
function I declare with let
the variabl
Here are the 3 interesting aspects of variable declarations in JavaScript:
var restricts the scope of variable to the block in which it is defined. ('var' is for local scope.)
let allows temporary overriding of an external variable's value inside a block.
Simply declaring a variable without var or let will make the variable global, regardless of where it is declared.
Here is a demo of let, which is the latest addition to the language:
// File name: let_demo.js
function first() {
a = b = 10
console.log("First function: a = " + a)
console.log("First function: a + b = " + (a + b))
}
function second() {
let a = 5
console.log("Second function: a = " + a)
console.log("Second function: a + b = " + (a + b))
}
first()
second()
console.log("Global: a = " + a)
console.log("Global: a + b = " + (a + b))
Output:
$ node let_demo.js First function: a = 10 First function: a + b = 20 Second function: a = 5 Second function: a + b = 15 Global: a = 10 Global: a + b = 20
Explanation:
The variables a and b were delcared inside 'first()', without var or let keywords.
Therefore, a and b are global, and hence, are accessible throughout the program.
In function named 'second', the statement 'let a = 5' temporarily sets the value of 'a' to '5', within the scope of the function only.
Outside the scope of 'second()', I.E., in the global scope, the value of 'a' will be as defined earlier.