Pular para o conteúdo principal
Módulo 1 · Lição 2 de 42/32 no curso~8 min
Lições do módulo (2/4)

Tipos primitivos

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

QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARS

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

Exercício#js.m1.l2.e1
Tentativas: 0Carregando…

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

Carregando editor…
Mostrar dica

You can pass any value or variable name to typeof.

Solução disponível após 3 tentativas

Review exercise

Exercício#js.m1.l2.e2
Tentativas: 0Carregando…

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

Carregando editor…
Mostrar dica

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

Solução disponível após 3 tentativas