Skip to main content

⚡ Lesson 3: Variables & Data Types

Store information in variables and understand the different types of data JavaScript can work with.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Declare variables using let, const, and var
  • Explain the difference between let, const, and var
  • Identify JavaScript's primitive data types: string, number, boolean, null, undefined, symbol, bigint
  • Use typeof to check a value's type
  • Follow naming conventions and best practices for variables

Estimated Time: 50 minutes

Project: Build a user profile using variables of different types

📑 In This Lesson

Introduction

Programs need to store and work with information: a user's name, a score, a list of products, whether someone is logged in. Variables are how you store that information in JavaScript, and data types define what kind of information it is.

This lesson covers the absolute fundamentals — the building blocks you'll use in every single program you write.

What Are Variables?

A variable is a named container that stores a value. Think of it as a labeled box — the label is the variable name, and the contents are the value.

graph LR A["let username"] --> B["📦 'Ray'"] C["let score"] --> D["📦 95"] E["let isLoggedIn"] --> F["📦 true"] style B fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style D fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style F fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#1e293b

// Declaring a variable and assigning a value
let username = "Ray";
let score = 95;
let isLoggedIn = true;

// Reading (using) the variables
console.log(username);    // "Ray"
console.log(score);       // 95
console.log(isLoggedIn);  // true
                

The = sign in JavaScript is the assignment operator — it stores the value on the right into the variable on the left. It does not mean "equals" in the mathematical sense (we'll cover that in the next lesson).


// You can change a variable's value later
let mood = "happy";
console.log(mood);  // "happy"

mood = "excited";
console.log(mood);  // "excited"
                

let, const, and var

JavaScript has three keywords for declaring variables. Here's when to use each:

let — For Values That Change


let count = 0;
count = 1;    // ✅ Allowed — let variables can be reassigned
count = 2;    // ✅ Still fine
                

const — For Values That Don't Change


const PI = 3.14159;
const SITE_NAME = "My Website";

PI = 3.0;  // ❌ ERROR! Cannot reassign a const
                

const stands for "constant." Once assigned, the value cannot be reassigned.

var — The Old Way (Avoid)


var oldSchool = "I'm from the 90s";
var oldSchool = "I can be redeclared!"; // ✅ var allows this (confusing!)
                

var was the only option before 2015 (ES6). It has quirks that cause bugs — it can be redeclared, it ignores block scope, and it gets "hoisted" in confusing ways. You'll see it in older code, but always use let or const in new code.

Keyword Reassign? Redeclare? Scope Use When
const ❌ No ❌ No Block Value won't change (default choice)
let ✅ Yes ❌ No Block Value will change (counters, toggles, etc.)
var ✅ Yes ✅ Yes Function Legacy code only — avoid in new code

✅ The Rule of Thumb

Start with const by default. Switch to let only when you know the value needs to change. Never use var unless maintaining old code.

Naming Rules & Conventions

Hard Rules (Must Follow)

  • Names can contain letters, digits, underscores (_), and dollar signs ($)
  • Names must start with a letter, _, or $ (not a digit)
  • Names are case-sensitivescore and Score are different variables
  • Names cannot be reserved words like let, const, function, return, etc.

Conventions (Should Follow)

  • Use camelCase for variables and functions: firstName, totalScore, isActive
  • Use UPPER_SNAKE_CASE for constants that are truly fixed: MAX_RETRIES, API_URL
  • Use descriptive names: userAge instead of x, itemCount instead of n
  • Start boolean variables with is, has, or can: isLoggedIn, hasPermission

// ❌ Poor names
let x = "Ray";
let n = 42;
let flag = true;

// ✅ Good names
let userName = "Ray";
let highScore = 42;
let isGameOver = true;

// ✅ Constants
const MAX_LIVES = 3;
const BASE_URL = "https://api.example.com";
                

JavaScript Data Types

Every value in JavaScript has a type. JavaScript has seven primitive (simple) types and one complex type (objects). For now, we'll focus on the five you'll use most.

graph TD A["JavaScript Data Types"] --> B["Primitive Types"] A --> C["Complex Type"] B --> D["string"] B --> E["number"] B --> F["boolean"] B --> G["null"] B --> H["undefined"] B --> I["symbol (advanced)"] B --> J["bigint (advanced)"] C --> K["object (arrays, functions, etc.)"] style A fill:#f0f0ff,stroke:#6366f1,stroke-width:2px,color:#1e293b style B fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style C fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#1e293b

String — Text

Strings hold text. Wrap them in single quotes, double quotes, or backticks (template literals).


let greeting = "Hello, World!";      // double quotes
let language = 'JavaScript';          // single quotes
let message = `Welcome, ${userName}`; // backticks (template literal)

// String length
console.log(greeting.length);  // 13

// Combining strings (concatenation)
let fullGreeting = greeting + " " + language;
console.log(fullGreeting);  // "Hello, World! JavaScript"
                

💡 Template Literals (Backticks)

Backtick strings let you embed variables and expressions directly using ${...}. This is called string interpolation and it's much cleaner than concatenation with +.


let name = "Ray";
let age = 30;

// ❌ Clunky concatenation
console.log("My name is " + name + " and I am " + age + " years old.");

// ✅ Clean template literal
console.log(`My name is ${name} and I am ${age} years old.`);
                

Number — All Numbers

JavaScript uses a single number type for both integers and decimals (no separate int/float).


let score = 100;        // integer
let temperature = 72.5; // decimal
let negative = -15;     // negative

// Special numeric values
let inf = Infinity;
let nan = NaN;  // "Not a Number" — result of invalid math

console.log(0 / 0);       // NaN
console.log(1 / 0);       // Infinity
console.log("abc" * 2);   // NaN
                

Boolean — True or False

Booleans have exactly two values: true or false. They're the foundation of all decision-making in code.


let isLoggedIn = true;
let hasPermission = false;

// Booleans are often the result of comparisons
let isAdult = age >= 18;  // true if age is 18 or higher
console.log(isAdult);      // true (if age is 30)
                

Null — Intentionally Empty

null means "I explicitly set this to nothing." It's an intentional absence of value.


let selectedItem = null;  // Nothing is selected yet
console.log(selectedItem);  // null
                

Undefined — Not Yet Assigned

undefined means "this variable exists but hasn't been given a value yet."


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

// It's also what functions return when they don't explicitly return something
                

⚠️ null vs. undefined

Both represent "no value," but they mean different things:

  • null = "I deliberately set this to empty"
  • undefined = "This hasn't been assigned a value yet"

Use null when you want to explicitly clear a value. Let JavaScript use undefined for uninitialized variables.

Checking Types with typeof

The typeof operator tells you what type a value is. This is invaluable for debugging.


console.log(typeof "Hello");     // "string"
console.log(typeof 42);          // "number"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (this is a famous JS bug!)

// Using typeof with variables
let price = 9.99;
console.log(typeof price);  // "number"

let name = "JavaScript";
console.log(typeof name);  // "string"
                

⚠️ The typeof null Bug

typeof null returns "object" instead of "null". This is a well-known bug from the earliest days of JavaScript (1995) that was never fixed because it would break existing websites. Just be aware of it — to check for null, use value === null instead of typeof.

Type Conversion Basics

Sometimes you need to convert between types. JavaScript offers both explicit conversion (you do it on purpose) and implicit conversion (JavaScript does it automatically — sometimes with surprising results).

Explicit Conversion (You Control It)


// String to Number
let input = "42";
let num = Number(input);
console.log(num);          // 42
console.log(typeof num);   // "number"

// Number to String
let price = 19.99;
let priceText = String(price);
console.log(priceText);        // "19.99"
console.log(typeof priceText); // "string"

// To Boolean
console.log(Boolean(1));       // true
console.log(Boolean(0));       // false
console.log(Boolean("hello")); // true
console.log(Boolean(""));      // false
                

Implicit Conversion (JavaScript Guesses)


// The + operator with strings does concatenation, not addition!
console.log("5" + 3);    // "53" (string — JS converts 3 to "3")
console.log("5" - 3);    // 2   (number — JS converts "5" to 5)
console.log("5" * 2);    // 10  (number)
console.log(true + 1);   // 2   (true becomes 1)
                

❌ Watch Out for Implicit Conversion

Implicit type conversion (also called "coercion") is one of JavaScript's biggest gotchas. The + operator is especially tricky because it concatenates strings but adds numbers. Always be explicit about conversions to avoid surprises.

Hands-on Exercise

🏋️ Exercise: Build a User Profile

Objective: Create variables of different types to represent a user profile, then display them in the console.

Instructions:

  1. Open your js-practice project (or create a new HTML file)
  2. In your app.js, create variables for a user profile:

// User Profile
// Use const for values that won't change
// Use let for values that might change

// TODO: Create these variables:
// - firstName (string)
// - lastName (string)
// - age (number)
// - email (string)
// - isPremiumMember (boolean)
// - accountBalance (number with decimals)
// - nickname (null — not set yet)

// TODO: Log each variable with its type
// Example: console.log(`firstName: ${firstName} (${typeof firstName})`);

// TODO: Create a greeting using template literals
// Example output: "Hello, Ray De La Paz! You are 30 years old."

// TODO: Try changing a let variable and logging it again
// TODO: Try changing a const variable — what happens?
                    
💡 Hint

Use const for firstName, lastName, and email (these typically don't change during a session). Use let for age, isPremiumMember, accountBalance, and nickname (these could change).

✅ Solution

// User Profile
const firstName = "Ray";
const lastName = "De La Paz";
let age = 30;
const email = "ray@example.com";
let isPremiumMember = false;
let accountBalance = 149.99;
let nickname = null;

// Log each variable with its type
console.log(`firstName: ${firstName} (${typeof firstName})`);
console.log(`lastName: ${lastName} (${typeof lastName})`);
console.log(`age: ${age} (${typeof age})`);
console.log(`email: ${email} (${typeof email})`);
console.log(`isPremiumMember: ${isPremiumMember} (${typeof isPremiumMember})`);
console.log(`accountBalance: ${accountBalance} (${typeof accountBalance})`);
console.log(`nickname: ${nickname} (${typeof nickname})`);

// Greeting with template literal
console.log(`Hello, ${firstName} ${lastName}! You are ${age} years old.`);

// Change some values
age = 31;
isPremiumMember = true;
nickname = "Ace";
accountBalance = accountBalance - 29.99;

console.log("\n--- After updates ---");
console.log(`Age: ${age}`);
console.log(`Premium: ${isPremiumMember}`);
console.log(`Nickname: ${nickname}`);
console.log(`Balance: $${accountBalance}`);

// Try changing a const — uncomment to see the error:
// firstName = "Raymond";  // TypeError: Assignment to constant variable
                        

🎯 Quick Quiz

Question 1: Which keyword should you use by default when declaring a variable?

Question 2: What is the result of typeof null?

Question 3: What does "5" + 3 evaluate to?

Summary

🎉 Key Takeaways

  • Variables store values — use const by default, let when values change, avoid var
  • Strings hold text — use backticks (`template literals`) for clean interpolation
  • Numbers cover both integers and decimals in a single type
  • Booleans are true or false — the basis of all logic
  • null = deliberately empty; undefined = not yet assigned
  • typeof checks a value's type (but watch out for typeof null)
  • Be careful with implicit type conversion, especially + with strings

📚 Additional Resources

🚀 What's Next?

Now that you can store data in variables, the next step is learning how to work with that data. In Lesson 4, you'll learn about operators and expressions — arithmetic, comparison, logical operations, and more.

🎉 Congratulations!

You've completed Lesson 3. You now understand variables and data types — the foundation of everything in JavaScript!