Lesson 2 โข Beginner
Variables and Data Types in JavaScript ๐ก
Learn how to store, use, and manage all kinds of information inside your programs.
What You'll Learn in This Lesson
- โDeclare variables with let, const, and var
- โWhen to use const vs let
- โAll 7 JavaScript data types
- โTemplate literals for string building
- โDynamic typing and typeof operator
- โNaming rules and best practices
๐ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a
.htmlfile with<script>tags and open it in your browser
๐ฆ Real-World Analogy: Variables are like labeled storage boxes:
- โข The label (variable name) tells you what's inside
- โข The contents (value) is what's actually stored
- โข You can open the box anytime to use what's inside
- โข With
let, you can swap the contents; withconst, the box is sealed!
๐ง What Are Variables?
A variable is like a box with a label โ you can store data inside it and use it later in your program. Imagine needing to remember a user's name, score, or age โ instead of retyping the number or word every time, you store it in a variable.
let name = "Alice";
let age = 25;
console.log(name);
console.log(age);๐ข Output:
Alice
25โ๏ธ How Variables Work
When you create (declare) a variable, you're telling the computer:
"Hey, save this piece of information for me so I can use it later."
There are three main ways to declare variables in JavaScript:
1๏ธโฃ let
Modern and flexible
let age = 25;
age = 26; // Can change2๏ธโฃ const
Constant (never changes)
const name = "Alice";
name = "Bob"; // โ Error!3๏ธโฃ var
Old and outdated
Avoid using var. It still works but can cause bugs due to outdated behavior. Always use let or const in modern JavaScript.
โ๏ธ Comparison Table
| Keyword | Reassignable? | Scope | Recommended? |
|---|---|---|---|
let | โ Yes | Block | โ Best for most variables |
const | โ No | Block | โ Use when value never changes |
var | โ Yes | Function | โ Avoid (legacy only) |
๐งฉ Example: Managing Variables
let score = 0; // Player's starting score
const player = "Boopie"; // Fixed player name
score = score + 10; // Increase score
console.log(`${player} scored ${score} points!`);๐ข Output:
Boopie scored 10 points!๐จ Data Types in JavaScript
A data type defines what kind of data a variable holds โ text, number, true/false, etc.
JavaScript has seven main primitive types you'll use daily:
- String โ Text (words or sentences)
- Number โ Any numerical value
- Boolean โ True or False
- Undefined โ Declared but not assigned
- Null โ Empty or intentionally nothing
- Symbol โ Unique identifier (advanced)
- BigInt โ Very large integers
Let's explore the common ones for beginners ๐
๐ค Strings
Text values
let name = "Alice";
let city = 'New York';
let message = `Welcome!`;๐ก You can use: "Double quotes", 'Single quotes', or `Backticks`
๐ข Numbers
Integers and decimals
let age = 16;
let price = 19.99;
let temperature = -5;๐ก JavaScript treats both integers and decimals as the same number type.
โ๏ธ Booleans
True or false values
let isStudent = true;
let hasLicense = false;
let isAdult = age >= 18;You'll use booleans for decisions and conditions, like checking if a user is logged in.
๐ณ๏ธ Null & Undefined
Special empty values
let empty = null;
let notDefined;
console.log(notDefined); // undefinedโข undefined โ variable exists but has no value yet
โข null โ means "nothing", used intentionally
๐ฏ Template Literals
Template literals (with backticks) let you embed variables directly into strings:
let user = "Brayan";
let points = 250;
console.log(`User ${user} has ${points} points.`);๐ข Output:
User Brayan has 250 points.This is easier to read and write than concatenation like:
console.log("User " + user + " has " + points + " points.");๐ง Type Checking
To check what type of data a variable holds, use the typeof operator:
let name = "Alice";
let age = 25;
console.log(typeof name); // string
console.log(typeof age); // number๐งฎ Mixing Data Types
JavaScript is flexible โ you can combine strings and numbers easily:
let apples = 5;
console.log("I have " + apples + " apples.");๐ข Output:
I have 5 apples.Or better yet, with template literals:
console.log(`I have ${apples} apples.`);โ๏ธ Dynamic Typing
In JavaScript, you can change a variable's data type anytime:
let value = 100; // number
value = "One hundred"; // string
console.log(value);๐ข Output:
One hundredThat's because JavaScript is a dynamically typed language โ it decides the type automatically at runtime.
Variables & Data Types Practice
Experiment with let, const, and different data types!
// Declaring variables with let
let name = "Alice";
let age = 25;
let isStudent = true;
console.log("Name:", name);
console.log("Age:", age);
console.log("Is Student:", isStudent);
// Declaring constants with const
const PI = 3.14159;
const birthYear = 1998;
console.log("PI:", PI);
// You can change let variables
age = 26;
console.log("New age:", age);
// Template literals (backticks)
let greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);
// Check types with typ
...๐งฑ Variable Naming Rules
When naming variables, follow these simple rules and conventions:
โ Must start with a letter, $, or _:
let myVar = 10;
let $price = 5.99;
let _count = 42;โ Can contain letters, numbers, $, and _:
let user123 = "John";โ Are case-sensitive:
let name = "Alice";
let Name = "Bob"; // Different variableโ Use camelCase for readability:
let firstName = "Alice";
let totalPrice = 49.99;โ Cannot start with a number:
let 2name = "Error"; // โ Invalidโ Cannot use reserved keywords:
let let = "Nope"; // โ
let if = "Nope"; // โ
let const = "Nope"; // โ๐งฉ Best Practices
โ Use meaningful names:
let score = 100;
let playerName = "Boopie";โ Avoid short or unclear names:
let x = 100; // What does x mean?โ
Use const for values that never change, like API keys or settings.
โ
Use let for values that change often, like scores or totals.
๐งฎ Common Mistakes to Avoid
- 1๏ธโฃ Forgetting to declare with let or const
score = 10; // โ Creates global variable accidentally - 2๏ธโฃ Mixing cases
playerScore vs playerscore // โ Not the same - 3๏ธโฃ Redeclaring a const variable
const name = "Alice"; const name = "Bob"; // โ Not allowed - 4๏ธโฃ Using reserved words (like
if,for,return) as variable names.
๐ง Fun Example โ Real-World Simulation
Let's simulate a small "profile card" using variables:
const firstName = "Boopie";
const lastName = "Plays";
let followers = 1000;
let verified = true;
console.log(`User: ${firstName} ${lastName}`);
console.log(`Followers: ${followers}`);
console.log(`Verified: ${verified}`);๐ข Output:
User: Boopie Plays
Followers: 1000
Verified: trueNow imagine this is part of your social app (like Flick ๐) โ variables store dynamic data that updates automatically when a user gets new followers.
๐งฉ Example: Mini Calculator
let a = 10;
let b = 5;
console.log("Sum:", a + b);
console.log("Difference:", a - b);
console.log("Product:", a * b);
console.log("Quotient:", a / b);๐ข Output:
Sum: 15
Difference: 5
Product: 50
Quotient: 2๐ก Did You Know?
JavaScript automatically converts between numbers and strings when needed โ this is called type coercion.
console.log("5" + 5); // "55"
console.log("5" - 2); // 3It can be confusing at first, so always use correct types when doing math!
๐ฏ Practice Challenge
Create variables to store information about a book:
- Title (string)
- Author (string)
- Year published (number)
- Is available (boolean)
Then, use template literals to create and display a sentence describing the book.
Example:
let title = "Atomic Habits";
let author = "James Clear";
let year = 2018;
let isAvailable = true;
console.log(`"${title}" by ${author}, published in ${year}. Available: ${isAvailable}`);๐ข Output:
"Atomic Habits" by James Clear, published in 2018. Available: trueโก Bonus Challenge
Add one more variable for price and use all values to print a full bookstore-style description.
let price = 12.99;
console.log(`Buy "${title}" by ${author} for ยฃ${price} โ Available Now: ${isAvailable}`);๐ฌ Recap
- โ Variables store data like numbers, text, and booleans
- โ
letchanges,conststays constant - โ JavaScript data types include string, number, boolean, null, undefined
- โ Follow naming conventions and avoid reserved keywords
- โ Use template literals for cleaner, modern code
๐ง Try This Thought:
If your program were a backpack, variables are the items you carry โ text, numbers, or data you'll use later. The better you name and organize them, the easier your "journey" through coding becomes!
๐ Quick Reference โ Variables & Data Types
| Keyword | Reassignable? | Use When |
|---|---|---|
let | โ Yes | Value changes over time |
const | โ No | Value never changes |
var | โ Yes | Avoid โ legacy only |
| Template literal | `Hello ${name}!` | |
| typeof | typeof name // "string" | |
Lesson 2 Complete โ Variables & Data Types!
You now know how to store any kind of data โ text, numbers, booleans โ and build readable strings with template literals.
Up next: JavaScript Functions โ how to group and reuse logic like a professional! ๐
Sign up for free to track which lessons you've completed and get learning reminders.