PLAINFINCH learn by building

Values and types

You will tell strings, numbers and booleans apart and convert text to a number before doing maths with it.

What is a type?

Every value in JavaScript has a type, and the type decides what you can do with it. You can multiply numbers, change text to upper case, and flip a true-or-false value. Trying to do number things with text, or text things with numbers, is where many beginner bugs come from.

JavaScript decides types as the code runs, not ahead of time. A variable has no fixed type; the value inside it does. That makes the language quick to write and easy to get wrong, because nothing stops you from adding a string to a number. Knowing the handful of types and how they convert is the cure.

FigureSeven JavaScript types with an example and the typeof result for each: string, number, boolean, undefined, null which reports object, object and array which reports object.Seven JavaScript types with an example and the typeof result for each: string, number, boolean, undefined, null which reports object, object and array which reports object.
Each value has a type. The first five are simple values; objects and arrays hold other values. typeof reports object for null and arrays, so use === null and Array.isArray() to tell them apart.

What are strings, numbers and booleans?

A string is text. You write it in single quotes, double quotes or backticks: 'Wren', "Wren", or ` Wren . Backticks make a template literal, which can drop values in with ${...}`. Pick one quote style for plain strings and use it everywhere; PlainFinch uses single quotes.

A number covers both whole numbers and decimals. 24, 4.5 and -3 are all the same type. JavaScript stores them as floating-point values, which is why 0.1 + 0.2 gives 0.30000000000000004. For money, work in pennies or round when you display the value.

A boolean is either true or false, written without quotes. Comparisons produce booleans: loavesLeft > 0 is true while there is bread left. Names like isOpen and hasPaid usually hold booleans.

const bird = 'Goldfinch';    // string
const count = 12;             // number
const isRare = false;         // boolean
console.log(`${bird}: ${count}`);

What is the difference between null and undefined?

Both mean "no value", with a difference in who said so. undefined is what JavaScript gives you when something was never set: a declared variable with no value, a missing property, a function with no return. null is a value a programmer puts there on purpose to say "empty for now".

A good rule: let JavaScript produce undefined, and write null yourself when you want to mark something as deliberately empty, such as let selectedBird = null; before anyone has picked one. document.querySelector returns null when it finds no element, which is the source of many TypeErrors.

let selectedBird = null;          // nothing picked yet
const club = { name: 'Heron Watchers' };
console.log(club.founded);        // undefined

How do you check a value's type?

The typeof operator returns the type as a string: 'string', 'number', 'boolean', 'undefined', 'object', 'function' and a couple of rarer ones. It is the quickest way to answer "why is this not adding up". Log typeof of each value right before the line that misbehaves.

typeof has two quirks. typeof null is 'object', a bug from 1995 that can never be fixed without breaking old websites. Check for null with value === null. And arrays report 'object' too, so use Array.isArray(value) to spot them.

The Step lens also helps: strings appear with quotes around them, numbers without. A value shown as "5" is text, and that one detail explains a lot of odd results.

console.log(typeof 'Wren');     // 'string'
console.log(typeof 3);          // 'number'
console.log(typeof null);       // 'object' (a known quirk)
console.log(Array.isArray([])); // true

What are objects and arrays?

Strings, numbers, booleans, null and undefined are simple values. Objects and arrays are containers that hold other values. An object groups named values, such as a bird's name and count. An array is an ordered list, such as the loaves in a basket.

You read from an object with a dot and the property name, and from an array with square brackets and a position that starts at 0. Both get full lessons later; for now, recognise them when you see {} and [].

const sighting = { bird: 'Heron', count: 1 };
const basket = ['Rye', 'Sourdough'];
console.log(sighting.bird, basket[0]); // Heron Rye

Why is '5' + 1 equal to '51'?

The + operator does two jobs: it adds numbers and joins strings. When either side is a string, JavaScript converts the other side to a string and joins them. '5' + 1 becomes '5' + '1', which is '51'.

The other maths operators only work with numbers, so they convert strings to numbers instead. '5' - 1 is 4, '5' * 2 is 10. That inconsistency is why bugs appear only in additions.

On real pages this comes up all the time, because everything you read from the page is a string. The value of an input, the text of an element, data from a URL: all strings, even when they look like numbers. Convert them the moment you read them.

AI-generated form code often skips this step. If a total on your page shows digits glued together, such as Total: 4.53.25, look for a + between a value read from the page and a number, and wrap the page value in Number().

console.log('5' + 1);   // '51'
console.log('5' - 1);   // 4
console.log(1 + 2 + '3'); // '33' (left to right)

How do you convert between strings and numbers?

Number(value) turns a string into a number. It accepts the whole string or nothing: Number('4.50') is 4.5, Number('') is 0, and Number('4 loaves') is NaN. String(value) goes the other way and works on any value, including null and undefined.

parseInt and parseFloat read numbers from the start of a string and ignore what follows, so parseFloat('4.5kg') gives 4.5. That is handy for values with units and risky for form input, because a typo like '4o' becomes 4 without any error. Use Number() by default.

NaN means "not a number", although typeof NaN is 'number'. Any maths with NaN gives NaN, so one bad conversion spreads through every calculation after it. NaN is also never equal to anything, even itself, so check it with Number.isNaN(value).

const qty = Number('3');          // 3
const bad = Number('three');      // NaN
console.log(Number.isNaN(bad));   // true
console.log(String(42) + '!');    // '42!'

What are truthy and falsy values?

When JavaScript needs a true-or-false answer, for example in an if, it converts whatever value it gets into a boolean. Exactly eight values become false: false, 0, -0, 0n, '' (the empty string), null, undefined and NaN. These are called falsy. Every other value is truthy, including '0', 'false', [] and {}.

That lets you write if (name) to mean "if a name was entered". It also causes surprises: a count of 0 is falsy, so code that checks if (count) treats zero birds the same as no data at all. The Making decisions lesson returns to this, and Boolean(value) shows you which way any value falls.

console.log(Boolean(''));      // false
console.log(Boolean('0'));     // true
console.log(Boolean(0));       // false
console.log(Boolean([]));      // true

Field notes

  • Every value has a type, and the type decides what you can do with it.
  • When either side of + is a string, JavaScript joins the values as text.
  • Number() turns text into a number, or gives NaN if the text is not a number.
  • Use typeof to check which type a value really has.

Easy to get wrong

Form values are always strings, so + joins text and '3' + 2 gives '32'. Convert with Number() first.

typeof null is 'object', never 'null', so the first check is always false. Compare with === null directly.

NaN is not equal to anything, including itself, so the comparison is always false. Number.isNaN is the reliable test.

Questions people ask

Should I use single or double quotes?

Either works. Pick one and stay consistent; use backticks when you need ${...} or a line break.

Why is typeof NaN 'number'?

NaN is a special value inside the number type that marks a failed calculation. It behaves like a number in maths, which is why it spreads.

Is there a separate integer type?

No. Whole numbers and decimals share one number type. BigInt exists for very large whole numbers, written with an n like 10n, and you rarely need it on web pages.

Does JavaScript have a date type?

Dates are objects made with new Date(). The Numbers and dates lesson covers them.

Keep going