Data Types
Numbers, text, true/false, lists and more — the kinds of data JavaScript works with.
What you will learn
- Identify the main JavaScript data types
- Tell strings, numbers and booleans apart
- Use typeof to check a type
The types you will use most
| Type | Example | For |
|---|---|---|
| String | "Hello", 'Asha' | Text (in quotes) |
| Number | 42, 3.14 | Any number |
| Boolean | true, false | Yes/no values |
| Array | [1, 2, 3] | A list |
| Object | {name: "Asha"} | Grouped data |
| Undefined | undefined | No value yet |
| Null | null | Deliberately empty |
We can ask JavaScript what kind of value something is with the typeof keyword. Below we make one variable of each common type, then print the type of three of them.
<script>
let city = "Bengaluru"; // string
let age = 22; // number
let isStudent = true; // boolean
let skills = ["HTML","CSS"]; // array
document.write(typeof city + ", " + typeof age + ", " + typeof isStudent);
</script>typeof city asks "what kind is city?" and gives back the word "string". age is a plain number, so typeof age is "number"; isStudent is true/false, so it is "boolean". We join the three answers with + to print them on one line.
Note: Output: string, number, boolean
Watch out: Numbers have no quotes: age = 22. Strings need quotes: name = "22". "22" (string) and 22 (number) behave very differently — adding strings joins them, adding numbers sums them.
This next example shows exactly why quotes matter. The + symbol does two different jobs depending on the types around it.
<script>
document.write("5" + 3 + "<br>"); // "53" (string join)
document.write(5 + 3); // 8 (number sum)
</script>On the first line "5" is text (it has quotes), so + glues it to 3 and you get the text "53". On the second line both 5 and 3 are real numbers, so + adds them and you get 8. Same symbol, completely different result — all because of the quotes.
Note: Output: 53 8
Q. What is the data type of true?
✍️ Practice
- Create one variable of each type (string, number, boolean, array) and print its
typeof. - Predict the result of
"10" + 5and10 + 5, then test both.
🏠 Homework
- Make an array of your three favourite movies and print the whole array.