Data Types

JavaScript values are one of several built-in types.

Syntaxlet text = 'hi'; let num = 10; let flag = true;

JavaScript has several built-in data types. The most common are:

  • String — text, in quotes: 'hello'.
  • Number — any number: 42, 3.14.
  • Booleantrue or false.
  • Array — an ordered list: [1, 2, 3].
  • Object — key/value pairs: { name: 'Sam' }.

There are also null, undefined, and others.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Check whether a value returned from an API is a string or a number before processing it.
  • Guard against passing the wrong type to a function that expects a boolean flag.
  • Choose the correct data structure (array vs object) when modeling a list of user records.

More examples

Common primitive types

Declares variables covering the five most common JavaScript primitive types and logs their typeof results.

Example · js
const name = "Alice";      // string
const age = 30;           // number
const active = true;      // boolean
const score = null;       // null
let address;              // undefined
console.log(typeof name, typeof age, typeof active);

Objects and arrays are reference types

Shows that both plain objects and arrays report "object" for typeof, so Array.isArray is needed to distinguish them.

Example · js
const user = { id: 1, name: "Bob" };  // object
const tags = ["js", "web"];           // array (also an object)
console.log(typeof user);  // "object"
console.log(Array.isArray(tags)); // true

Dynamic typing in action

Demonstrates JavaScript's dynamic typing: the same variable can hold different types at different times.

Example · js
let value = 42;
console.log(typeof value); // "number"
value = "hello";
console.log(typeof value); // "string"

Discussion

  • Be the first to comment on this lesson.
Data Types — JavaScript | SoundsCode