In JavaScript, variables are used to store data that can be referenced and manipulated later. There are three ways to declare variables:
1. `var`:
The traditional way to declare variables, which has function scope or globally scoped if declared outside a function.
var x = 5;
var y = 'hello';
2. `let`:
Introduced in ES6, `let` allows you to declare block-scoped variables, which are only accessible within the block they are defined.
let x = 5;
if (true) {
let y = 'hello';
}
// y is not accessible here
3. `const`:
Also introduced in ES6, `const` is used to declare block-scoped variables that are read-only. Once a value is assigned to a `const` variable, it cannot be reassigned.
const x = 5;
// x = 10; // This will throw an error
Variable Scope
Global Scope:
Variables declared outside any function are in the global scope and can be accessed anywhere in the code.
var x = 5; // Global variable
function example() {
console.log(x); // 5
}
Function Scope:
Variables declared within a function using `var` are only accessible within that function.
function example() {
var y = 10; // Function scoped variable
console.log(y); // 10
}
// console.log(y); // Error: y is not defined
Block Scope:
Variables declared with `let` or `const` inside a block (e.g., inside a loop or conditional statement) are only accessible within that block.
if (true) {
let z = 15; // Block scoped variable
console.log(z); // 15
}
// console.log(z); // Error: z is not defined
Hoisting
JavaScript variables declared with `var` are hoisted to the top of their scope, meaning they can be referenced before they are declared, although they will be `undefined` until the actual declaration is encountered.
console.log(a); // undefined
var a = 10;
console.log(a); // 10
Variables declared with `let` and `const` are also hoisted but are not initialized, resulting in a ReferenceError if accessed before declaration.
// console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;
Best Practices
- Use `const` by default unless you know the variable's value will change.
- Use `let` if you need to reassign a variable's value.
- Avoid using `var` to prevent potential issues with scope and hoisting.