Variables have what is called a "scope". It indicates the visibility
of the variable.
If a variable is created outside a function, it can be seen globally
from anywhere in the script. It is called
a
global
variable. Variable j is a global variable.
var j;
function myFunc(){
j = 0; // this is valid
}
j = 1; // this is also valid
If a variable is created as part of a function (either as an
argument/parameter or inside a function), or more generally within a
code segment indicated by curley brackets { }, the variable can only
be seen inside the function or the code segment inbetween the curley
brackets{ } and it takes precedent over global variables. These are
called
local
variables. Variable i is a local variable and can be
seen (accessed) only from within the function.
function myFunc(){
var i; // variable i can be accessed only within the function
i = 0;
}
i = 1; // this is NOT valid
let is block-scoped - it is only accessible within the block (like an if or for statement) where it's defined.
if (true) {
let message;
message = "Hello from inside the block!";
console.log(message); // This works and logs: "Hello from inside the block!"
}
console.log(message); // This will throw an error: "ReferenceError: message is not defined"
// Also, isn't let easier to read?
// let message = "Hello from inside the block!"