JavaScript Variables


What Are Variables?

Variables are containers used to store data in JavaScript. They allow you to save information such as numbers, text, true/false values, and more. JavaScript provides three ways to declare variables: let, const, and var.


1. let

let is used to declare a variable whose value can be changed later.

Example:

let name = "Alex"

This means a variable named name is given a value of "Alex".


2. const

const is used to declare a constant. Its value cannot be changed after assigning it.

Example:

const pi = 3.14159

This means the variable pi will always have the value 3.14159.


3. var

var works similarly to let, but it is considered outdated and is no longer recommended.

Example:

var x = 5

This means a variable named x is given a value of 5.


Example Using All Variable Types

Code:

// Using var
var x = 10;
console.log("x =", x);

// Using let
let y = 5;
console.log("y =", y);

// Using const
const z = 2;
console.log("z =", z);

// Performing a simple calculation
let sum = x + y + z;
console.log("Sum =", sum);

// Change values of var and let
x = 20; // var can be changed
y = 8; // let can be changed

let newSum = x + y + z;
console.log("New Sum =", newSum);

Output:

x = 10
y = 5
z = 2
Sum = 17
New Sum = 30

HTML Logo