Introduction
Whenever we talk about programming languages like C, C++, Python, or JavaScript, we are working with data. This data can be a number, a name, a price, a Boolean value, or many other things.
But how do we store this data and use it later in a program?
This is where variables come in.
Variables allow us to give a name to a value so that we can access and work with it easily. But before learning how to create variables using var, let, and const, we should understand an important concept called scope.
In this article, we will learn:
- What scope is and why it matters
- Global, function, and block scope
- Variables and how to declare them
- The difference between
var,let, andconst - Variable naming rules
- JavaScript data types
- Primitive data types and the
typeofoperator - Practical examples and exercises
1. What Is Scope in JavaScript?
In JavaScript, scope defines where a variable can be accessed in a program.
Imagine you create a variable inside a function. Can you access it outside that function? What if you create a variable inside an if block? Can you use it after the block ends?
Scope determines the answer to these questions.
JavaScript commonly introduces us to three kinds of scope:
- Global scope
- Function scope
- Block scope
Let's understand each one with simple examples.
2. Global Scope
A variable declared outside functions and blocks is generally considered to be in the global scope.
This means it can be accessed from different parts of the program within that scope.
Example:
let name = "Gaurav";
function greet() {
console.log(name);
}
greet();
console.log(name);
Output:
Gaurav
Gaurav
Explanation:
Here, name is declared outside the function, so it is available inside greet() as well as at the outer level.
Important: In modern JavaScript, top-level variables in modules have module scope rather than becoming properties of the global object. For beginners, the key idea is that an outer variable can be accessed from inner scopes.
3. Function Scope (Local Scope)
A variable declared inside a function is accessible within that function, but it cannot be accessed directly outside it.
This is commonly called function scope or local scope.
Example:
function student() {
let age = 20;
console.log(age);
}
student();
console.log(age);
Output:
20
ReferenceError: age is not defined
Explanation:
ageis declared inside thestudent()function.- It can be accessed inside the function.
- It cannot be accessed outside the function.
This is useful because variables that are only needed inside a function can remain local to that function, helping prevent accidental access or changes elsewhere.
4. Block Scope
A block is a section of code enclosed in curly braces { }, such as the body of an if statement or a loop.
Block scope means a variable declared with let or const inside a block can only be accessed within that block.
Example:
if (true) {
let age = 20;
console.log(age);
}
console.log(age);
Output:
20
ReferenceError: age is not defined
Explanation:
The variable age is created inside the if block. It can be accessed inside those braces, but not after the block ends.
Now that we understand scope, let's see how it helps us understand the three main ways to declare variables in JavaScript.
5. What Is a Variable?
A variable is a named identifier used to access a value in a program.
For example:
let age = 25;
Here:
| Part | Meaning |
|---|---|
let |
Keyword used to declare a variable |
age |
Variable name |
= |
Assignment operator |
25 |
Value assigned to the variable |
; |
Statement terminator |
We can now access the value using the variable's name.
let age = 25;
console.log(age);
Output:
25
We can also update a variable declared with let.
let age = 25;
age = 26;
console.log(age);
Output:
26
Variables make it easier to reuse and update values without having to write the original value everywhere in the program.
6. Ways to Declare Variables in JavaScript
JavaScript provides three commonly used variable declaration keywords:
varletconst
All three allow us to create variables, but they differ in scope, redeclaration, and reassignment.
7. Understanding var
var is an older way of declaring variables in JavaScript. It is still valid, but modern JavaScript code generally prefers let and const.
var is function-scoped
A variable declared with var inside a function is available throughout that function.
function example() {
var x = 10;
console.log(x);
}
example();
Output:
10
However, if we try to access x outside the function:
function example() {
var x = 10;
}
console.log(x); // ReferenceError
var is not block-scoped
Unlike let and const, var ignores ordinary block boundaries.
if (true) {
var age = 20;
}
console.log(age);
Output:
20
var allows redeclaration
You can declare the same variable again within the same scope using var.
var x = 20;
var x = 40;
console.log(x);
Output:
40
var allows reassignment
You can also assign a new value to an existing var variable.
var name = "Gaurav";
name = "Rahul";
console.log(name);
Output:
Rahul
8. Why Do We Prefer let Over var?
Consider this example:
function calculate() {
var result = 100;
if (true) {
var result = 500;
}
console.log(result);
}
calculate();
Output:
500
The var declaration inside the if block refers to the same function-scoped variable, so its value changes to 500.
Now let's use let.
function calculate() {
let result = 100;
if (true) {
let result = 500;
}
console.log(result);
}
calculate();
Output:
100
The let declared inside the if block belongs to a separate block scope. It does not overwrite the outer result.
9. Understanding let
let was introduced in ES2015 (ES6) to provide block-scoped variable declarations.
let is block-scoped
{
let age = 25;
console.log(age);
}
console.log(age); // ReferenceError
let does not allow redeclaration in the same scope
let age = 20;
let age = 30; // SyntaxError
let allows reassignment
let age = 20;
age = 30;
console.log(age); // 30
let can hold values of different types
JavaScript is dynamically typed. That means a variable declared using let can be assigned values of different data types.
let value = 20;
value = "Gaurav";
value = true;
value = null;
console.log(value); // null
10. Understanding const
const is also a block-scoped declaration introduced in ES2015 (ES6).
It is used when you do not want to reassign a variable after its initial assignment.
const country = "India";
console.log(country);
const does not allow reassignment
const age = 25;
age = 30; // TypeError
const does not allow redeclaration in the same scope
const age = 25;
const age = 30; // SyntaxError
const must be initialized
Unlike let, a const variable must be given a value when it is declared.
const age; // SyntaxError
Important: const does not make objects immutable
When a const variable stores an object, the variable cannot be reassigned to another object, but the object's properties can still be changed.
const student = {
name: "Gaurav"
};
student.name = "Rahul";
console.log(student.name); // Rahul
But this is not allowed:
student = {}; // TypeError
11. Difference Between var, let, and const
| Feature | var |
let |
const |
|---|---|---|---|
| Function-scoped | Yes | No | No |
| Block-scoped | No | Yes | Yes |
| Redeclaration in same scope | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Must be initialized at declaration | No | No | Yes |
| Modern code preference | Usually avoid | Use when reassignment is needed | Use by default when reassignment is not needed |
Easy way to remember:
var→ Function-scoped, can redeclare and reassign.let→ Block-scoped, can reassign but cannot redeclare in the same scope.const→ Block-scoped, cannot reassign or redeclare in the same scope.
12. Variable Naming Rules
When creating variables, we should follow JavaScript's naming rules and use meaningful names.
Use meaningful variable names
// Not recommended
let x = 25;
// Better
let studentAge = 25;
Variable names cannot contain spaces
// Invalid
let student name = "Gaurav";
// Correct
let studentName = "Gaurav";
Variable names cannot start with a number
// Invalid
let 1name = "Gaurav";
// Correct
let name1 = "Gaurav";
Underscores and dollar signs are allowed
let _name = "Gaurav";
let $price = 500;
Avoid reserved keywords
JavaScript has reserved words that have special meanings in the language. For example, if, else, let, const, function, and return cannot be used as variable names.
JavaScript is case-sensitive
let age = 20;
let Age = 30;
console.log(age); // 20
console.log(Age); // 30
13. What Are Data Types?
Now that we understand variables, let's move to data types. A variable stores or refers to a value, and that value has a data type.
For example:
let age = 25;
let name = "Gaurav";
let isStudent = true;
Here:
25is a Number."Gaurav"is a String.trueis a Boolean.
JavaScript is dynamically typed, so we don't have to explicitly specify the data type when declaring a variable.
14. Types of Data in JavaScript
JavaScript data types can be grouped into two broad categories:
Primitive: Number, String, Boolean, Undefined, Null, BigInt, Symbol
Non-primitive: Object, Array, Function
15. Primitive Data Types
JavaScript has seven primitive data types.
Number
The Number data type is used for both integers and decimal numbers.
let age = 25;
let price = 99.50;
let temperature = -10;
console.log(typeof age); // number
String
A string is used to represent text.
let name = "Gaurav";
let city = 'Lucknow';
let message = `Hello students`;
Boolean
A Boolean represents one of two values: true or false.
let isLoggedIn = true;
let isStudent = false;
console.log(typeof isLoggedIn); // boolean
Undefined
When a variable is declared but no value is assigned, its value is undefined.
let age;
console.log(age); // undefined
console.log(typeof age); // undefined
Null
null is used to intentionally represent the absence of a value.
let selectedUser = null;
console.log(selectedUser); // null
console.log(typeof selectedUser); // object
BigInt
BigInt is used to represent integers larger than the safe integer range of Number.
let bigNumber = 9007199254740993n;
console.log(bigNumber);
console.log(typeof bigNumber); // bigint
Symbol
Symbol is a primitive data type used to create unique values.
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // false
console.log(typeof id1); // symbol





