3.2 Data Types and Variables
After writing your first JavaScript statements, the next question is: where does a program keep information while it runs?
A program is not just a list of commands. It is also a small world of data: numbers, text, yes/no values, lists, and structured records. Variables give that data names so later statements can reuse it.
The lab below lets you choose different values and see how JavaScript identifies their type.
Values and variables
A value is a piece of data:
18
"Leaf"
trueA variable is a name that points to a value:
let age = 18;
const name = "Leaf";Read let age = 18 as: create a variable named age, and store the value 18 in it. After that, writing age means "use the value currently stored in age."
let and const
Modern JavaScript uses let and const to declare variables:
let count = 0; // can be reassigned later
const PI = 3.14159; // cannot be reassigned
count = count + 1; // OK
// PI = 3; // Error- Use
constby default when the variable should keep pointing to the same value. - Use
letwhen the value will change, such as a counter, score, or running total. - You may see old code using
var; new beginner code should avoid it.
Common data types
JavaScript values have different types:
| Type | Example | Used for |
|---|---|---|
| number | 42, 3.14, -8 | quantities, scores, prices |
| string | "hello", 'A' | text |
| boolean | true, false | yes/no conditions |
| undefined | undefined | a variable has no value yet |
| null | null | intentionally empty |
| array | [80, 92, 75] | ordered lists |
| object | { name: "Leaf", age: 18 } | named fields |
Use typeof to inspect a value:
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"typeof [1, 2, 3] returns "object" because arrays are a special kind of object in JavaScript. You will learn how arrays behave in section 3.12.Assignment and updating
Assignment stores a new value in a variable:
let score = 80;
score = 95;When updating a value, the right side is computed first:
let total = 10;
total = total + 5; // total becomes 15
total += 2; // shorter form; total becomes 17This pattern appears everywhere: counters, totals, progress bars, shopping carts, and form validation.
Strings and numbers are different
Quoted text is a string. Unquoted numeric data is a number:
console.log(18 + 1); // 19
console.log("18" + 1); // "181"The second line joins text because one side is a string. If a value comes from a text box or prompt, convert it before doing math:
const ageText = prompt("Age?");
const age = Number(ageText);
console.log(age + 1);