Brainlag
  1. Library
  2. Concepts
  3. Web

Values and types

Every JavaScript value has a type. typeof tells you which, and the type decides whether + adds two numbers or glues two strings together.

Web8 min

Every value has a type

A value is a piece of data: 42, "Neon Rain", true. Each one has a type, and typeof tells you which:

JavaScript
typeof 42           // "number"
typeof "42"         // "string"
typeof true         // "boolean"
typeof undefined    // "undefined"

Quotes make a string, even when the text inside looks like a number. "42" is two characters, not the number forty-two. Values you get from a text box, a URL or a file always arrive as strings.

Plus adds or glues

+ checks its two sides. Two numbers: it adds. A string on either side: it glues them into one longer string.

JavaScript
5 + 3        // 8
"5" + 3      // "53"
"Level " + 3 // "Level 3"

That second line is the classic bug: a score read from a form plus a bonus gives "53", not 8. Turn the string into a number first with Number("5"), then add. Other maths signs (-, *, /) always try to make numbers, which is why "5" - 3 is 2 and hides the problem.

Run it: same digits, different types

Run it, then change one thing and run it again.

main.js to run
const kills = 12;
const typed = "12";

console.log(typeof kills, typeof typed);
console.log(kills + 3);
console.log(typed + 3);
console.log(Number(typed) + 3);
console.log("Score: " + kills);

A bonus that breaks the total

The coins come from a form, so they are a string. The total should be Total: 175, but it prints Total: 15025. Fix it so the maths works.

exercise_1.js to run
const coinsFromForm = "150";
const bonus = 25;
const total = coinsFromForm + bonus;
console.log("Total: " + total);

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.