Chapter 1 - Values, Types, and Operators


JavaScript uses a fixed number of bits, 64 of them, to store a single number value.


You can use single quotes, double quotes, or backticks to mark strings, as long as the quotes at the start and the end of the string match.

JavaScript’s representation uses 16 bits per string element. many emoji, take up two “character positions” in JavaScript strings.

"con" + "cat" + "e" + "nate"

Backtick-quoted strings, usually called template literals, can do a few more tricks. Apart from being able to span lines, they can also embed other values.

`half of 100 is ${100 / 2}`

When you write something inside ${} in a template literal, its result will be computed, converted to a string, and included at that position. The example produces “half of 100 is 50”.

Unary operators

console.log(typeof 4.5)
// → number
console.log(typeof "x")
// → string

Boolean values


There is only one value in JavaScript that is not equal to itself, and that is NaN (“not a number”).

console.log(NaN == NaN)
// → false

Empty values

There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.

Automatic type conversion

console.log(8 * null)
// → 0
console.log("5" - 1)
// → 4
console.log("5" + 1)
// → 51
console.log("five" * 2)
// → NaN
console.log(false == 0)
// → true

When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules.
This is called type coercion.

When you want to test whether a value has a real value instead of null or undefined, you can compare it to null with the == (or !=) operator.

When you do not want any type conversions to happen, there are two additional operators: === and !==. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal. So "" === false is false as expected.

The || operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise.

console.log(null || "user")
// → user
console.log("Agnes" || "user")
// → Agnes

0, NaN, and the empty string ("") count as false, while all the other values count as true

The && operator works similarly but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.