2.4 Dynamic Typing

One thing that sets JavaScript apart from many other programming languages is that it is a dynamic language. In a static language, the type of a variable is fixed at declaration time and cannot change later. In a dynamic language like JavaScript, the type of a variable can change at runtime depending on the value you assign to it.

Inspecting types with typeof

JavaScript provides a special operator called typeof to inspect the type of a value. Let's reuse the name variable from the previous lesson: it was initialized to a string, so typeof name returns "string". If we reassign name = 1, typeof name now returns "number". The type literally changed at runtime. That's dynamic typing in action.

let name = 'Brahim';
console.log(typeof name); // "string"
name = 1;
console.log(typeof name); // "number"

Note that typeof is a reserved keyword, so you cannot use it as a variable name. In the browser console, you can clear previous logs with Ctrl + L to keep your tests readable.

The primitive and object types

  • number: there is no distinction between integers and decimals — 17 and 1.5 are both of type number.
  • boolean: true or false, for example a flag like isApproved.
  • undefined: when a variable is declared without a value, both its value and its type are undefined.
  • object: when we inspect a more complex value such as selectedColors, typeof returns "object".

JavaScript organizes types into two main categories: primitive types (number, string, boolean, undefined, null, symbol) and reference types (objects, arrays, functions). What is an object exactly? That's the topic of the next video.