JavaScript Variables and Data Types
# 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, andconst.
- Correctly name and declare variables.
- Identify and use Primitive Data Types (Strings, Numbers, Booleans, Null, Undefined).
-
Use the
typeofoperator 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.
var(The Old Way): Used before 2015. It has some quirky behaviors regarding "scope" (which we will cover later), so modern developers avoid it.
-
2.
let(The Modern Way): Used to declare a variable that *can* change its value later.
-
3.
const(The Constant): Used to declare a variable that *cannot* be changed once it is set.
Syntax Example
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 (
yandYare 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. String: Text wrapped in quotes (single or double).
- 2. Number: Integers or decimals.
-
3.
Boolean:
trueorfalse.
- 4. Undefined: A variable that has been declared but has not yet been assigned a value.
- 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 "".
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).
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).
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.
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".
Output Explanation: Prints null.
Example 6: The typeof Operator
You can ask JavaScript what type of data is inside a variable using typeof.
Example 7: Updating Variables (let)
You can change the value of variables created with let at any time.
Example 8: Attempting to Update Constants (const)
Constants are locked down.
Example 9: Mixing Strings and Numbers
What happens when you add a String and a Number?
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!
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.
Forgetting quotes around strings:
let name = John;will throw an error because JS thinks John is a variable, not text. It should belet name = "John";.
-
2.
Re-declaring the same
letvariable:
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>
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.
Declare a variable const myName
and assign your name to it.
-
2.
Declare a variable let myAge
and assign your age to it. Then, on the next line, updatemyAgeto be one year older.
-
3.
Use typeof
to check the data type of the booleanfalseand 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, andconstfor 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`.