JavaScript Variables and Types
In JavaScript, variables are used to store data values. Unlike some other programming languages, JavaScript is dynamically typed, meaning you don’t need to explicitly declare the data type of a variable when you create it. Instead, the type of the variable is determined automatically at runtime based on the type of data it holds.
In JavaScript, var, let, and const are used for variable declaration, but they have different scopes and behaviors.
- var:
- Declares a variable globally, or locally to an entire function, regardless of block scope.
- Variables declared with
varare function-scoped or globally scoped. - Variables declared with
varcan be re-declared and updated. - Hoisted to the top of their scope and initialized with undefined.
Example:
var x = 10;
function example() {
var y = 20;
console.log(x); // accessible
console.log(y); // accessible
}
console.log(x); // accessible
console.log(y); // ReferenceError: y is not defined
- let:
- Introduces block scoping to JavaScript. Variables declared with
letare scoped to the nearest enclosing block. - Variables declared with
letcan be reassigned but not re-declared within the same block scope. - Hoisted to the top of their block but not initialized (temporal dead zone).
Example:
let x = 10;
if (true) {
let y = 20;
console.log(x); // accessible
console.log(y); // accessible
}
console.log(x); // accessible
console.log(y); // ReferenceError: y is not defined
- const:
- Declares a constant whose value cannot be changed once initialized.
- Similar to
let,constis block-scoped. - Requires initialization at the time of declaration and cannot be left uninitialized.
- The value assigned to a
constvariable is not immutable. If it’s an object or array, its properties or elements can still be modified.
Example:
const PI = 3.14;
PI = 3; // TypeError: Assignment to constant variable
const person = {
name: 'John',
age: 30
};
person.age = 31; // Valid, modifying object properties
console.log(person.age); // Output: 31
In modern JavaScript, it’s generally recommended to use let and const instead of var due to their block scoping behavior, which helps in reducing bugs and unintended side effects in your code. Use let when you need to reassign a variable, and use const for variables that should not be reassigned.