Chapter 03
Data Types
Not all values are the same kind of thing. The number 42 behaves differently from the word "hello", which behaves differently from a yes/no answer. These different kinds are called types. JavaScript has a handful of basic ones, and you'll use three of them constantly: numbers, strings, and booleans.
Numbers
Numbers are written just as you'd expect - no quotes. Whole numbers and decimals are both just "numbers" in JavaScript; there's no separate type for them.
const apples = 5;
const price = 2.50;
const temperature = -3;
console.log(apples + 2); // 7
console.log(price * 4); // 10You can do arithmetic directly: + adds, - subtracts, * multiplies, / divides. We'll cover all of these in the next chapter.
Strings (Text)
A string is a piece of text. It's called a "string" because it's a string of characters joined together. You must wrap it in quotes - single ' ' or double " ", it doesn't matter, as long as they match:
const greeting = "Hello";
const name = 'Ada';
console.log(greeting); // HelloThe quotes are not part of the value - they just tell JavaScript "this is text." Without them, JavaScript thinks you're referring to a variable and gets confused:
const city = London; // Error! London is not defined.
const city2 = "London"; // Correct - it's text."5" is text, 5 is a number. They look similar but behave very differently, which trips up almost every beginner. We'll see why in Chapter 5.Booleans (True or False)
A boolean has only two possible values: true or false. That's it. They answer yes/no questions and are the foundation of decision-making (Chapter 6):
const isRaining = true;
const hasFinished = false;
console.log(isRaining); // trueNote there are no quotes - true is a special built-in value, whereas "true" would just be the word "true" as text.
Nothing: null and undefined
Two special values represent "no value." They're subtly different:
undefinedmeans "this hasn't been given a value yet." A variable you declare but don't assign isundefined.nullmeans "deliberately empty." You use it to say "there is nothing here on purpose."
let winner;
console.log(winner); // undefined - never assigned
let selected = null;
console.log(selected); // null - intentionally emptyYou'll meet these constantly, usually when something you expected to be there isn't. For now, just recognise them.
Checking a Value's Type
If you're ever unsure what type a value is, ask JavaScript with typeof:
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined);// "undefined"typeof check is often the fastest way to spot the problem - very often a value you thought was a number is secretly a string.