comparison on var, let and const variable declaration

let, const and var are keywords used for variable declarations in JavaScript programming language,

const and let were newly introduced to the programming language in Escmascript es6 or es2016.

Declaration keywords
the syntax of declaring a variable using let keyword is done as;

let {variable name} = value

for const it's done as;

const {variable name} = value

similarly with var;

var {variable name} = value

Scope for 'let' and 'const' variables
let and const declared variables are block scoped that means values assigned remain within the block of assignment;
take for instance;

if(true) {
   const declaration = "declared"

console.log(typeof declaration)
// undefined

values remain accessible only within the if block

Scope for 'var' variables
var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example;

function assign(param){
    var assignment = param;


console.log(typeof assignment)
// undefined

Outside the scope of the function type of assignment is 'undefined', within the scope of the function it's a String with the value "assigned"

mutability for 'var' and 'let' variables
variables declared using 'var' and 'let' keyword are mutable therefore can be reassigned with a new value;

var typeofvar = []
      typeofvar = {} // true

let me = 'myself'
      me = 'i' // true

Immutability for 'const' variables
const variables are immutable, they can only be assigned once, for example;

const variable = []
      variable.push(10) // true
      variable = 'string' // "TypeError: Assignment to constant variable"

Redeclarations of 'let' and 'const' variables
const and let declared variables cannot be redeclared within their scope once they are declared any attempt to redeclare them will cause the JavaScript runtime to throw an error;

const name = "John" // true
const name = "duke" //
"SyntaxError: Identifier 'name' has already been declared"

Redeclarations of 'var' variables
variables declared using var can be redeclared at anytime in or outside their scope

var name = "duke" // true
var name = "max" // true
var name = "khloe" // true


Popular posts from this blog

How to make a Snake Game using JavaScript and html5

How to get user's ip address in JavaScript

Adding Gameover and introduction screen on HTML Canvas

JavaScript intro to classes

How to use canvas context rect method for drawing rectangles