1. Variable Declaration
To declare a variable in JavaScript, you use the var, let, or const keyword followed by the variable name. Here's how each keyword works:
a. Using var
The var keyword was the traditional way to declare variables in JavaScript. It has function scope, meaning it's scoped to the nearest function block.
b. Using let
Introduced in ES6, let allows block scoping. Variables declared with let are limited to the block (or statement) they are defined in.
c. Using const
const also came with ES6 and is used to declare constants. Constants cannot be reassigned a new value once initialized.
2. Variable Naming Rules
When naming variables in JavaScript, you should follow these rules:
- Variable names can contain letters, digits, underscores, and dollar signs.
- Variable names cannot start with a digit.
- Variable names are case-sensitive (age is different from Age).
- Reserved words (e.g., if, else, function) cannot be used as variable names.
3. Examples of Variable Declaration
a. Declaring and Initializing Variables
var firstName = 'Alice'; // Using var
let lastName = 'Smith'; // Using let
const MAX_VALUE = 100; // Using const
b. Reassigning Variables
count = count + 1; // Reassigning the value of count
c. Constants
DAYS_IN_WEEK = 10; // This will throw an error as constants cannot be reassigned.
4. Scope of Variables
Variables declared with var have function-level scope, meaning they are visible throughout the function they are declared in (including inside nested blocks). However, they are not accessible outside the function.
Variables declared with let and const have block-level scope. They are limited to the block (enclosed by curly braces) they are defined in.
5. Hoisting
JavaScript hoists variable declarations. This means that variable declarations (not initializations) are moved to the top of their scope during compilation.
Example of Hoisting
var name = 'Alice';
Even though name is declared later in the code, it's hoisted to the top, so the code above is interpreted as:
console.log(name); // Outputs: undefined
name = 'Alice';
Practice Excercise Practice now