Plenty of π
Module 2: Variables, Data Types, Type Casting, and Comments
Naming Conventions, Reassignment, and Shadowing

Naming Conventions: Choosing good variable names makes your code more readable and understandable.

  • Start with a letter, underscore (_), or dollar sign ($): Variable names cannot start with a number.
  • Subsequent characters: Can be letters, numbers, underscores, or dollar signs.
  • Case-sensitive: myVariable is different from MyVariable.
  • CamelCase: Commonly used in JavaScript (e.g., firstName, totalAmount). The first word is lowercase, and subsequent words start with an uppercase letter.
  • Avoid reserved keywords: You cannot use JavaScript keywords (like let, const, if, for, function) as variable names.
  • Descriptive names: Choose names that clearly indicate the variable's purpose (e.g., userName instead of u or x).

Reassignment:

  • Variables declared with let can be reassigned to a new value.
    let score = 100;
    score = 150; // Valid
    
  • Variables declared with const cannot be reassigned.
    const apiKey = "xyz123";
    // apiKey = "abc789"; // This would cause an error
    
    Note: If a const variable holds an object or an array, the object/array itself is still mutable (its properties or elements can be changed), but the variable cannot be reassigned to a new object/array.

Shadowing: Variable shadowing occurs when a variable declared within a certain scope (e.g., inside a function or a block) has the same name as a variable declared in an outer scope. The inner variable "shadows" or hides the outer variable within its scope.

let x = 10; // Outer scope x

function example() {
  let x = 20; // Inner scope x, shadows the outer x
  console.log(x); // Prints 20
}

example();
console.log(x); // Prints 10 (outer scope x is unaffected)

While shadowing is allowed, it can sometimes make code harder to understand and debug if not used carefully.