Skip to main content
eLearner.app
Module 1 · Lesson 2 of 42/32 in the course~8 min
Module lessons (2/4)

Primitive types

Every value in JavaScript has a type. Primitive types are the basic building blocks of the language: they come out of nowhere, they don't have properties of their own (even if sometimes they seem to), and you'll use them hundreds of times a day.

JS
'ciao'; // string
42; // number
true; // boolean
null; // null
undefined; // undefined

The five types you use every day

  • string — text. Delimited with single quotes '…', double quotes "…" or backticks `…` (template literals, which we'll see in the next module).
  • number — numbers. JS doesn't distinguish integers and decimals: 3 and 3.14 are both number.
  • boolean — truth or falsehood. Only allows true and false.
  • null — "no value", intentionally empty. You set it yourself when you want to say "there is nothing here yet".
  • undefined — "no value", implicitly empty. It's the default value of variables declared but not initialized, and of function parameters that were not passed.

Inspecting a type with typeof

The typeof operator returns a string describing the type of the value:

JS
typeof 'ciao'; // 'string'
typeof 42; // 'number'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof null; // 'object'  ← rumore storico, non un vero "oggetto"

Type conversions

Often you receive a string (e.g. from an HTML input) and need to turn it into a number, or vice versa. Explicit conversions are done with the functions Number(...) and String(...):

JS
Number('42'); // 42
Number('3.14'); // 3.14
Number('ciao'); // NaN   ← Not-a-Number, "non rappresenta un numero"

String(42); // '42'
String(true); // 'true'

Try it

Exercise#js.m1.l2.e1
Attempts: 0Loading…

Write a single expression that returns the `typeof` of a boolean value. The expected result is the string 'boolean'.

Loading editor…
Show hint

You can pass any value or variable name to typeof.

Solution available after 3 attempts

Review exercise

Exercise#js.m1.l2.e2
Attempts: 0Loading…

Convert the string '128' to a number and double it. The last expression must evaluate to 256.

Loading editor…
Show hint

Use Number(...) for the explicit conversion, then multiply by 2.

Solution available after 3 attempts