11.3 Variables

Variables

  1. Introduction to Variables:

    • Variables are used to store data that can be referenced and manipulated in a program.

    • In JavaScript, variables can be declared using three keywords: var, let, and const. Each has different behavior in terms of scope and reassignment.

    • var (older way of declaring variables):

      • Used to declare variables before ES6 (2015).

      • Allows function-scoped variables.

      • Can be redeclared and updated within its scope.

      var name = "Adil";
      console.log(name);  // Outputs: Alice
      
      var name = "Bob";
      console.log(name);  // Outputs: Bob (var allows redeclaration)
    • let (block-scoped variable):

      • Introduced in ES6, let is now the preferred way to declare variables when their value may change.

      • Variables declared with let are block-scoped, meaning they are only accessible within the block they are declared in (e.g., inside a loop or if-statement).

      • Cannot be redeclared within the same scope, but can be updated.

      let age = 25;
      console.log(age);  // Outputs: 25
      
      age = 30;
      console.log(age);  // Outputs: 30 (let allows reassignment)
    • const (constant variables):

      • Also introduced in ES6, const is used to declare variables whose value should never change (i.e., immutable).

      • Like let, const is block-scoped and cannot be redeclared or reassigned after its initial assignment.

      const PI = 3.14;
      console.log(PI);  // Outputs: 3.14
      
      // PI = 3.15;  // This will cause an error as reassignment is not allowed
  2. Local vs. Global Variables:

    • Local Variables:

      • Variables declared inside a function or block (using let or var within a function) are local and cannot be accessed outside that function or block.

      • Example:

        function greet() {
          let message = "Hello";  // Local variable
          console.log(message);   // Outputs: Hello
        }
        greet();
        // console.log(message);  // Error: message is not defined (outside its scope)
    • Global Variables:

      • Variables declared outside of any function or block are global variables, meaning they can be accessed from anywhere in the program.

      • Global variables should be used sparingly, as they can easily lead to conflicts and unintended side effects.

      • Example:

        let globalVar = "I'm global";
        
        function display() {
          console.log(globalVar);  // Can access global variable inside the function
        }
        display();  // Outputs: I'm global
  3. Using console.log() for Debugging:

    • console.log() is an essential tool for debugging in JavaScript. It outputs the value of variables or messages to the browser’s console, allowing developers to inspect the state of their code during execution.

    • Example:

      let score = 100;
      console.log("Player's score: " + score);  // Outputs: Player's score: 100
      
      let name = "Alice";
      console.log(name);  // Outputs: Alice
    • Students should be encouraged to frequently use console.log() to trace their code, especially when encountering errors or unexpected behavior.

Student Activity (20 mins):

  • Objective: Students will practice declaring and using variables with var, let, and const, and observe the difference between local and global variables. They will also use console.log() for debugging.

Instructions:

  1. Create an HTML file (e.g., index.html) with an embedded JavaScript section. Implement the following code and observe the output in the browser console:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Variables</title>
</head>
<body>
  <h1>JavaScript Variables Example</h1>
  
  <script>
    // Using var
    var city = "New York";
    console.log("City: " + city);  // Outputs: City: New York
    
    // Redeclaring var
    var city = "Bishkek";
    console.log("Updated City: " + city);  // Outputs: Updated City: Los Angeles
    
    // Using let
    let age = 20;
    console.log("Age: " + age);  // Outputs: Age: 20
    
    // Reassigning let (no redeclaration allowed)
    age = 25;
    console.log("Updated Age: " + age);  // Outputs: Updated Age: 25
    
    // Using const
    const birthYear = 1995;
    console.log("Birth Year: " + birthYear);  // Outputs: Birth Year: 1995
    
    // Local vs Global Example
    let globalVar = "Global Variable";
    
    function testScope() {
      let localVar = "Local Variable";
      console.log(globalVar);  // Can access global variable
      console.log(localVar);   // Can access local variable within the function
    }
    
    testScope();
    // console.log(localVar);  // Uncommenting this will cause an error (localVar is not defined outside the function)
  </script>
</body>
</html>
  1. Instructions for the activity:

    • Run the code in a browser and open the developer console (press F12 or right-click and select "Inspect" > "Console") to see the outputs of the console.log() statements.

    • Modify the values of var, let, and const and see how they behave when you try to redeclare or reassign them.

    • Experiment with placing variables inside and outside functions to understand local vs global scope.

Follow-up Discussion:

  • Ask students to identify which parts of the code caused errors (if any) and why.

  • Review the differences between var, let, and const in terms of redeclaration, reassignment, and scope.

  • Discuss when and why global variables should be used with caution.

Expected Outcome:

Students will understand how to declare and use variables in JavaScript, the differences between var, let, and const, and how to debug their code using console.log(). They will also grasp the concept of variable scope and how to avoid common issues with local vs. global variables.

Last updated