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.
'ciao'; // string
42; // number
true; // boolean
null; // null
undefined; // undefinedThe 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:3and3.14are bothnumber.boolean— truth or falsehood. Only allowstrueandfalse.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:
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(...):
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
Write a single expression that returns the `typeof` of a boolean value. The expected result is the string 'boolean'.
Show hint
You can pass any value or variable name to typeof.
Solution available after 3 attempts
Review exercise
Convert the string '128' to a number and double it. The last expression must evaluate to 256.
Show hint
Use Number(...) for the explicit conversion, then multiply by 2.
Solution available after 3 attempts