Lesson 2: Variables - Storing Information

What You'll Learn

  • What variables are and why they're useful
  • How to create variables in JavaScript
  • Different types of data (strings, numbers, booleans)
  • The difference between let and const

Why This Matters

Variables are like containers that hold information. Instead of typing the same value over and over, you store it once and reuse it. This makes your code easier to read, update, and maintain.


What is a Variable?

Think of a variable as a labeled box:

  • The label is the variable's name
  • The contents are the value it holds
  • You can look inside the box (read the value)
  • You can put new things in the box (change the value)

In code, we create variables to remember information while our program runs.


Step 1: Creating Your First Variable

Create a new file: lesson-02/variables.js
let message = "Hello, JavaScript!";
console.log(message);
Run it:
node variables.js
Output:
Hello, JavaScript!

Understanding This Code

Let's break down each part:

let message = "Hello, JavaScript!";
  • let: A keyword that creates a variable
  • message: The name we give to our variable (you can choose any name)
  • =: The assignment operator - puts a value into the variable
  • "Hello, JavaScript!": The value we're storing

Why Use Variables?

Without variables:
console.log("Hello, JavaScript!");
console.log("Hello, JavaScript!");
console.log("Hello, JavaScript!");
With variables:
let message = "Hello, JavaScript!";
console.log(message);
console.log(message);
console.log(message);

Now if you want to change the message, you only need to change it in one place!


Step 2: Variable Types in JavaScript

JavaScript has several basic types. Let's explore the most common ones:

Strings (Text)

let firstName = "Alice";
let lastName = "Johnson";
let greeting = 'Hello there!';  // Single quotes work too

console.log(firstName);  // Output: Alice
console.log(lastName);   // Output: Johnson
console.log(greeting);   // Output: Hello there!
What are strings? Any text data - letters, words, sentences, even numbers in quotes like "123".

Numbers

let age = 25;
let temperature = -5;
let price = 19.99;
let pi = 3.14159;

console.log(age);         // Output: 25
console.log(temperature); // Output: -5
console.log(price);       // Output: 19.99
What are numbers? Any numeric value - whole numbers (integers) or decimals (floats). Notice: no quotation marks!

Booleans (True/False)

let isRaining = true;
let isWeekend = false;
let hasLicense = true;

console.log(isRaining);  // Output: true
console.log(isWeekend);  // Output: false
What are booleans? Only two possible values: true or false. Perfect for yes/no questions or on/off states.

Step 3: Let vs Const

JavaScript has two main ways to declare variables:

Using `let` (Changeable)

let score = 0;
console.log(score);  // Output: 0

score = 10;          // We can change it
console.log(score);  // Output: 10

score = 25;          // We can change it again
console.log(score);  // Output: 25
Use let when the value might change later.

Using `const` (Unchangeable)

const birthYear = 2000;
console.log(birthYear);  // Output: 2000

birthYear = 2001;  // ❌ ERROR! Cannot change a const
Use const when the value should never change (like your birth year or mathematical constants).

Which Should You Use?

Best practice: Use const by default. Only use let if you know you'll need to change the value.
const MAX_PLAYERS = 10;  // Will never change
const COMPANY_NAME = "TechCorp";  // Will never change

let currentPlayers = 0;  // Will change as players join/leave
let currentLevel = 1;    // Will change as game progresses

Step 4: Combining Variables

You can use variables together:

const firstName = "Emma";
const lastName = "Wilson";
const age = 28;

// Combining strings with +
const fullName = firstName + " " + lastName;
console.log(fullName);  // Output: Emma Wilson

// Combining in output
console.log(firstName + " is " + age + " years old");
// Output: Emma is 28 years old

Template Literals (A Better Way!)

Instead of using +, you can use backticks and ${}:

const firstName = "Emma";
const age = 28;

// Using template literals (backticks: )
const message = Hello, my name is ${firstName} and I am ${age} years old.;
console.log(message);
// Output: Hello, my name is Emma and I am 28 years old.
How template literals work:
  • Use backticks: ` (not regular quotes)
  • Insert variables with ${variableName}
  • Much easier to read than using +`

Step 5: Naming Variables

Good variable names make your code easier to understand.

Rules You Must Follow:

  1. Start with a letter, underscore, or dollar sign
  2. Can contain letters, numbers, underscores
  3. Cannot use reserved words (like let, const, if, for)
  4. Case-sensitive: age and Age are different

Good Naming Practices:

// ✅ GOOD: Clear and descriptive
let userAge = 25;
let productPrice = 49.99;
let isLoggedIn = true;

// ❌ BAD: Unclear abbreviations
let ua = 25;
let pp = 49.99;
let login = true;

// ✅ GOOD: Use camelCase for multiple words
let firstName = "John";
let totalScore = 100;

// ❌ BAD: Don't use spaces or hyphens
let first name = "John";  // ❌ ERROR
let total-score = 100;    // ❌ ERROR
Naming convention: We use camelCase - first word lowercase, subsequent words capitalized.

Step 6: Common Mistakes

Mistake 1: Using a Variable Before Declaring It

console.log(name);  // ❌ ERROR
let name = "Alice";
Fix: Declare before using:
let name = "Alice";
console.log(name);  // ✅ CORRECT

Mistake 2: Changing a Const

const pi = 3.14;
pi = 3.14159;  // ❌ ERROR: Cannot reassign const
Fix: Use let if you need to change it:
let pi = 3.14;
pi = 3.14159;  // ✅ CORRECT

Practice Exercises

Exercise 1: About You

Create variables for:

  • Your name (string)
  • Your age (number)
  • Whether you like pizza (boolean)

Print them using template literals.

Exercise 2: Simple Math

Create variables:

const firstNumber = 10;
const secondNumber = 25;
const sum = firstNumber + secondNumber;

Print the result in a sentence.

Exercise 3: Update a Variable

Create a let variable for score, starting at 0. Then "score points" by updating it several times, printing after each update.


Key Concepts Summary

Concept Definition Example
Variable A named container for storing data let age = 25;
let Creates a variable that can change let score = 0;
const Creates a variable that cannot change const PI = 3.14;
string Text data "Hello"
number Numeric data 42 or 3.14
boolean True or false true or false
Template literal String with embedded variables `Age: ${age}`

What You Learned

  • ✅ How to create variables with let and const
  • ✅ The three basic types, number, boolean
  • ✅ How to combine variables with + and template literals
  • ✅ How to name variables clearly
  • ✅ When to use let vs const

What's Next?

In the next lesson, you'll learn about basic operators - how to do math, compare values, and make decisions in your code.