Skip to main content

Variables and Data Types in JavaScript

Before you can interact with a web page, you must understand how JavaScript stores and handles information.

Variables (let and const)

A variable is like a "box" with a label where you can save a piece of data to use later.

In modern JavaScript (ES6+), you should never use var to declare variables due to historically annoying issues with its "scope". Instead, we use let and const.

1. let (Mutable variables)

Use let when you know that the value of the variable IS GOING to change in the future (like a counter or a user's name being updated).

let age = 25;
print(age); // 25

// Reassigning a new value
age = 26;
print(age); // 26

2. const (Immutable constants)

Use const when the variable's value should NEVER be reassigned. This should be your default choice. If you use const and later try to change its value, JavaScript will throw an error, which is excellent for preventing accidental bugs.

const pi = 3.14159;
const companyName = "No.Learn";

// pi = 3.14; <-- THIS WILL CAUSE AN ERROR (Assignment to constant variable)

Primitive Data Types

JavaScript is "loosely typed", meaning you don't have to explicitly declare whether a variable is a text or a number; the language infers it automatically.

The most common types are:

  1. String (Text string): Text wrapped in single quotes ('), double quotes ("), or backticks (`).

    • Note: Backticks are very powerful because they allow injecting variables directly into the text (Template Literals) using ${}.
    const name = "Anna";
    const greeting = `Hello, my name is ${name}`; // Template Literal
  2. Number: Unlike other languages, JS makes no distinction between whole numbers (int) and decimals (float). They are all Number.

    const temperature = -5.5;
    const price = 100;
  3. Boolean: Can only hold two logical values: true or false.

    const isLoggedIn = true;
  4. Null: Represents the intentional absence of any value.

    let result = null; // We know the variable exists, but it's still purposely empty.
  5. Undefined: A variable that has not been assigned a value, or a property that does not exist.

    let username;
    console.log(username); // undefined