Courses/JavaScript/Variables and Data Types

    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 .html file 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; with const, 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 change

    2๏ธโƒฃ 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

    KeywordReassignable?ScopeRecommended?
    letโœ… YesBlockโœ… Best for most variables
    constโŒ NoBlockโœ… Use when value never changes
    varโœ… YesFunctionโŒ 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:

    1. String โ€” Text (words or sentences)
    2. Number โ€” Any numerical value
    3. Boolean โ€” True or False
    4. Undefined โ€” Declared but not assigned
    5. Null โ€” Empty or intentionally nothing
    6. Symbol โ€” Unique identifier (advanced)
    7. 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 hundred

    That'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!

    Try it Yourself ยป
    JavaScript
    // 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. 1๏ธโƒฃ Forgetting to declare with let or const
      score = 10; // โŒ Creates global variable accidentally
    2. 2๏ธโƒฃ Mixing cases
      playerScore vs playerscore // โŒ Not the same
    3. 3๏ธโƒฃ Redeclaring a const variable
      const name = "Alice";
      const name = "Bob"; // โŒ Not allowed
    4. 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: true

    Now 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); // 3

    It 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
    • โœ… let changes, const stays 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

    KeywordReassignable?Use When
    letโœ… YesValue changes over time
    constโŒ NoValue never changes
    varโœ… YesAvoid โ€” legacy only
    Template literal`Hello ${name}!`
    typeoftypeof 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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service