Variables in JavaScript (var, let, const)

JavaScript4 min read
Variables in JavaScript (var, let, const)
JavaScriptVariablesScopeHoistingES6ShadowingWeb Development

Learn how to declare, assign, and initialize variables in JavaScript using var, let, and const. Understand the key differences in scope, hoisting, shadowing, and best practices for variable usage with clear examples.

Variables in JavaScript

In JavaScript, variables are used to store and manipulate data. They can hold values of various types, such as numbers, strings, Booleans, or objects.

Let's understand variable configuration:

1. Declaration

  • Declaration is the process of defining a variable name without assigning a value to it.

  • Example:

var name;

In this example, var is a keyword used for declaring variables, and name is the name of the variable being declared.

2. Assignment

  • Assignment is the process of assigning a value to a variable after it has been declared.
  • Example:
name = "coders";

Here, the variable name is assigned the value "coders".

3. Initialization

  • Initialization is the process of assigning an initial value to a variable at the time of declaration.
  • Example:
var age = 25;

Here, the variable age is declared and initialized with the value 25. To display this value, you can use:

var age = 25; document.write("age = " + age);

This will output: age = 25

Reassigning Values

  • After a variable has been initialized, you can change its value by reassigning it.
  • Example:
var age = 25; age = 30; document.write("age = " + age);

Now, age is 30.

Variables Without Declaration (Non-Strict Mode)

  • In JavaScript, you can initialize a variable without explicitly declaring it if the code is not in strict mode.
  • Example:
marks = 90; // No 'var', 'let', or 'const'

This will display the value of marks as 90.

Strict Mode Restriction

  • However, when you use strict mode, declaring a variable without a keyword will result in an error.
  • Example:
"use strict"; marks = 90; // Error: marks is not defined

In this case, JavaScript requires all variables to be declared properly using var, let, or const.

1. var

  • Variables declared with var have function-level scope or global scope if declared outside of any function.

Function-Level Scope Example:

function show() { var age; // Variable declaration age = 30; // Variable assignment if (age === 30) { var msg = "welcome"; // Declared inside a block but has function scope } document.write("message = " + msg); // Valid and shows "message = welcome" }

In this example:

  • The variable msg is declared inside the if condition block but is accessible outside of it because var has function-level scope.

Variable Shadowing:

  • var supports shadowing, which means you can redeclare a variable without causing an error.
  • Example:
var msg = "welcome"; var msg = "welcome to club"; // Re-declared without any error document.write("message = " + msg); // Outputs: "message = welcome to club"

Here, the second declaration of msg with a new value replaces the original value without any errors.

Hoisting:

  • var supports hoisting, meaning you can use the variable before it has been declared.
  • Example:
x = 20; // Initialized without declaration document.write("x = " + x); // Outputs: "x = 20" var x; // Declaration (hoisted to the top)

In this case:

  • Even though the variable x is initialized before it is declared, JavaScript moves the declaration to the top during compilation, making it accessible throughout the function or globally if outside any function.

2. let

  • Variables declared with let have block-level scope, meaning they are limited to the block enclosed by curly braces.

Block-Level Scope Example:

function show() { let age = 30; // Variable declared with let if (age === 30) { let ticket = 123; // Variable is block-scoped document.write("ticket = " + ticket); // Outputs: "ticket = 123" } // Attempt to access the ticket variable outside its block document.write("ticket = " + ticket); // Shows an error: "ticket is not defined" }

In this example:

  • The variable ticket is declared inside the if condition block and is only accessible within that block. Accessing it outside results in an error because let has block-level scope.

No Shadowing and Hoisting:

  • let does not support shadowing or hoisting in the same way as var. Each block can have its own let variable, but variables declared with let are not accessible before their declaration.

Example:

{ let ticket = 123; // Variable for this block document.write("ticket = " + ticket); // Outputs: "ticket = 123" } { let ticket = 456; // Different variable for this new block document.write("ticket = " + ticket); // Outputs: "ticket = 456" }

In this example:

  • Each let variable named ticket is independent of the others, existing only within its respective block. This prevents shadowing and ensures that variables do not interfere with each other across different blocks.

3. const

Variables declared with the const keyword also have block-level scope. They only allow initialization and once a variable declared with const is assigned a value, that value cannot be changed.

Example of const:

const userName = "The Coding Co."; // Variable declared with const document.write("userName = " + userName); // Outputs: "userName = The Coding Co." // Attempt to change the value of the constant variable userName = "The Coders"; document.write("userName = " + userName); // Throws an error: "Uncaught TypeError: Assignment to constant variable."

In this example:

  • The variable userName is declared with const and initialized with the value "The Coding Co.". Trying to reassign it to "The Coders" results in an error because const variables cannot be reassigned.

Block-Level Scope Example:

function show() { if (true) { const id = 123; // Variable declared with const inside a block document.write("id = " + id); // Outputs: "id = 123" } // Attempt to access the id variable outside its block document.write("id = " + id); // Throws an error: "Uncaught ReferenceError: id is not defined" }

In this example:

  • The variable id is declared with const inside an if condition block and is only accessible within that block. Accessing it outside the block results in an error.

No Shadowing and Hoisting:

  • const does not allow shadowing or hoisting in the same way as var or let. Variables declared with const are not accessible before their declaration and cannot be shadowed within the same scope.

When to use const:

  • Use const when you want to ensure that a variable's value remains fixed and does not change.