Var, const, let,null, and undefined A quick intro to variables in JavaScript
A quick history of scope
The old way to declare vars (in ES5) was use the keyword var which has function scope (a precursor to block scope). Block scope came to existence with the introduction of the let and const keywords in ECMA script 6. Global scope (using no keyword) still works the same in both ES5 and ES6.
A simple example of block scoping
const and let are block scoped, which means you can have multiple variables with the same name, as long as they are within their own set of parentheses. Look at this simple example:
let a=1;
{
let a=5;
let b=2;
console.log(‘A= ‘+a) //A= 5
console.log(‘B= ‘+b) //B= 2
}
console.log(‘outside A= ‘+a) //outside A= 1
//b is undefined outside the parentheses because isn't declared
Note that global vars can be declared inside or outside a block, and they will still exist after the block (or loop) ends.
Const- Can’t be reassigned, but it can be changed
const c=[2]
//c=3 //throws an error because you cant re-assign a const var
console.log(‘c is: ‘+c)//but you can mutate it…for example:
c.push(3)console.log(‘c is: ‘+c)
Null vs Undefined
Undefined vars have been instantiated (aka declared) but haven’t been given a value (aka assigned).
let d;
console.log(‘d=‘+d) //d= undefined
A variable is null when it has been assigned the absence of a value (aka a null). Some function calls in JavaScript return null For example the match function attempts to match characters in a string and when there are no valid matches returns null.
let e=’no exclamation here’.match(/!/)
console.log(‘e= ‘+e)//e= null