Like any other programming language, JavaScript supports multiple data types. Understanding these types and the different operations you can perform on them is essential to coding effectively with JavaScript.
JavaScript Data Types
The data types supported by JavaScript fall into two categories: primitive and object types. After introducing some key concepts about typing in JavaScript and an overview of primitive data types in the last post, I introduce object data types in this post.
Object Data Types
Object types are containers that hold collections of values of primitive types or more complex entities composed of object types. Object types are mutable and are referenced by identifiers. There are eight object types in JavaScript, which I present in the two tables below.
In the first table, I briefly describe the type, the mechanism to create it, some main methods you can apply to it, an example, and the result of its execution.
In the second table, I resume the way you can iterate over these types with some examples. Let’s note that I consider only the types that we iterate over. I will exclude the others that are not naturally iterable.
Object Data Types in JavaScript: Creating and Main Methods |
||||
Type |
Description |
Creating |
Main Methods |
Code Snippet |
Object |
- Container for multiple values - Collection of key-value pairs - Objects can have methods
|
- Using object literal: let obj = {key1:value1, key2:value2, ...};
- Using Object constructor: let obj = new Object(); obj.key1 = value1; obj.key2= value2; ...
- Using a class: class ObjClass { constructor(val1, val2, ..) { this.property1 = val1; this.property2 = val2; ... } } let myObj = new ObjClass(value1, value2, ...);
|
- Add or update a property: obj.property = value
- Delete a property: delete obj.property;
- Copy an object’s properties to another: Object.assign();
|
let employee = { firstName: 'Marie', lastName: 'Hitman', email:"marie@gmail.com", age: 26, salary:5000, getSalary: function() { return this.salary + '$'; } }; console.log(employee.firstName); console.log(employee.email); console.log(employee['lastName']); console.log(employee['age']); console.log(employee.getSalary());
|
Array |
- Ordered collection of elements accessible using indexes - Dynamically sized
|
- Using literals: let myArray = [elem1, elem2, ...];
- Using Array constructor: let myArray = new Array(elem1, elem2, ...);
- From a set: let myArray = Array.from(mySet); |
Access an element with an index: let element = myArray[index];
Add an element: myArray.push(element);
Remove an element from the beginning: myArray.shift();
Remove an element from the end: myArray.pop();
Update an element: myArray[index] = newElement
|
let nums = [45, 23, -80, 12];
let result = []; nums.forEach((num) => { result.push(num ** 4); });
console.log('Quadruples of each element in :', nums, 'are', result); |
Function |
Block of code to perform a specific task |
- Using function definition: function myFunction(p1, ..,pn){ //code of the function } |
|
function applyExpArray(arr, n) {
let result = []; arr.forEach((num) => { result.push(num ** n); }); return result; }
let arr = [45, 23, -80, 12]; console.log(applyExpArray(arr, 2));
|
Date |
One moment in time |
- Using Date constructor with or without parameter: let myDate = new Date(dateString); let now = new Date();
|
- Get date component (year, month, day, etc.): myDate.getFullYear(), ..
- Set date component (year, month, day, etc.): myDate.setFullYear(myYear); .. |
let myDate = new Date("04.04.2020"); console.log(myDate); console.log("Year:", myDate.getFullYear()); console.log("Month:", myDate.getMonth()); console.log("Day:", myDate.getDate()); |
Map |
- Collection of key-value pairs - Keys should be unique - Keys can be of any type |
- Using Map constructor: let map = new Map();
|
- Add a new key-value pair: set(key, value)
- Get the value associated to the key: get(key)
- Remove the key-value pair: delete(key)
- Check if a key exists: has(key)
- Remove all key-value pairs: clear()
- Get the number of the key-value pairs: size
|
let personMap = new Map(); personMap.set(100, 'Marie'); personMap.set(200, 'Bob'); personMap.set(300, 'Jack'); console.log(personMap.get(100)); console.log(personMap.get(300)); console.log(personMap.has(400)); console.log(personMap.size); |
Set |
Unordered collection of elements where each element is unique |
- Using Set constructor: let mySet = new Set([elem1, elem2,..]);
- From an array: let myArray = [elem1, elem2,..]; let mySet = new Set(myArray); |
- Add a new element: add(element)
- Check if an element exists: has(element)
- Remove an element: delete(element)
- Remove all elements: clear()
- Get the number of elements: size
|
let carSet = new Set(['BMW', 'Ferrari', 'Toyota', 'Porsche']); let index = 1; for (let car of carSet) { console.log('Car' + index + ':', car); index++; } console.log('Size of carSet:', carSet.size); carSet.clear(); console.log('Size of carSet:', carSet.size); |
WeakMap |
- Similar to Map - A Key must be an object. - A Key is weakly referenced: it is garbage collected and its entry will be removed, when there is no reference to it.
|
- Using WeakMap constructor: let weakMap = new WeakMap(); |
- set(key, value) - get(key) - delete(key) - has(key) |
let key1 = {id: 100}; let key2 = {id: 200}; let p1 = {name: 'Marie Hitman', age: 26}; let p2 = {name: 'John Wayne', age: 40}; let personMap = new WeakMap(); personMap.set(key1, p1); personMap.set(key2, p2); console.log(personMap.get(key1)); console.log(personMap.get(key1).name); console.log(personMap.get(key2).age);
|
WeakSet |
- Similar to Set - An element must be an object - An element is weakly referenced
|
- Using WeakSet constructor: let weakSet = new WeakSet(); |
- add(element) - has(element) - delete(element) |
let perWeakSet = new WeakSet(); let person1 = { firstName: 'Joe', firstName: 'Doe'}; let person2 = { firstName: 'Marie', firstName: 'Hitman'}; perWeakSet.add(person1); perWeakSet.add(person2); console.log(perWeakSet.has(person1)); perWeakSet.delete(person1); console.log(perWeakSet.has(person1)); console.log(perWeakSet.has(person2)); |
Object Data Types in JavaScript: Iteration |
|||
Type |
Iterating Over |
Code Snippet |
Code Output |
Object |
- Iterate over keys using for...in loop: for (let key in myObj) { console.log(key + ': ' + myObj[key]); }
- Iterate over Object.keys() using forEach: let keys = Object.keys(myObj); keys.forEach(key => { console.log(key + ': ' + myObj[key]); });
- Iterate over Object.entries() using forEach: let entries = Object.entries(myObj); entries.forEach(([key, value]) => { console.log(key + ': ' + value); });
|
for (let key in employee){ console.log(key, "=", employee[key]) }
|
firstName = Marie lastName = Hitman email = marie@email.com age = 26 salary = 5000 getSalary = Æ’ () { return this.salary + '$'; } |
Array |
- Using for loop: for (let i = 0; i < myArray.length; i++) { console.log(myArray[i]); }
- Using for...of loop: for (let value of myArray) { console.log(value); }
- Using forEach method: myArray.forEach(function(value) { console.log(value); });
- Using map method: myArray.map(value => { console.log(value); });
- Using for...in Loop: for (let index in myArray) { console.log(myArray[index]); } |
for (let num of nums) { console.log('Double of:', num, 'is', num*2); } for (let index in nums) { console.log('Element', nums[index], 'is at the index:', index); } |
Double of: 45 is 90 Double of: 23 is 46 Double of: -80 is -160 Double of: 12 is 24 Element 45 is at the index: 0 Element 23 is at the index: 1 Element -80 is at the index: 2 Element 12 is at the index: 3 |
Map |
- Iterating over keys using for..of loop: for (let key of myMap.keys()) { console.log(key); }
- Iterating over values using for..of loop: for (let value of myMap.values()) { console.log(value); }
- Iterating over entries using for..of loop: for (let [key, value] of myMap.entries()) { console.log(key, value); }
- Iterating over keys and entries using forEach: myMap.forEach((value, key) => { console.log(key, value); }); |
for (let value of personMap.values()) { console.log(value); }
personMap.forEach((value, key) => { console.log(key + ':', value); }); |
Marie Bob Jack 100: Marie 200: Bob 300: Jack |
Set |
- Using for..of loop: for (let item of setName) { console.log(item); }
- Using forEach: setName.forEach((value) => { console.log(value); }); |
let citySet = new Set(['Vienna', 'Salzburg', 'Graz', 'Klagenfurt', 'Innsbruck']);
citySet.forEach((city) => { console.log(city); });
|
Vienna Salzburg Graz Klagenfurt Innsbruck |