Instagram
youtube
Facebook
Twitter

Variables and Constants

In programming, variables and constants are essential tools used to store and manage data. In JavaScript, variables and constants let us give names to data we can use and manipulate throughout our code. This lesson will cover how to declare variables and constants, understand their scope and behavior, and choose the right type for different programming needs.


1. What Are Variables and Constants?

  • Variables: A variable is a named container that stores data that can be changed later in the program. For example, we can store a user's name in a variable, allowing us to refer to it without typing the name directly each time.

  • Constants: A constant is a named container that holds data that cannot be changed once it’s assigned. Constants are helpful for values that remain the same, like PI = 3.14.

Both variables and constants help make our code more readable, flexible, and organized.


2. Declaring Variables and Constants in JavaScript

JavaScript provides three main ways to declare variables and constants: let, const, and var.

a. let

The let keyword declares a variable that can change its value after it’s been assigned.

  • Example:
    let userName = "Alice";
    userName = "Bob"; // Changing the value of userName

Using let ensures that your variable is block-scoped (more on this later), which helps avoid conflicts between variables with the same name in different parts of the code.

b. const

The const keyword declares a constant, a value that cannot be reassigned after the initial assignment.

  • Example:
    const pi = 3.14159;
    // pi = 3.15; // This would throw an error because pi is constant

If you know a value will not change throughout your program, use const to make your code clear and help prevent accidental changes.

c. var

var is the original way to declare variables in JavaScript. It is function-scoped rather than block-scoped, which can lead to unexpected behavior. With modern JavaScript, it’s best practice to use let and const instead of var for better readability and control.

  • Example:
    var age = 30;

3. Naming Variables and Constants

In JavaScript, variables and constants follow specific naming conventions:

  • Variable names should be descriptive, describing the value or purpose of the variable.
  • They must begin with a letter, underscore (_), or dollar sign ($).
  • They can contain letters, numbers, _, and $, but cannot contain spaces or special characters.
  • Variable names are case-sensitive, so userName and username are different.

Examples of Valid Names:

let firstName = "John";
const MAX_USERS = 50; // Constants are often written in uppercase with underscores

Examples of Invalid Names:

let 1user = "Alice";  // Cannot start with a number
let user-name = "Bob"; // Hyphens are not allowed

4. Assigning Values to Variables

In JavaScript, variables and constants are assigned values using the = (assignment operator). You can assign values during the declaration or later in your code (for let and var, but not const).

  • Example:
    let color; // Declaration without assignment
    color = "blue"; // Assignment
    const year = 2024; // Declaration and assignment together

5. Variable Scope: Block, Function, and Global

Scope refers to where a variable or constant is accessible in your code. JavaScript has three main scopes:

a. Block Scope

Variables declared with let and const are block-scoped, meaning they’re only accessible within the block they’re declared in (usually within { } braces).

  • Example:
    {
      let score = 10;
      console.log(score); // 10
    }
    // console.log(score); // Error: score is not defined outside the block
    
b. Function Scope

Variables declared with var are function-scoped, meaning they’re accessible only within the function they’re declared in.

  • Example:
    function showAge() {
      var age = 30;
      console.log(age); // 30
    }
    // console.log(age); // Error: age is not defined outside the function
    
c. Global Scope

Variables declared outside any block or function are global and accessible from anywhere in the code. Use global variables sparingly, as they can lead to conflicts in large programs.

  • Example:
    let user = "Alice"; // Global variable
    function greet() {
      console.log("Hello, " + user);
    }
    greet(); // Accesses the global variable
    

6. const with Objects and Arrays

While const prevents reassignment, it doesn’t make objects and arrays immutable. You can still change the properties of objects or the elements in arrays declared with const.

  • Example:
    const user = { name: "Alice", age: 25 };
    user.age = 26; // Allowed: modifying a property of an object
    console.log(user); // { name: "Alice", age: 26 }
    
    const colors = ["red", "green", "blue"];
    colors.push("yellow"); // Allowed: modifying an array
    console.log(colors); // ["red", "green", "blue", "yellow"]
    

However, you cannot reassign the user or colors variable itself to a new object or array.


7. Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top of the scope. var declarations are hoisted and initialized with undefined, while let and const declarations are hoisted but not initialized, causing a Temporal Dead Zone if accessed before declaration.

  • Example with var:

    console.log(score); // Outputs: undefined due to hoisting
    var score = 10;
    
  • Example with let:

    console.log(points); // ReferenceError: Cannot access 'points' before initialization
    let points = 5;
    

To avoid confusion, always declare variables at the top of the scope.


8. Best Practice s for Variables and Constants

  • Use const whenever possible: If you don’t need to change a value, use const. This makes your code easier to read and prevents accidental changes.
  • Use let only when necessary: Use let if you expect the value to change.
  • Avoid using var: Unless working with legacy code, avoid var due to its function-scoping and potential for unexpected behavior.
  • Choose descriptive names: Variable and constant names should be meaningful and self-explanatory.

9. Coding Exercise

Let’s put this knowledge into practice with a quick exercise.

  1. Create a new JavaScript file named variablesPractice.js.
  2. Declare the following variables:
    • A constant for the number of days in a week (daysInWeek).
    • A variable for today’s temperature (temperature).
    • An object for a person with properties name, age, and isStudent.
  3. Try changing the values of each variable and log the results to see which ones can be updated and which ones cannot.

Example Solution:

const daysInWeek = 7;
let temperature = 22;
let person = {
    name: "Alice",
    age: 25,
    isStudent: true
};

// Try changing values
temperature = 30; // Allowed, since it was declared with let
person.age = 26; // Allowed, since we’re modifying a property, not reassigning the object

console.log(daysInWeek); // 7
console.log(temperature); // 30
console.log(person); // { name: "Alice", age: 26, isStudent: true }

Conclusion

In this lesson, you learned how to declare and use variables and constants, the difference between let, const, and var, and best practices for managing data in JavaScript. Mastering variables and constants is essential for building efficient and reliable code, especially as you work on larger projects.

In the next lesson, we’ll dive into Control Structures, where you’ll learn how to make decisions and control the flow of your code.