Text and Numbers
Every value in JavaScript has a type. So far, you've used two types:
- numbers, such as
25or1.5, which you can calculate with; - text, such as
"Hello". Programmers call it a string, as in a string of characters.
That's why text needs quotes and numbers don't: 25 is a number, but "25" is text made of the characters 2 and 5. The type decides what an operator does. For example, + adds two numbers, but joins two strings:
console.log(5 + 3);
console.log("5" + "3");
console.log("5" + 3);This prints:
8
53
53The last line surprises many people. When one side of + is a string, JavaScript turns the other side into a string too, and joins them. That's why you can join text with numbers: "I am " + 25 + " years old." gives "I am 25 years old."
In the output, you can't see the type: console.log(5) and console.log("5") both print 5. To find out the type of a value, use typeof:
console.log(typeof 5);
console.log(typeof "5");This prints:
number
stringtypeof works with variables too: typeof price gives the type of the value stored in price.
A typical mistake is a number in quotes. Then + joins instead of adding, and the result looks strange:
const apples = "5";
console.log(apples + 1);This prints 51 instead of 6. When a result surprises you like this, check the types with typeof.
Instructions
The program should print Next year you will be 26, but it prints Next year you will be 251. Find out why: on a new line, print the type of age using typeof.
It prints string: age holds text, because its value is in quotes. Fix it: remove the quotes around 25, so that age holds a number. Then the program prints Next year you will be 26, and typeof prints number.
Start programming for free
9/12