Codiqo

Learn JavaScript · lesson 4 of 60 · about 7 minutes

typeof and Comments

See what type a value really is, why text from a page breaks your maths, and leave notes in your code.

What you'll learn

  • Tell strings, numbers and booleans apart with typeof
  • Spot that text from a page is always a string
  • Write comments with // and /* */

Why did 18 + 1 make 181?

Your page shows someone's age, 18. Add 1 to it and you get 181, not 19. To see why, you need to know what type a value is.

Most values are one of three types: strings (text), numbers and booleans (true or false). typeof tells you which.

typeof names the type

console.log(typeof "18");
console.log(typeof 18);
console.log(typeof true);

Output

string
number
boolean

Text from a page is always a string

Everything you read from a page, its text or what someone typed in a box, arrives as a string, even when it looks like a number. And when either side of + is a string, + joins instead of adding.

You'll learn to turn strings into numbers soon. For now, typeof shows you when it's needed.

The age on the page is text

const age = document.querySelector("#age").textContent;
console.log(typeof age);
console.log(age + 1);

Output

string
181

Notes for humans

A comment is a note JavaScript skips. // makes the rest of the line a comment. /* and */ wrap a comment over several lines.

Use comments to say *why* the code does something, not what every line does.

Comments are skipped when the code runs

// Greet visitors when the page opens
console.log("Hi!"); // shown in the console
/* The footer is filled in
   by a later lesson */

Output

Hi!

Tip

true and false are written in lowercase, without quotes. With quotes, "true" is just text.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.