What Are Variables in JavaScript? See Examples

Variables are one of the most important building blocks of JavaScript. They store data that you can use and modify throughout your program.

In this guide, you’ll learn what variables are, how they work, and when to use var, let, and const.


What Are Variables in JavaScript?

A variable is a container that holds a value.
You can store numbers, text, objects, arrays, and more.

Example

let name = "Sagar";
console.log(name);  // Output: Sagar

Types of Variables in JavaScript

JavaScript provides three keywords to declare variables:

var

let

const

Each works differently.


1. var – Function Scoped (Old Way)

var was the original way to declare variables in JavaScript.

✔ Function-scoped

✔ Allows redeclaration

✔ Should be avoided in modern JavaScript

Example

var x = 5;
var x = 10;  // Allowed
console.log(x);  // Output: 10

Problem:

var ignores block scope.

if (true) {
  var a = 100;
}
console.log(a);  // Works — NOT GOOD!

2. let – Block Scoped (Modern Way)

Introduced in ES6, let is the preferred way to declare variables.

✔ Block-scoped

✔ Cannot be redeclared in the same block

✔ Can be updated

Example

let count = 1;
count = 2;  // Allowed
console.log(count);

Block scoping:

if (true) {
  let y = 50;
}
console.log(y); // Error: y is not defined

3. const – Block Scoped & Constant

const is used when the value should NOT change.

✔ Block-scoped

✔ Must be initialized

✔ Cannot be reassigned

Example

const PI = 3.14;
PI = 3.15;  // ❌ Error: Assignment not allowed

Important:
const prevents reassignment, but not mutation of objects.

const user = {name: "Sam"};
user.name = "John";  // ✔ Allowed

Variable Naming Rules

You can use:

  • letters
  • digits
  • _ underscore
  • $ dollar sign

You cannot:

  • start with a number
  • use reserved keywords (like let, class, return)

Valid:

let userName;
let $price;
let _totalAmount;

Invalid:

let 1name;     // ❌
let let;       // ❌

Dynamic Typing in JavaScript

JavaScript is dynamically typed, meaning variable types can change at runtime.

Example

let data = 10;       // number
data = "Hello";      // now a string

Which One Should You Use?

KeywordScopeRedeclareReassignBest Use
varfunctionyesyesAvoid using
letblocknoyesGeneral variables
constblocknonoConstants & objects

Recommended:

✔ Use const by default
✔ Use let when you need to change the value
✔ Avoid var


Conclusion

Variables allow JavaScript programs to store and manipulate data. Understanding the differences between var, let, and const helps you write clean, modern, and bug-free code.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:

https://www.w3schools.com/js

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *