On this page

Variables and data types

15 min read TextCh. 1 — Fundamentals

Variables

JavaScript has three ways to declare variables: const, let, and var. In modern JavaScript, we prefer const by default and let when we need to reassign.

const vs let

  • const — Cannot be reassigned. Use it whenever you can
  • let — Can be reassigned. Use it only when you need to change the value
  • var — Avoid it. It has problematic behaviors

Primitive types

JavaScript has 7 primitive types:

Type Example Description
string 'Hello' Text strings
number 42, 3.14 Numbers (integers and decimals)
boolean true, false True or false
null null Intentional absence of value
undefined undefined Variable with no assigned value
symbol Symbol('id') Unique identifier
bigint 9007199254740991n Large integers

Dynamic typing

JavaScript is dynamically typed: a variable can hold any type of value and change type at runtime. This is flexible but can cause subtle errors.

The typeof operator

The typeof operator allows you to check the type of a value at runtime. It is useful for validations and debugging.

Note: typeof null returns "object" — this is a historic bug in JavaScript that was never fixed for compatibility reasons.


Practice

  1. Declare variables with const and let: Create a constant APP_NAME with the value 'My App' and a variable counter with value 0. Reassign counter to 5 and verify that APP_NAME cannot be reassigned.
  2. Identify types with typeof: Declare a variable of each primitive type (string, number, boolean, null, undefined) and use typeof to print the type of each one to the console.
  3. Explore dynamic typing: Create a variable with let assigning it a number, then reassign it to a string. Use typeof before and after the reassignment to observe the type change.

In the next lesson we will learn about operators and control flow in JavaScript.

Avoid var
Never use var in modern code. It has scope issues (function-scoped instead of block-scoped) and hoisting behavior that causes hard-to-detect bugs.
javascript
// const - cannot be reassigned
const name = 'Carlos';
const PI = 3.14159;

// let - can be reassigned
let counter = 0;
counter = 1;

// Primitive types
const text = 'Hello world';         // string
const age = 25;                     // number
const active = true;                // boolean
const empty = null;                 // null
let notDefined;                     // undefined

// typeof
console.log(typeof text);     // "string"
console.log(typeof age);      // "number"
console.log(typeof active);   // "boolean"
console.log(typeof empty);    // "object" (historic bug!)