Hoisting, mutability and scope
Understanding the differences between the const, let and var keywords in javascript

By codeitadmin April 12, 2018 • Posted in: Bash Scripting, ES6, javascript, Programming Concepts, Uncategorized

Required Knowledge

To understand the difference between the keywords const, let and var and their applications in javascript programming, there are three principles you must grasp.

Immutability

In the simplest terms, an immutable value is one that cannot be changed after it is declared. By contrast mutable values may be changed at any point in a programs lifecycle.

Scope

You can think of Scope in Javascript as the lifetime of a variable. There are two types of scope in Javascript: global and local scope

The code below shows an example of both global and local (function) scope


var outside = 'I am in the global scope';
// This variable is in the global scope. We can access it anywhere within our script

function fence() {
    console.log(outside);
    // The outside variable is accessible inside the fence function
    var inside = 'I am in the local scope, I can\t be accessed outside the fence';
    console.log(inside);
    // the inside variable is available only inside the fence function
}
console.log(inside);
// attempting to access the inside variable out side of the fence function will result in an error
fence();

Global Scope

Globally scoped variables are accessible throughout the script. The first variable, outside, is declared in the global scope. Notice we are able to access it from both inside and outside the function fence().

Local Scope

Local scope refers to variables that can only be accessed from the scope in which they are declared. There are two types of local scope in JS — function scope and block scope

Function scope

Originally, in Javascript, variables were all scoped either globally or to the function that contained them. The variable inside, declared within the fence() function illustrates functional scoping, Notice we are able to access the variable from within the function, but calling it from outside the function results in an error

Block Scope

Block scope allows for even more fine grained control over the availability of variables, by limiting variable usage to the containing block.

It should also be noted that variables declared in any scope will be available to that scope’s children. 

Hoisting

In Javascript when we declare a variable using the var keyword, the declaration will be be moved to the top of the current execution scope at runtime, before any other code is executed.

To see this in action, try running the following


    mcbane_says = 'My eyez! The goggles do nauthing!.....';
    console.log(mcbane_says);
    var mcbane_says = 'rubber baby tuggy bumpers';

As a side note if you don’t alter the value of a hoisted variable prior to use, it will return undefined. Scotch.io has a really good article that explains in this more depth.


console.log(mcbane_says);
var mcbane_says = 'rubber baby tuggy bumpers';<

Understanding the var, const and let keywords and how they function

The Var Keyword

The var keyword is the classic way of creating variables in Javascript. Variables declared using var are mutable, function or global scoped variables. Variables declared with var will be hoisted.

The const Keyword

The const keyword is used to denote an immutable value.

Running the following code will throw an error because we attempted to alter the value.


const young_gunz = 'Can\'t Stop';
young_gunz = 'Won\'t Stop';

Javascript treats constants a little different than some languages. In Javascript, it is not that the value that must remain constant, but the binding. So, for example, if we create a constant submit_btn, and assign a DOM object, we can still alter it’s properties without getting an error.

for example:


// When storing a DOM object as a constant
const submit_btn = document.getElementById('#submit_btn');

// We can still alter properties like this
submit_btn.value = 'Submit Me'

//But trying to assign a different object to submit_btn will cause an error
submit_btn = document.getElementById('#submit_btn');

Constants are block scope

 

The Let Keyword

ES6 also introduced the let keyword.

Unlike the var keyword which is scoped only to a function or the global window object, the let keyword declares a mutable value that is scoped to whatever block it is enclosed in. In addition to functions, this allows to create variables that are scoped to if/else statements, loops and more.

Let’s look at a couple of examples, to illustrate this better

Ex 1: using var inside of for loop


let elements = [];
for(let i = 0; i<10; i++) {
    let link = document.createElement('a');
    // Here we are declaring the destination url using the var keyword
    var destination = `https://somesite.io/?q=${i}`;
    link.src = destination;
    elements.push(link);
}
console.log(elements);
// and here, if we print the value of destination, we see that it prints the value as it was set in the last iteration of our loop
console.log(destination);

Ex 2 using let inside of for loop


let elements = [];
for(let i = 0; i<10; i++) {
    let link = document.createElement('a');
    // this time we declare the destination url using the let keyword
    let destination = `https://somesite.io/?q=${i}`;
    link.src = destination;
    elements.push(link);
}
console.log(elements);
// now when we try to log the contents of destination, we get an error
// ReferenceError: destination is not defined
console.log(destination);

The let keyword is pretty useful to avoid naming collisions, and to ensure that a given variable contains the expected value at any given time.

So which should I use?

In most cases if you know a binding is not going to change, or if you are unsure, use const. If you discover later that the variable needs to change, change the declaration to use let. Generally speaking, post ES5, var should only be used if  you have a compelling reason. Using let, in place of var, will help protect against naming collisions and reduce the complexity of your code, it also allows to scope to the current block, which   

comments

add comment

Your comment will be revised by the site if needed.