Understanding Variables and Data Types in JavaScript
Source: Dev.to
Think of variables as boxes that store information. If you have multiple boxes, you need to label each one to understand what is stored inside.
In programming, a variable stores data and the variable name is the label.
let name = "John";
Here name is the label and "John" is the value.
How to declare variables
You can use let, var, and const to declare variables:
let age = 25;
const country = "USA";
var isStudent = true;
Primitive data types
String
let name = "Alice";
Number
let age = 20;
Boolean
let isStudent = true;
Null
let middleName = null;
Undefined
let score;
When to use var, let, & const
var– declares function‑scoped or globally‑scoped variables.let– declares a block‑scoped variable.const– declares a block‑scoped variable whose value cannot be reassigned.
What is block scope
Scope determines where a variable can be accessed. Think of it like placing a box in different rooms:
- A box in the living room (global scope) can be seen by everyone.
- A box in your bedroom (block scope) can only be seen by you.
{
let message = "Hello";
console.log(message); // ✅ Works here
}
console.log(message); // ❌ Error (not accessible outside)
Declare variables
let name = "Emma";
let age = 22;
let isStudent = true;
Try changing values
age = 23; // ✅ Allowed
isStudent = false; // ✅ Allowed
Now try with const
const country = "Canada";
country = "USA"; // ❌ Error: Assignment to constant variable
Scope visualization
Global Scope
├── name
├── age
└── Block Scope
└── message