var vs let
introduction to the `let` keyword for declaring block-scoped variables; and the dangers of scoping, such as the temporal dead zone
Variables declared with var
have function scope. This means that they are accessible inside the function/block they are defined in. Take a look at the following code:
Node.js
var guessMe = 2;console.log("guessMe: "+guessMe);// A: guessMe is 2( function() {console.log("guessMe: "+guessMe);// B: guessMe is undefinedvar guessMe = 5;console.log("guessMe: "+guessMe);// C: guessMe is 5} )();console.log("guessMe: "+guessMe);// D: guessMe is 2
Comment B
may surprise you if you have not heard of hoisting.
If a variable is declared using var inside a function, the Javascript engine treats them as if they are declared at the top of a functional scope. However, ...