A data type defines the kind of value a variable can hold and what operations can be performed on it. JavaScript offers several data types split into two categories: primitive and non-primitive.
Primitive data types are the most basic data types in JavaScript that represent single, simple values.
| Type | Description | Examples |
|---|---|---|
| Number | Any number. Can be negative, decimal or natural. | 1, -99, 3.14195, 1e43, 42 |
| Bigint | Very large integer numbers. Used in very specific cases. | 1e100 |
| String | A sequence of characters | 'hello', '42' , ' ' , "A32" |
| Boolean | true of false | true or false |
| Null | Empty value | null |
| Undefined | A declared variable without a value | undefined |
| Symbol | A uniquely generated value | Symbol() |
Non-primitive data types are complex data structures that can hold multiple values from different types.
| Type | Description | Examples |
|---|---|---|
| Arrays | A list of multiple values | [1, 2, 3, 4, 5] |
['Banana', 'Apple', 'Pear'] |
||
| Objects | A combination of different values in a complex structure. | `{ |
| 'name': 'John', | ||
| 'age': 54, | ||
| 'location': 'Amsterdam' | ||
| }` |
Arrays and objects will be covered in depth in Week 4 - Data structures and loops.
Null is a value that represents the intentional absence of any value. It's explicitly assigned by a programmer to indicate "no value" or "empty".
let age = null; // Deliberately set to empty
Undefined means a variable has been declared but has not yet been assigned a value. It's JavaScript's default value for uninitialised variables.
let myVariable; // Declared but not assigned
console.log(myVariable); // undefined
Key differences:
null is an assignment value - you choose to set itundefined is JavaScript's default - it happens automaticallyIn practice, use null when you want to explicitly indicate "no value", and let JavaScript use undefined for variables that haven't been initialized yet.
You can use the typeof operator to get the type of a certain variable. As you can see in the following examples it returns the type of value that you have assigned to your variable:
let myString = 'Hi';
console.log(typeof myString); // 'string'
let myNumber = 1.23;
console.log(typeof myString); // 'number'
let myBoolean = false;
console.log(typeof myBoolean); // 'boolean'
JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).
For example, if you declare a variable and give it a value enclosed in quotes, JavaScript treats the variable as a string:
let myString = 'Hello';
You can also re-assign different types to the same variable:
let myString = 'Hello';
myString = 123;
myString = null;
myString = 'Bye';
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **
