Variable names must follow these rules:
- Must begin with a letter, an underscore (`_`), or a dollar sign (`$`).
- Subsequent characters can be letters, digits, underscores, or dollar signs.
- Are case-sensitive (e.g., `y` and `Y` are different variables).
- Cannot be reserved JavaScript keywords (like `if`, `for`, `class`, etc.).
**Note:** If no value is specified, the variable is initialized with the value `undefined`. | ### Technical Details | Feature | Specification | | :--- | :--- | | **JavaScript Version:** | 1.0 (ECMAScript 1) | --- ## More Examples ### Example 1: Declaring Multiple Variables You can declare multiple variables in a single statement. Start the statement with `var` and separate the variables with commas: ```javascript var lastName = "Doe", age = 30, job = "carpenter"; ``` ### Example 2: Performing Calculations Declare two variables, `x` and `y`, assign values to them, and output their sum: ```javascript var x = 5; var y = 6; document.getElementById("demo").innerHTML = x + y; // Outputs: 11 ``` ### Example 3: Using a Variable in a Loop Declare a counter variable `i` and use it inside a `for` loop: ```javascript var text = ""; var i; for (i = 0; i < 5; i++) { text += "The number is " + i + "
"; } ``` --- ## Key Considerations & Modern Best Practices While `var` is still widely supported, modern JavaScript (ES6 and later) introduces `let` and `const` for variable declarations. Here are the key differences to keep in mind: ### 1. Scope * **Function Scope:** Variables declared with `var` are scoped to the immediate function body in which they are declared. * **No Block Scope:** Unlike `let` and `const`, variables declared with `var` do not have block scope (e.g., inside an `if` statement or a `for` loop). They leak outside of the block: ```javascript if (true) { var x = 10; } console.log(x); // Outputs: 10 (with let/const, this would throw a ReferenceError) ``` ### 2. Hoisting Variables declared with `var` are "hoisted" to the top of their enclosing function or global scope. This means you can reference a variable before it is declared in the code, though its value will be `undefined`: ```javascript console.log(myVar); // Outputs: undefined (no error is thrown) var myVar = "Hello"; ``` ### 3. Redeclaration You can redeclare the same variable multiple times using `var` without throwing an error, which can lead to accidental bugs: ```javascript var name = "Alice"; var name = "Bob"; // Allowed with var ``` > **Recommendation:** In modern JavaScript development, it is highly recommended to use `const` for variables that will not change, and `let` for variables that will be reassigned. Avoid using `var` to prevent scope-related bugs and hoisting confusion. --- ## Related Pages * JavaScript Tutorial: **JavaScript Variables** * JavaScript Tutorial: **JavaScript Scope** * JavaScript Reference: **let Statement** * JavaScript Reference: **const Statement**
YouTip