Learning Outcomes - 03 April
var, let and const
For a while now I’ve been using these 3 keywords almost synonymously and I decided to put some time aside to learn the distinction amongst them.
Var
Var was the traditional way used to declare variables in JavaScript.
Properties of var
Function/Window Scoped
If a var is declared in a function, then it will only be accessible in that function and if declared outside the function (in the window), it is accessible throughout the window, including in functions in that window.
var result1
function sum(a, b) {
result1 = a + b
var result2 =. a + b
}
sum(1, 2)
console.log(result1)
console.log(result2)
the output would be:
3
undefined
Allows re-declaration of variables
var x = 10
var x = 12
the above code passes without an errorHoisting
variable declaration is moved before the variable is first accessed and is initialized to ‘undefined’
console.log('name’)
var name = “Emmanuel“
The above is interpreted as:
var name = undefined
console.log(name)
name = “Emmanuel“
Therefore this will log `undefined` rather than a syntax error (Uninitialized constant) thrown by other languages.
Problem with var
Since variables can be redeclared, you may not know that you are redeclaring/(redefining) a variable in the program and this may cause unwanted output (bugs).
let and const come in to solve the problem. They were introduced in ES6
let
properties of let
block scoped
a block of code is code between curly braces.
No redeclarations
let x = 10
let x = 12
the above code will throw an errorHoisting
Unlike var, variable declarations are also moved before the variable is accessed but not initialised.console.log('name’)
var name = “Emmanuel“
the above code is interpreted as:
let name
console.log('name’)
name = “Emmanuel“
const
properties of const
block scoped
just like letHoisted
just like let
No redeclaration nor updates
like let is can’t be re-declared, but const also cannot be updated.
const age = 12
age = 13
the above code will throw an error.
Therefore, const should be initialized on the declaration.
however, properties of const objects can be updated.const user = { name : “”Emmanuel }
user = { last name : “Omona” } // not permitted
user.name = “Omona” // permitted