JavaScript Data Types
A data type is the kind of a value. JavaScript values come in a few basic kinds, and each kind behaves in its own way.
Four basic kinds
A data type is the kind of a value, and typeof names that kind. The typeof operator reports the type of each value here.
let city = "Oslo";
let score = 42;
let isReady = true;
let winner;
console.log(typeof city);
console.log(typeof score);
console.log(typeof isReady);
console.log(typeof winner);A type can change
A variable can hold a new value of a different type.
let item = "pen";
console.log(typeof item);
item = 5;
console.log(typeof item);Text and numbers differ
Quotes make text, so "42" is a string. The value 42 without quotes is a number.
let label = "42";
let amount = 42;
console.log(typeof label);
console.log(typeof amount);Example
let playerName = "Ana";
let playerScore = 120;
let passed = true;
let prize;
console.log(typeof playerName);
console.log(typeof playerScore);
console.log(typeof passed);
console.log(typeof prize);Key points
- A string is text, and a string value sits inside quotes.
- A number is a numeric value, and it needs no quotes.
- A boolean is a value that is either true or false.
- A variable declared with no value holds undefined.
- An object is a value that groups related values together.
- The null value means no value on purpose, and its type is object.
In this example, four variables hold four different types. The string "Ana" reports string, and the number 120 reports number. The boolean true reports boolean, and the variable with no value reports undefined.
Note
typeof null reports "object". That answer is a long-standing mistake in JavaScript.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does typeof 42 report?