Skip to main content

Command Palette

Search for a command to run...

Understanding Variables in JavaScript

Updated
•2 min read•View as Markdown

1. A Simple Idea

Think of a variable like a box.

You can store something inside it, give it a name, and use it later.

Example:

let name = "Aman";
  • name → box name

  • "Aman" → value inside the box


2. Why Variables Are Needed

Instead of writing values again and again:

console.log("Aman");
console.log("Aman");

You store it once:

let name = "Aman";

console.log(name);
console.log(name);

This makes code easier to manage.


3. Declaring Variables

JavaScript provides three ways:

var a = 10;
let b = 20;
const c = 30;

4. Primitive Data Types

String (text)

let name = "Aman";

Number

let age = 21;

Boolean

let isStudent = true;

Null

let data = null;

Undefined

let value;

5. Difference Between var, let, and const

Image

Simple Explanation

  • var → old way (avoid using)

  • let → can change value

  • const → cannot change value


6. Changing Values

let (allowed)

let age = 21;
age = 22;

console.log(age); // 22

const (not allowed)

const pi = 3.14;
pi = 3.15; // error

7. What is Scope (Simple)

Scope means:

👉 Where a variable can be used


Example

{
  let x = 10;
  console.log(x); // works here
}

console.log(x); // error
Image

9. Practice Assignment

Declare variables

let name = "Aman";
let age = 21;
let isStudent = true;

console.log(name);
console.log(age);
console.log(isStudent);

Try changing values

let age = 21;
age = 25; // works

const name = "Aman";
name = "Rahul"; // error