Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Text and Numbers

Every value in JavaScript has a type. So far, you've used two types:

  • numbers, such as 25 or 1.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
53

The 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
string

typeof 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

  1. 1

    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.

  2. 2

    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.

Back

10/15

  1. 1. Printing
  2. 2. Arithmetic Operations
  3. 3. Comments
  4. 4. Variables
  5. 5. Changing a Variable's Value
  6. 6. Quiz: The Order of Commands
  7. 7. Constants
  8. 8. Division and Remainder
  9. 9. Joining Text
  10. 10. Text and Numbers
  11. 11. Quiz: Text and Numbers
  12. 12. Template Literals
  13. 13. Quiz: Template Literals
  14. 14. Reading Errors
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.