Javascript – Declaring Variables in ES6, the differences between var, let, and const – 2020

I wanted to put together this quick blog post for my reference and others on understanding how to declare variables in Javascript, specifically with ES6 (Javascript 2015).

There are three variable types now that you can use with modern Javascript.

var, let, and const

Let me break these down in simple terms.

var was the original and continues to be the original way to define a variable in Javascript.

let – supports global scope and block scope

const – Used for static / immutable variables that you do not want to be changed or redefined overtime or during execution. This variable type will also follow the scope behavior of let.

Examples of the let scope:

let globalLetVar = "This is global scope string";
console.log(globalLetVar); // This can use globalLetVar

function myPrivateVarFunction() {
  // this function can use globalLetVar
  console.log(globalLetVar);
  let privateLetVar = "This is a local block scope string";
  // this function can use privateLetVar INSIDE the function.
  console.log(privateLetVar);

}

//running it:
myPrivateVarFunction();
// Output:
// This is global public string
// This is a private string

//Trying to access to the privateLetVar variable outside the myPrivateVarFunction function:
console.log(privateLetVar); // Uncaught ReferenceError: privateLetVar is not defined

Examples of const:

const a = 'Hello'; 
console.log(a) // 'Hello'
a = 'Bye'; // Uncaught TypeError: Assignment to constant variable.
var a = 'Bye' // Uncaught SyntaxError: Identifier 'a' has already been declared
console.log(a) // 'Hello'

Javascript variable naming rules:

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words such as private, return, static, new, this…cannot be used as names as they are reserved words. You can find a list of more words here private JavaScript keywords

Leave a Reply

You are currently viewing Javascript – Declaring Variables in ES6, the differences between var, let, and const – 2020
The differences between var, let, and const