Start learning free

CONDITIONAL STATEMENTS

Declare Variables in JavaScript

Lesson Read the full explanation

In computer science, data is anything that is meaningful to the computer. JavaScript provides a large number of data types, the most frequently used being:

  • number - represents integer numbers like 3, -12 and also floating point numbers like 3.14
  • string - represents a sequence of characters like "John Doe" or 'dog'
  • boolean - represents one of two values: true or false
  • undefined - represents the value of a variable that hasn't been yet initialized
  • null - represents the intentional absence of any object value

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or '123 cats', which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable.

Variables are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer variables differ from mathematical variables in that they can store different values at different times.


Variable creation:

We tell JavaScript to create or declare a variable by putting the keyword let in front of it, like so:

let ourName;

creates a variable called ourName. In JavaScript we end statements with semicolons. Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.


Variable initialization:

It is common to initialize a variable to an initial value in the same line as it is declared.

let ourName = "AlgoCademy";

creates a new variable called ourName and assigns it an initial value of "AlgoCademy".


Variable assignment:

You can always change the value stored in a variable with the assignment operator(=):

// Initializing with 5:
let myVar = 5;

// Assigning the value 10:
myVar = 10;

First, this code creates a variable named myVar, equal to 5. Then, the code assigns 10 to myVar. Now, if myVar appears again in the code, the program will treat it as if it is 10.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the ourName example above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · CONDITIONAL STATEMENTS

    Truthy And Falsy in JavaScript, explained

    Introduction

    In this lesson, we will explore how to declare variables in JavaScript. Variables are fundamental in programming as they allow us to store and manipulate data dynamically. Understanding how to declare and use variables is crucial for any aspiring programmer. Variables are used in various scenarios, such as storing user input, performing calculations, and managing application state.

    Understanding the Basics

    Before diving into variable declaration, let's understand some fundamental concepts:

    • Data Types: JavaScript supports several data types, including numbers, strings, booleans, undefined, and null. Each data type serves a specific purpose and is used in different contexts.
    • Variables: Variables act as containers for storing data. They are given a name (label) and can hold different values at different times.

    Understanding these basics is essential before moving on to more complex aspects of variable declaration and manipulation.

    Main Concepts

    Let's delve into the key concepts and techniques involved in declaring variables in JavaScript:

    • Variable Creation: We use the let keyword to declare a variable. For example, let ourName; creates a variable named ourName.
    • Variable Initialization: Variables can be initialized with an initial value at the time of declaration. For example, let ourName = "AlgoCademy"; initializes ourName with the value "AlgoCademy".
    • Variable Assignment: The value of a variable can be changed using the assignment operator (=). For example, myVar = 10; assigns the value 10 to myVar.

    Examples and Use Cases

    Let's look at some examples to understand variable declaration and usage in different contexts:

    // Example 1: Declaring and initializing a variable
    let userName = "John Doe";
    console.log(userName); // Output: John Doe
    
    // Example 2: Changing the value of a variable
    let age = 25;
    age = 26;
    console.log(age); // Output: 26
    
    // Example 3: Using variables in calculations
    let num1 = 10;
    let num2 = 20;
    let sum = num1 + num2;
    console.log(sum); // Output: 30
    

    These examples demonstrate how variables can be declared, initialized, and used in various scenarios, such as storing user information, updating values, and performing calculations.

    Common Pitfalls and Best Practices

    When working with variables, it's important to avoid common mistakes and follow best practices:

    • Avoid using undeclared variables: Always declare variables using let or const to prevent accidental global variable creation.
    • Use meaningful variable names: Choose descriptive names that convey the purpose of the variable, making the code more readable and maintainable.
    • Initialize variables: Initialize variables with a value to avoid unexpected behavior due to undefined values.

    Advanced Techniques

    Once you are comfortable with basic variable declaration, you can explore advanced techniques:

    • Using const: The const keyword is used to declare variables that should not be reassigned. For example, const PI = 3.14; declares a constant variable.
    • Destructuring: Destructuring allows you to extract values from arrays or objects into distinct variables. For example, const [a, b] = [1, 2]; assigns 1 to a and 2 to b.

    Code Implementation

    Here are some well-commented code snippets demonstrating the correct use of variables:

    // Declaring a variable
    let cityName;
    
    // Initializing a variable
    let countryName = "USA";
    
    // Changing the value of a variable
    let population = 1000000;
    population = 1200000;
    
    // Using const for a constant variable
    const PI = 3.14159;
    
    // Destructuring an array
    const [firstName, lastName] = ["John", "Doe"];
    console.log(firstName); // Output: John
    console.log(lastName); // Output: Doe
    

    Debugging and Testing

    Debugging and testing are crucial for ensuring the correctness of your code:

    • Debugging Tips: Use console.log() to print variable values and track their changes. Utilize browser developer tools to inspect variables and debug code.
    • Writing Tests: Write test cases to verify the behavior of functions and scripts. Use testing frameworks like Jest or Mocha for automated testing.
    // Example test case using Jest
    test('should add two numbers correctly', () => {
      const num1 = 5;
      const num2 = 10;
      const result = num1 + num2;
      expect(result).toBe(15);
    });
    

    Thinking and Problem-Solving Tips

    Here are some strategies for approaching problems related to variable declaration and usage:

    • Break down complex problems: Divide the problem into smaller, manageable parts and solve each part step-by-step.
    • Practice coding exercises: Regularly practice coding exercises and projects to reinforce your understanding of variables and their usage.

    Conclusion

    In this lesson, we covered the basics of declaring variables in JavaScript, including variable creation, initialization, and assignment. We also explored advanced techniques, common pitfalls, and best practices. Mastering these concepts is essential for writing efficient and maintainable code. Keep practicing and exploring further applications to enhance your programming skills.

    Additional Resources

    For further reading and practice, check out the following resources:

    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free