var let const

Introduction
Variables are used to store data in JavaScript. They allow developers to save values like text numbers or objects and reuse them in a program. JavaScript provides three ways to declare variables which are var let and const. Each has different behavior and use cases.

Understanding var
The var keyword is the oldest way to declare variables in JavaScript. It has function scope which means it is accessible throughout the function where it is defined. If declared outside a function it becomes globally accessible.

Variables declared with var can be redeclared and updated. This flexibility can sometimes lead to errors in large programs.

Example
var name = “Ali”
var name = “Ahmed”
name = “Sara”

Understanding let
The let keyword was introduced in modern JavaScript to solve issues with var. It has block scope which means it only works inside the block where it is defined such as inside loops or conditions.

Variables declared with let can be updated but cannot be redeclared in the same scope.

Example
let age = 20
age = 25

Understanding const
The const keyword is used to declare variables whose values should not change. It also has block scope like let. Once a value is assigned to a const variable it cannot be reassigned.

However if the value is an object or array its contents can still be modified.

Example
const country = “Pakistan”

Key Differences
var is function scoped while let and const are block scoped
var allows redeclaration but let and const do not
let allows updates but const does not allow reassignment
const must be initialized at the time of declaration

When to Use var let const
Use let when the value may change during the program
Use const when the value should remain constant
Avoid using var in modern JavaScript as let and const are safer

Conclusion
Understanding var let and const is essential for writing clean and error free JavaScript code. Using the correct variable type improves readability and prevents bugs.

Home ยป JavaScript Fundamentals (Beginner Level) > Variables and Data Types > var, let, const