Variable in JavaScript

Dikshya SubediDikshya Subedi
2 min read

In JavaScript, variables are used to store and manage data. You can declare variables using the var, let, or const keywords. Starting with ES6 (ECMAScript 2015), it's recommended to use let and const over var for better scoping and immutability, respectively.

var:

var was the original way to declare variables in JavaScript.Variables declared with var are function-scoped, meaning they are limited to the function in which they are declared, or they are globally scoped if declared outside any function.var variables can be redeclared and reassigned within their scope.

Hoisting: var declarations are hoisted to the top of their containing function or global scope, so you can access the variable before it's declared, but it will be initialized with undefined.

let:

Introduced in ES6 (ECMAScript 2015) to address some of the issues with var. Variables declared with let are block-scoped, meaning they are limited to the block (a block is a set of statements enclosed in curly braces {}) in which they are declared, such as within loops or conditional statements. let variables can be reassigned within their scope, but they can't be redeclared within the same block. Hoisting: let declarations be hoisted, but they are not initialized, so you can't access the variable before it's declared.

const:

Also introduced in ES6. Variables declared with const are block-scoped. const variables cannot be reassigned after their initial assignment. They are read-only. const variables must be initialized with a value when declared, and they cannot be redeclared or reassigned. Hoisting: Like let, const declarations are hoisted but not initialized, so you can't access the variable before it's declared.

Example:

1.Var

// Using var (function-scoped and reassignable)
function exampleVar() {
  if (true) {
    var localVar = "I'm a var!";
  }
  console.log(localVar); // Output: I'm a var!
  localVar = "Changed the value";
  console.log(localVar); // Output: Changed the value
}
exampleVar();

2.Let

// Using let (block-scoped and reassignable)

function exampleLet() {

if (true) {

let localLet = "I'm a let!";

}

// console.log(localLet); // Uncommenting this line would result in an error

let localLet = "Reassigned let";

console.log(localLet);

// Output: Reassigned let

}

exampleLet();

3.Const

// Using const (block-scoped and immutable)

function exampleConst() {

if (true) {

const localConst = "I'm a const!";

console.log(localConst); // Output: I'm a const!

// localConst = "Trying to change";// Uncommenting this line would result in an error

}

}

exampleConst();
0
Subscribe to my newsletter

Read articles from Dikshya Subedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dikshya Subedi
Dikshya Subedi