JS Scoping, Hoisting and var/let/const

JavaScript (similar to PHP) is a dynamically types scripting language which means, that variables don’t have a fixed variable type.

myvar = 1;
myvar = “Ich bin ein Text”;
myvar = ["Chevrolet", "Ford", "Audi"];

In statically typed languages like Java you can e.g. assign an internger value to a string variable.

Scope

Local Variables

// code here can NOT use carName

function myFunction() {
  var carName = "Ford";
  // code here CAN use carName
}

Global Variables

var carName = "Volvo";

// code here can use carName

function myFunction() {
  // code here can also use carName
}

Hoisting

Hoisting is the “automatic movement of variable definitions to the beginning of the current scope”.

That means the following 2 scripts produce the same result:

x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x
var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

This ONLY happens with variables defined with “var”!
“let” and “const” don’t have this Hoisting behaviour.

Here one more important difference! Hoisting occurs ONLY on the variable definition, not the initialisation with a value.

That means the following 2 scripts produce a different result:

var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y
var x = 5; // Initialize x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

var y = 7; // Initialize y

In the 2 script we don’t get an error due to the fact, that the variable definition is being hoisted to the top, but the value assignment with 7 only happens at the end.

Therefore the 2 script from above is the same as this:

var x = 5; // Initialize x
var y;     // Declare y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

y = 7;    // Assign 7 to y

var vs let & const

With ES6 (ECMAScript 2015) 2 new possibilities how to declare variables have been added.:

let is a mutable variable, const is an immutable variable.

That means a variable defined with let can have different values all the time but a variable defined with const can only have 1 value.

If you try to change an already set const variable you will get an error.

But the main difference between var to let & const is that these 2 are only available in their respective scopes and not “globally”.

Here are some examples with the “old” var system and the “new” let/const system.

var x = 10;
// Here x is 10
{
  var x = 2;
  // Here x is 2
}
// Here x is 2
var x = 10;
// Here x is 10
{
  let x = 2;
  // Here x is 2
}
// Here x is 10

If you define a “global” let variable you will be able to read its value inside functions that are placed on the same scope or inside the corrent scope.

let x = 10;

function myFunc(){
  console.log(x);
}

myFunc();

// Outputs 10

But you are not allowed to “redeclare” x in the myFunc function like:

let x = 10;

function myFunc(){
  console.log(x);
  let x = 2;
  console.log(x);
}

myFunc();
console.log(x);

VM611:4 Uncaught ReferenceError: Cannot access 'x' before initialization
    at myFunc (<anonymous>:4:15)
    at <anonymous>:9:1

You are only allowed to assign new values to it like:

let x = 10;

function myFunc(){
  console.log(x);
  x = 2;
  console.log(x);
}

myFunc();
console.log(x);

// Outputs
10
2
2

This means the scope of a variable is determined when the decleration of the variable is being done and not when or in which scope it is used.

Sources:
https://www.w3schools.com/js/js_scope.asp
https://www.w3schools.com/js/js_hoisting.asp

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.