js variables

JavaScript Variables

Variables are "containers" for storing information.
JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.



**Rules for JavaScript Variable Names: **

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.


Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value.



<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript Variables Example</title>
</head>
<body>
    <script type="text/javascript">
        var firstname;
        firstname = "Welcome";
        document.write(firstname);
        document.write("<br />");
        firstname = "XYZ";
        document.write(firstname);
    </script>
    <p>
        The script above declares a variable, assigns a value to it, displays the value, 
        changes the value, and displays the value again.
    </p>
</body>
</html>



Output:

Welcome  
XYZ  


---

# **JavaScript Variables**  

Variables are **containers** for storing information.  
JavaScript variables hold values or expressions and can be used to store data dynamically.  

A variable can have a **short name** (e.g., `x`) or a **descriptive name** (e.g., `carName`).  

---

## **Rules for JavaScript Variable Names**  

- Variable names are **case-sensitive** (`y` and `Y` are different variables).  
- Must **begin with a letter**, underscore (`_`), or dollar sign (`$`).  
- Cannot start with a number.  
- **Reserved words** (e.g., `var`, `function`) **cannot** be used as variable names.  

> **Note:** Because JavaScript is case-sensitive, variable names must be used exactly as declared.  

---

## **Declaring JavaScript Variables**  

Creating variables in JavaScript is referred to as **declaring** variables.  

### **1️⃣ Using `var` (Old Method)**  

```javascript
var x;
var carName;

After declaration, these variables hold undefined values.

You can assign values immediately:

var x = 5;
var carName = "Scorpio";

2️⃣ Using let (Preferred for Block Scope)

let age = 25;
let city = "New York";

✅ let is block-scoped, meaning it's only accessible within the {} block where it's declared.

✅ Better than var for modern JavaScript.
3️⃣ Using const (For Constant Values)

const PI = 3.14159;
const country = "USA";

✅ const cannot be reassigned once defined.

✅ You must assign a value when declaring const.
Assigning Values to Undeclared JavaScript Variables

If you assign values to variables without declaring them, JavaScript automatically declares them as global variables.

x = 5;
carName = "Scorpio";

This is the same as:

var x = 5;
var carName = "Scorpio";

    ⚠ Warning: Avoid using undeclared variables, as they become global variables, which can cause unexpected behavior in large applications.

Redeclaring JavaScript Variables

    Redeclaring var does NOT lose its value:

var x = 5;
var x;
console.log(x); // Output: 5

    Redeclaring let or const in the same scope is NOT allowed:

let y = 10;
let y = 20; // ❌ SyntaxError: Identifier 'y' has already been declared

Variable Scope in JavaScript
1️⃣ Global Scope

A variable declared outside a function is global and can be accessed anywhere in the script.

var globalVar = "I am global";  
function showMessage() {
    console.log(globalVar); // Accessible
}
showMessage();
console.log(globalVar); // Accessible

2️⃣ Function Scope

Variables declared inside a function cannot be accessed outside the function.

function localExample() {
    var localVar = "I exist only inside this function";
    console.log(localVar); // Accessible here
}
localExample();
console.log(localVar); // ❌ Error: localVar is not defined

3️⃣ Block Scope (let and const)

let and const are block-scoped, meaning they are only accessible within {} blocks.

if (true) {
    let blockScoped = "Inside the block";
    console.log(blockScoped); // Accessible here
}
console.log(blockScoped); // ❌ Error: blockScoped is not defined

    Note: var is not block-scoped, which can lead to unexpected behavior.

Hoisting in JavaScript

JavaScript moves variable declarations to the top of their scope before execution. This is called hoisting.

console.log(a); // Output: undefined
var a = 10;

⚠ Explanation:

    JavaScript hoists the declaration (var a;) but not the assignment (a = 10).

For let and const, hoisting does not initialize the variable:

console.log(b); // ❌ ReferenceError: Cannot access 'b' before initialization
let b = 20;

Best Practices for Using Variables

✅ Use const by default – It prevents accidental reassignment.
✅ Use let only if you need to change the value later.
✅ Avoid var – Use let and const instead.
✅ Use meaningful variable names – Instead of x, use totalAmount or userName.
✅ Follow naming conventions – Use camelCase (myVariableName).
✅ Avoid global variables – They can be unintentionally modified anywhere in the script.
Example: Combining Everything

const name = "Alice"; // Constant variable (cannot be changed)
let age = 25; // Block-scoped variable
var message = "Hello"; // Function-scoped variable (avoid using var)

function greet() {
    let greeting = "Hi, " + name + "!"; 
    console.log(greeting);
}

if (age > 18) {
    let status = "Adult";
    console.log(status); // Accessible only inside this block
}

console.log(message); // Accessible globally
greet();

Comparison Table: var vs let vs const
Feature	var	let	const
Scope	Function	Block	Block
Hoisted?	Yes	Yes (but uninitialized)	Yes (but uninitialized)
Can be redeclared?	Yes	No	No
Can be reassigned?	Yes	Yes	No

Using let and const instead of var leads to cleaner, more predictable JavaScript code.

Quiz

To mark this module as complete, you must finish this quiz. Once submitted, you'll need to wait 2 hours before attempting it again.