JavaScript Variables
Declaring Variables
Variables are containers for storing data values, and in JavaScript, variables can be declared using var
, let
, or const
.
var
The var
keyword was the original way to declare variables in JavaScript. Variables declared with var
are function-scoped and can be reassigned.
Example:
var x = 5;
console.log(x); // Outputs: 5
x = 10;
console.log(x); // Outputs: 10
Key Characteristics of var
:
- Scope: Function-scoped, meaning it’s accessible within the function it’s declared in.
- Hoisting:
var
declarations are hoisted to the top of their scope, but only the declaration is hoisted, not the assignment.
Example of Hoisting with var
:
console.log(a); // Outputs: undefined, as only the declaration is hoisted
var a = 10;
console.log(a); // Outputs: 10
let
Introduced in ES6, the let
keyword allows for block-scoped variables, meaning they are limited to the block (or set of curly braces) where they are defined.
Example:
let y = 5;
console.log(y); // Outputs: 5
y = 20;
console.log(y); // Outputs: 20
Key Characteristics of let
:
- Scope: Block-scoped, making it safer to use in loops and conditional blocks.
- Hoisting:
let
is hoisted but is not initialized, so accessing it before declaration results in aReferenceError
.
Example with let
and Block Scope:
if (true) {
let z = 30;
console.log(z); // Outputs: 30
}
// console.log(z); // Throws ReferenceError because z is not accessible outside the block
const
const
is also block-scoped but is meant for values that should not be reassigned after their initial assignment.
Example:
const pi = 3.14159;
console.log(pi); // Outputs: 3.14159
// pi = 3.14; // Throws TypeError: Assignment to constant variable.
Key Characteristics of const
:
- Scope: Block-scoped, just like
let
. - Reassignment: Cannot be reassigned after declaration.
- Hoisting: Similar to
let
,const
is hoisted but not initialized.
Note: For objects and arrays declared with const
, the contents can still be modified, but the variable itself cannot be reassigned.
Example of a const
Array:
const colors = ["red", "blue"];
colors.push("green"); // Works because we're modifying the array, not reassigning it
console.log(colors); // Outputs: ["red", "blue", "green"]
// colors = ["yellow"]; // Throws TypeError: Assignment to constant variable.
Summary of var
, let
, and const
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Yes | Yes (uninitialized) | Yes (uninitialized) |
Reassignment | Allowed | Allowed | Not allowed |
Use Cases | Legacy code | Modern usage | Constants |