Skip to main content
JavaScript Basics
CHAPTER 03 Beginner

JavaScript Variables and Data Types

Updated: May 12, 2026
20 min read

# JavaScript Variables and Data Types

Imagine you are packing boxes for moving. You need a way to label each box so you know what is inside. In JavaScript, variables are like those moving boxes—they are containers used to store data. Data types define what kind of data goes inside the box (e.g., text, numbers, or true/false values).

In this chapter, we will learn how to declare variables and understand the fundamental data types in JavaScript.

1. Introduction

Without variables, programming would be impossible. We need a way to store user input, calculate totals, and keep track of information as a user interacts with a webpage. JavaScript provides three ways to create a variable: var, let, and const.

2. Learning Objectives

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

  • Understand the difference between var, let, and const.
  • Correctly name and declare variables.
  • Identify and use Primitive Data Types (Strings, Numbers, Booleans, Null, Undefined).
  • Use the typeof operator to check variable types.
  • Build a simple student information app using variables.

3. Declaring Variables: var, let, and const

In modern JavaScript (ES6 and later), we primarily use let and const.

  1. 1. var (The Old Way): Used before 2015. It has some quirky behaviors regarding "scope" (which we will cover later), so modern developers avoid it.
  1. 2. let (The Modern Way): Used to declare a variable that *can* change its value later.
  1. 3. const (The Constant): Used to declare a variable that *cannot* be changed once it is set.

Syntax Example

javascript
123456789
// Example JavaScript

var oldSchool = "Not recommended"; 

let age = 25; // Good for values that will change
age = 26;     // Updating the value is perfectly fine

const birthYear = 1998; // Good for values that should NEVER change
// birthYear = 1999;    // ERROR! You cannot reassign a const.

4. Variable Naming Rules

When naming your "boxes" (variables), you must follow strict rules:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter, $, or _. They cannot start with a number.
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords let, return, function) cannot be used as names.

Best Practice: Use *camelCase* for variable names. Start with a lowercase letter, and capitalize the first letter of subsequent words. *(Example: firstName, totalPrice, userAccountBalance)*

5. JavaScript Data Types

JavaScript variables can hold many types of data. The basic ones are called Primitive Data Types.

  1. 1. String: Text wrapped in quotes (single or double).
  1. 2. Number: Integers or decimals.
  1. 3. Boolean: true or false.
  1. 4. Undefined: A variable that has been declared but has not yet been assigned a value.
  1. 5. Null: A deliberate non-value or empty value.

Let's explore these through examples.

6. Real-world Examples & Code Snippets

Example 1: Strings (Text)

Strings are used for text. You can use single quotes '' or double quotes "".

javascript
1234567
// Example JavaScript
let firstName = "John";
let lastName = 'Doe';
let message = "Welcome to JavaScript!";

console.log(firstName);
console.log(message);

Output Explanation: Prints John and Welcome to JavaScript! in the console.

Example 2: Numbers

Unlike some other languages, JavaScript has only one type of number. It handles both integers and decimals (floats).

javascript
123456
// Example JavaScript
let price = 99;         // Integer
let taxRate = 0.08;     // Decimal (Float)
let total = price + (price * taxRate);

console.log(total);

Output Explanation: Prints 106.92.

Example 3: Booleans (True/False)

Booleans are useful for logic. Imagine a light switch: it's either on (true) or off (false).

javascript
12345
// Example JavaScript
let isLoggedIn = true;
let hasAdminRights = false;

console.log(isLoggedIn);

Output Explanation: Prints true.

Example 4: Undefined

If you create a variable but don't put anything in the "box", its value is automatically undefined.

javascript
123
// Example JavaScript
let userEmail;
console.log(userEmail); 

Output Explanation: Prints undefined because no email was assigned.

Example 5: Null

null is used when you deliberately want to say "this box is completely empty".

javascript
123
// Example JavaScript
let currentActiveUser = null; // No one is currently logged in
console.log(currentActiveUser);

Output Explanation: Prints null.

Example 6: The typeof Operator

You can ask JavaScript what type of data is inside a variable using typeof.

javascript
12345
// Example JavaScript
console.log(typeof "Hello");    // Output: string
console.log(typeof 42);         // Output: number
console.log(typeof true);       // Output: boolean
console.log(typeof undefined);  // Output: undefined

Example 7: Updating Variables (let)

You can change the value of variables created with let at any time.

javascript
123456
// Example JavaScript
let score = 0;
console.log("Initial Score:", score); // Output: Initial Score: 0

score = score + 10;
console.log("New Score:", score);     // Output: New Score: 10

Example 8: Attempting to Update Constants (const)

Constants are locked down.

javascript
123456
// Example JavaScript
const pi = 3.14159;
console.log(pi);

// The next line would crash your script in a real environment
// pi = 3.14; // ERROR: Assignment to constant variable.

Example 9: Mixing Strings and Numbers

What happens when you add a String and a Number?

javascript
12345
// Example JavaScript
let age = 30;
let phrase = "I am " + age + " years old.";

console.log(phrase);

Output Explanation: JavaScript automatically converts the number 30 into text to join them together. Outputs: I am 30 years old.

Example 10: The Weird JavaScript Math Bug (String + Number)

Be very careful when mixing types with the + operator!

javascript
123456
// Example JavaScript
let x = "5" + 2; 
let y = "5" - 2;

console.log(x); // Output: 52 (It treats 2 as text and joins them)
console.log(y); // Output: 3  (Wait, what? Minus forces math mode!)

Output Explanation: The + operator concatenates (joins) strings. But the - operator does not exist for strings, so JS forces them into numbers and performs subtraction.

---

7. Common Mistakes for Beginners

  1. 1. Forgetting quotes around strings: let name = John; will throw an error because JS thinks John is a variable, not text. It should be let name = "John";.
  1. 2. Re-declaring the same let variable:
javascript
12345678910111213141516
   let city = "London";
   let city = "Paris"; // ERROR: Identifier 'city' has already been declared.
   ```
   Instead, just update it without `let`: `city = "Paris";`
3. **Using `var` instead of `let` or `const`:** Try to break the habit of using `var` early on.

## 8. Best Practices

- Always use `const` by default. Only change it to `let` if you realize the value needs to change later (like a score counter or user input).
- Use descriptive variable names. `let p = 10;` is bad. `let price = 10;` is good. `let productBasePrice = 10;` is best.

## 9. Mini Project: Student Information App

Let's create an HTML interface that displays dynamic data from our JavaScript variables.

**HTML:**

html <!-- Example HTML --> <!DOCTYPE html> <html> <head> <style> /* Example CSS */ .card { border: 1px solid #ccc; padding: 20px; width: 300px; border-radius: 10px; font-family: sans-serif;} .label { font-weight: bold; color: #555; } </style> </head> <body>

<div class="card"> <h2>Student Profile</h2> <p><span class="label">Name:</span> <span id="s-name"></span></p> <p><span class="label">Age:</span> <span id="s-age"></span></p> <p><span class="label">Graduated:</span> <span id="s-grad"></span></p> </div>

<script src="student.js"></script> </body> </html>

1
**student.js:**

javascript // Example JavaScript // 1. Declare our data variables const studentName = "Emily Chen"; let studentAge = 21; let hasGraduated = false;

// 2. Inject the data into the HTML Document document.getElementById("s-name").innerHTML = studentName; document.getElementById("s-age").innerHTML = studentAge; document.getElementById("s-grad").innerHTML = hasGraduated; `` How it works: We store the student's data in strictly typed variables, then use DOM manipulation to display those variables cleanly on the webpage.

10. Exercises

  1. 1. Declare a variable const myName and assign your name to it.
  1. 2. Declare a variable let myAge and assign your age to it. Then, on the next line, update myAge to be one year older.
  1. 3. Use typeof to check the data type of the boolean false and log it to the console.

11. MCQs (Multiple Choice Questions)

Q1: Which keyword should you use to create a variable that will NOT change? A) var B) let C) const D) static *Answer: C*

Q2: What is the output of typeof 3.14? A) integer B) float C) decimal D) number *Answer: D*

Q3: Which of the following is an invalid variable name? A) _firstName B) 1stPlace C) $accountBalance D) lastName *Answer: B (Variables cannot start with a number)*

12. Interview Questions

Q: Explain the difference between undefined and null. *A: undefined means a variable has been declared but not yet assigned a value. It is the default state of a variable. null is an assignment value; it is explicitly assigned to a variable to mean "absolutely nothing" or "empty".*

Q: Why were let and const introduced in ES6 to replace var? *A: let and const provide block-level scoping, meaning they are contained within the curly braces {} they are defined in. var is function-scoped, which often led to bugs where variables leaked out of if-statements and loops.*

13. FAQs

Q: Do I have to declare the data type like in Java or C++ (e.g., int age = 10;)? *A: No. JavaScript is a "dynamically typed" language. You just use let or const, and JavaScript automatically figures out if it's a number, string, or boolean.*

Q: Can a variable change its data type? *A: Yes! let test = "Hello"; can later become test = 100;. However, this is generally considered a bad practice in real-world development.*

14. Summary

  • Variables are containers for data.
  • Use let for variables that change, and const for variables that stay the same.
  • Avoid using var.
  • The main data types are Strings (text), Numbers, Booleans (true/false), Undefined, and Null.
  • You can check a variable's type using typeof`.

15. Next Chapter Recommendation

You now know how to store data, but what good is data if you can't manipulate it? In the next chapter, JavaScript Operators, we will learn how to perform math, compare values, and combine variables to create logic!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·