Understanding Variables (var, let, const) - in JavaScript

Understanding Variables (var, let, const) - in JavaScript
- 5th Mar, 2020 | 9min read

Variables are the very basic thing of any programming language to start with, and one of the first and most important things to learn. In JavaScript, there are three ways to declare any variable - with the keywords var (default), let, and const.

Earlier we have only one keyword var but ECMAScript 2015 (ES6) introduced two new keywords let and const to declare a variable

In this article, we will learn what variables are, how to name and declare them, their scope, and finally the difference between var, let, and const.

A little overview :

  • var and let - Variables that we can read and modify, with some differences between them
  • const - As name suggests, constant variables that can be readOnly, once assigned any value

Understanding Variables

A variable is a unique named container used for storing values for later logical use, either by accessing or modifying its value by calling variable names anywhere within the code.

Syntax : keyword variableName = variableValue

// Example
var name = 'Rahul'

JavaScript variables can hold many data types like : string, number, boolean, object, function, null, undefined

// Assigning various data types to variables
var name = 'Anny'
var totalMarks = 200
var pass = true
var topics = ['A', 'B', 'C']
var marks = { A:80, B:60, C:60}
var task = function(){alert('task done !')}
var nothing = null
var xyz = undefined

Using console.log, we can see the current value stored in a specific variable on console.

totalMarks = 220        // calling the variable and modifying it

// Accessing the variables
console.log(totalMarks)
console.log(name)
220
Anny

Naming Variables

Variable names are also known as identifiers in JavaScript. Below are some of the rules that must be followed.

  • Variable names can consist of letters (a-z), numbers (0-9), a dollar sign symbol ($), and an underscore (_)
  • Variable names cannot begin with a number
  • Variable names cannot be any reserved keywords (like JavaScript keywords)
  • Variable names are case sensitive (y and Y are two different variables)

JavaScript also has the convention of using camel-case (sometimes referred as camelCase) which is the practice of writing the first word lowercase, and all following words capitalized. So, that it's easy to read big variable names like: helloWorld, studyBook, firstName, likeYouAndMe

Declaration and Initialization

In JavaScript, we can declare variable using one of the three keyword from var, let and const.

when declaring a variable

  • Initialization of variables with keyword var and let are optional (default value undefined)
  • Initialization of variables with keyword const is must and required
var v
console.log('var keyword variable value : '+ v)
let l
console.log('let keyword variable value : '+ l)
const c = 12
console.log('const keyword variable value : '+ c)
var keyword variable value : undefined
let keyword variable value : undefined
const keyword variable value : 12
const c
console.log('const keyword variable value : '+ c)
SyntaxError: missing = in const declaration

Scope

Scope determines the accessibility lifetime/boundary of variables within JavaScript code.

The two types of scope are :

  • Global scope - Contains global variables which are declared outside of a block
  • Local scope - Further divided into functional-scope and block-scope

    • Functional scope - contains local variables which are declared inside a function and accessible only within its direct parent function
    • Block scope - contains local variables which are declared inside a block and accessible only within its direct parent block

Remember! Local variables are always preferred over global variables when variable names are same

Global Scope

Contains global variables which are declared outside of a block

// Initialize few global variables
var v = 'I am a global variable with var keyword'
let l = 'I am a global variable with let keyword'
const c = 'I am a global variable with const keyword'

Accessibility of global scope variables

  • We can access global variables globally in the entire JavaScript code.
  • If global variables are declared at local scope

    • We can't access global variables with keyword let and const at their local scope.
    • But we can only access var keyword variables globally with syntax window.variableName.

Remember! Initialized variable without declaration anywhere in javascript code become global variables by default using default keyword var and we can access it anywhere only after the initialization of a variable, otherwise return an error

// Initialize global variables without declaration
v = 15
// Only accessible after this

Local Scope

Contains local variables which are declared inside local scopes

Block Scope

In JavaScript, variables declared with the keywords let and const are in block scope. we use { } to declare block scope, and in single-line statements, it's hidden like in if, for, while,function because we generally don't use it

// Initialize few local variables within a block-scope
{
  let l = 'I am a local variable with let keyword'
  const c = 'I am a local variable with const keyword'
}

Accessibility of block scope variables

  • We can only access this variables anywhere inside its direct parent block.
// Block-scoped variable example, Same for 'let' keyword
const x = 12;                                           // Has global scope
console.log("Not In Block : " + x);
  {  //Block-1
    const x = 14;                                      // Has local scope
    console.log("In Block-1 : "+ x);
  }
  { //Block-2
    const x = 99;                                     // Has local scope
    console.log("In Block-2 : "+ x);
  }
console.log("Not In Block, After Block : " + x);
Not In Block : 12
In Block-1 : 14
In Block-2 : 99
Not In Block, After Block : 12

Functional Scope

In JavaScript, variables declared with the keyword var are in functional scope.

// Initialize few local variables within functional-scope
function hello() {
  var v = 'I am a local variable with var keyword'
}

Accessibility of functional scope variables

  • We can only access this variables anywhere inside its direct parent function.
// Functional-scoped variable example
var x = 12;                                           // Has global scope
console.log("Not In Function : " + x);
function one() {
  var x = 14;                                        // Has local scope
  console.log("In Function-1 : "+ x);
}
function two() {
  var x = 99;                                       // Has local scope
  console.log("In Function-2 : "+ x);
  console.log("Accessing global variable In Function-2 : "+ window.x);
}
one();
two();
console.log("Not In Function, After Function : " + x);
Not In Function : 12
In Function-1 : 14
In Function-2 : 99
Accessing global variable In Function-2 : 12
Not In Function, After Function : 12

Redeclaration

In JavaScript,

  • We can't redeclare a variable, declared with keyword let and const within its scope
  • But we can redeclare a variable, declared with keyword var
// Here, z has a global scope
let z
let z
SyntaxError: redeclaration of let z
// Here, z has a Block scope
{
  const z = 12
  const z  = 15
}
SyntaxError: redeclaration of const z

Reassignment

In JavaScript,

  • We can reassign a variable, declared with keyword let and var within its scope
  • But we can't reassign a variable, declared with keyword const because it's readOnly
const c = 'hello'
c = 'world'
TypeError: invalid assignment to const `z'

Well, const cannot be reassigned but an object properties can be modified. So, we can use an object as a const variable value if we wanna reassign anything later

// Creating a constant variable object
const you = {
  like: 'food',
  play: 'game',
}

// Modify a property of you object
you.like = 'books'

// Modify the structure of you object
you.love: "nature"

console.log(you)
{ like: 'books', play: 'game', love: "nature" }

Hoisting

In JavaScript, declared variables only with keyword var anywhere are automatically declared at the very top of their scope (functional-scope or global-scope), before executing the code.

  • functional-scope - when var variable declared inside anywhere in a function
  • global-scope - when var variable declared not inside anywhere in a function

Most of the time we access or reassign the variable after declaring and initializing it. But what If we try to access a variable before it has been declared and initialized, it will return undefined.

console.log(x)    // Trying to access a variable before declaring it
var x = 100       // Variable declaring and initializing
undefined
console.log(x)    // Trying to access a variable before declaring it
let x = 100       // Variable declaring and initializing
ReferenceError: can't access lexical declaration `x' before initialization

Remember! The variable must be declared with keyword var. otherwise it will return an error if try to access before declaring it

console.log(x)    // Trying to access a variable before declaring it
x = 100           // Variable initialization without declaration
ReferenceError: x is not defined

To be more clear see the example below

// Initialize x in the global scope
var x = 10

function hoistingExample() {
    /* In this function 'var' is declared at the condition which will never run
      But due to hosting, the 'var x' will automatically declare at the top of this function
      as 'var x;' with its default value 'undefined'
    */
  if (false) {          // condition which will never run
    var x = 30
  }
  console.log(x)
}

hoistingExample()
undefined

In the above example, we declared x to be 10 globally. And x is declared on local scope at condition which will never run. In general if you see the code, you may think the output value of x to be 10. But that's not correct, Due to hosting x was declared at the very top of its direct parent function (In above case hoistingExample( )), with its default value undefined.

// This is how JavaScript interpreted above function 
function hoistingExample() {
  var x;              // virtually declare at the top of this function
  if (false) {
    var x = 30
  }
  console.log(x)
}

Difference Between Var, Let, and Const

JavaScript has three different keywords to declare a variable with some differences

Keyword Initialization Scope Redeclaration Reassignment Hoisting
var   (default) Optional Functional Yes Yes Yes
let Optional Block No Yes No
const Required Block No No No

only var keyword global variables are accessible if same variable is declared at local scope, with syntax window.variableName

Conclusion

In this article, we have learned what a variable is, naming rules of a variable, and the actual differences between var, let and const keyword

At the end, it's been recommended to use const as much as possible, and let in the case of loops and reassignment. Try to avoid use of var until not needed or required mostly on global-scope.

NewOld