In JavaScript, variables are used to store data values. Variables are essential for holding data that can change over time or that needs to be referenced multiple times. Let's explore how to declare and use variables in JavaScript, from basic to advanced.
### 1. Declaring Variables with `var`, `let`, and `const`
JavaScript provides three ways to declare variables: `var`, `let`, and `const`. Each has different characteristics and use cases.
#### **Using `var`**
- `var` is the oldest way to declare variables in JavaScript.
- It has function scope (or global scope if declared outside a function) and is **hoisted** (accessible before its actual declaration, with an `undefined` value).
```javascript
var name = "Alice";
name = "Bob"; // `var` variables can be reassigned
console.log(name); // Outputs: Bob
```
#### **Using `let`**
- `let` was introduced in ES6 (ECMAScript 2015).
- It has **block scope**, meaning it is only accessible within the block (`{}`) it is declared in.
- `let` can be reassigned, but it is not hoisted like `var`.
```javascript
let age = 25;
age = 26; // `let` variables can be reassigned
console.log(age); // Outputs: 26
```
#### **Using `const`**
- `const` was also introduced in ES6 and is used to declare constants.
- It has **block scope** and cannot be reassigned or redeclared.
- However, if `const` holds an object or array, its properties or elements can still be modified.
```javascript
const birthYear = 1995;
// birthYear = 2000; // This would cause an error, as `const` cannot be reassigned
const user = { name: "Alice" };
user.name = "Bob"; // This is allowed; the object's properties can be modified
console.log(user.name); // Outputs: Bob
```
### 2. Naming Variables
- Variable names must begin with a letter, underscore (`_`), or dollar sign (`$`).
- Variable names are **case-sensitive** (`myVariable` is different from `MyVariable`).
- Descriptive variable names are recommended for readability, like `userName` or `totalAmount`.
### 3. Example of Variables in Action
Here’s an example demonstrating different ways to declare and use variables:
```javascript
let firstName = "Alice"; // Declare a variable with `let`
const birthYear = 1995; // Declare a constant with `const`
// Combine variables in a sentence
let message = "Hello, " + firstName + "! You were born in " + birthYear + ".";
document.write(message); // Outputs: Hello, Alice! You were born in 1995.
```
### 4. Advanced: Scope of Variables
- **Global Scope**: Variables declared outside functions are accessible globally.
- **Function Scope**: `var` is limited to the function scope it’s declared in.
- **Block Scope**: `let` and `const` are limited to the `{}` block they are declared in.
```javascript
function greet() {
var localVar = "I'm local"; // Only accessible within this function
if (true) {
let blockScoped = "I'm block-scoped";
const alsoBlockScoped = "Me too!";
console.log(blockScoped); // Outputs: I'm block-scoped
console.log(alsoBlockScoped); // Outputs: Me too!
}
// console.log(blockScoped); // Error: blockScoped is not defined outside the block
}
- **`var`**: Function-scoped, can be redeclared and reassigned.
- **`let`**: Block-scoped, can be reassigned but not redeclared within the same scope.
- **`const`**: Block-scoped, cannot be reassigned or redeclared within the same scope, but mutable if it’s an object or array.
Choosing the correct variable type (`let` and `const` are generally preferred) helps in writing more reliable, readable, and manageable code.