Introduction and Overview

Let's explore JavaScript variables — the essential containers for storing data — along with assignment and equality operators, which facilitate our interaction with these variables. After this lesson, you'll understand how to define, use variables, and comprehend the operators.

Understanding Variables

Think of a variable in JavaScript as a box. This box stores data that can be changed, accessed, and manipulated within a program. Variables are declared in three ways: let, var and const, each with its own characteristics:

let age = 20;
var month = 12;
const year = 1900; // A constant. Its value can't change.

month = 11;
age = 21; // Variables created with let can be reassigned.
Why We avoid using var

You might encounter var in older JavaScript code or tutorials, and it's important to understand why modern JavaScript favors let and const instead.

The Problem with var:

var has quirky scoping rules that can lead to unexpected bugs. It uses "function scope" instead of "block scope," meaning variables declared with var are accessible throughout the entire function, even outside the blocks where they're declared:

function example() {
  if (true) {
    var x = 10;
  }
  console.log(x); // prints 10 - x "escaped" the if block!
}

function betterExample() {
  if (true) {
    let y = 10;
  }
  console.log(y); // Error! y only exists inside the if block
}

Why You Need to Know About var:

Even though we avoid using var in new code, you'll likely see it when:

  • Reading older tutorials or Stack Overflow answers
  • Working with legacy codebases
  • Maintaining existing projects

Best Practice:

  • Use const by default for values that won't change
  • Use let when you need to reassign a variable
  • Avoid var in new code — it's a relic from JavaScript's early days

This understanding helps you read older code while writing better code yourself!

JavaScript Null and Undefined Types

In JavaScript, we frequently encounter situations in which a variable doesn't have a value. In such cases, the null and undefined types come into play.

Imagine you possess a flower jar (variable), but it's empty. There is no flower inside. This absence of content is what null in JavaScript represents — an intentionally empty or non-existent value.

Suppose you have a label for a candy jar, but you don't actually have the jar. This is where undefined comes in. It indicates that a variable has been declared, but doesn't yet hold any value.

Here's a code example to illustrate:

let flowerJar = null;         // we have an empty flower jar
console.log(flowerJar);       // outputs: null

let candyJar;                 // we have a label for a candy jar, but no actual jar
console.log(candyJar);        // outputs: undefined
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal