Module lessons (2/4)
Primitive types
Every value in JavaScript is either a primitive value or an object. Primitive types are immutable by nature: no operation modifies an existing string or number, but produces a new one.
Mental model: primitive types and typeof
| Primitive type | Example | Result of typeof x | Meaning |
|---|---|---|---|
string | 'ciao', "JS" | 'string' | Immutable text sequence |
number | 42, 3.14, NaN | 'number' | Integers and floating point IEEE-754 |
boolean | true, false | 'boolean' | Binary logical value |
undefined | let x; | 'undefined' | Variable or argument not yet assigned |
null | const selected = null; | 'object' (historical bug!) | explicit and intentional absence of value |
Progressive examples
1. Inspect primitive values with typeof
typeof 'hello'; // 'string'
typeof 42; // 'number'
typeof true; // 'boolean'
typeof undefined; // 'undefined'2. Immutability of primitive values
const word = 'javascript';
word.toUpperCase(); // restituisce 'JAVASCRIPT', NON modifica word
word; // ancora 'javascript'3. Distinguish null from undefined
let pendingScore; // undefined: nessuno ha ancora assegnato un valore
const emptyCart = null; // null: scelta esplicita di vuoto
typeof emptyCart === 'object'; // true (eredità JS dal 1995!)
emptyCart === null; // true (unico test affidabile)4. Explicit conversions and safe scope
Number('42'); // 42
Number('3.5'); // 3.5
Number('abc'); // NaN
String(99); // '99'
Boolean(''); // falseGuided laboratory
Exploring typeof on boolean
Write a single expression that returns the typeof of a Boolean value. The expected result is 'boolean'.
Show hint
Apply the unary operator typeof to true or false.
Solution available after 3 attempts
Explicit conversion to number
Convert the string raw = '128' to number and double it. The last expression must evaluate to 256.
Show hint
Use Number(raw) before multiplying by 2.
Solution available after 3 attempts
Safe classifier with null fix
Implement inspectType(value) that returns 'null' when value === null and typeof value in all other cases.
Show hint
Check if (value === null) return 'null'; as the first line of the function.
Solution available after 3 attempts
Check for understanding
Which expression precisely identifies whether payload is exactly null (and not undefined or an object)?
What does console.log(typeof Number('ciao')) print?