On this page
Variables and data types
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 canlet— Can be reassigned. Use it only when you need to change the valuevar— 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 nullreturns"object"— this is a historic bug in JavaScript that was never fixed for compatibility reasons.
Practice
- Declare variables with const and let: Create a constant
APP_NAMEwith the value'My App'and a variablecounterwith value0. Reassigncounterto5and verify thatAPP_NAMEcannot be reassigned. - Identify types with typeof: Declare a variable of each primitive type (
string,number,boolean,null,undefined) and usetypeofto print the type of each one to the console. - Explore dynamic typing: Create a variable with
letassigning it anumber, then reassign it to astring. Usetypeofbefore 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.
// 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!)
Sign in to track your progress