On this page

Variables declaration in JavaScript

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

var, let and const​

In JavaScript, you can declare variables using var, let, and const. Here’s a brief explanation of each:

  1. var: This is the oldest way to declare variables. It is function-scoped, which means a variable declared with var is available within the function it’s declared in. If it’s not declared inside any function, it’s globally scoped. One peculiar behavior of var is hoisting, where variable and function declarations are moved to the top of their containing scope.

var x = 5; // Declare a variable
  1. let: Introduced in ES6 (ECMAScript 2015), let allows you to declare block-scoped local variables. The variable is limited in scope to the block, statement, or expression in which it is declared. This is more intuitive and less error-prone than var.

let y = 10; // Declare a variable
  1. const: Also introduced in ES6, const is used to declare variables whose values are never intended to change. It’s block-scoped like let. The value of a constant cannot change through reassignment, and a constant cannot be redeclared.

const z = 15; // Declare a constant

Remember, while const means that the identifier can’t be reassigned, it doesn’t mean that the value it holds is immutable. If you assign an object or an array to a const variable, the contents of the object or array can still be modified.

Multiple inline assignments​


let a = 1,

  b = "hello",

  c = true; // Declaring and assigning different types



let x, y, z; // Declaring multiple variables without initial assignment



// Destructuring assignment (arrays)

let [first, second, third] = [10, 20, 30];



// Destructuring assignment (objects)

const { name, age } = { name: "Alice", age: 25 };



//You can also use var or const instead of let.

var d = 4,

  e = 5;

const f = 6,

  g = 7;

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Inline vs External Scripts for Web Pages

Next

Primitive Data Types