Object Data Types in JavaScript
Object Data Types in JavaScript
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.
1
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 - Container for - Using object literal: - Add or update a property: let employee = { Marie
multiple values let obj = {key1:value1, obj.property = value firstName: 'Marie', [email protected]
- Collection of key2:value2, ...}; lastName: 'Hitman', Hitman
key-value pairs - Delete a property: 26
- Objects can have - Using Object constructor: delete obj.property; email:"[email protected]", 5000$
methods let obj = new Object(); age: 26,
obj.key1 = value1; - Copy an object’s salary:5000,
obj.key2= value2; properties to another: getSalary: function() {
... Object.assign(); return this.salary + '$';
}
- Using a class: };
2
class ObjClass { console.log(employee.firstN
constructor(val1, val2, ..) { ame);
this.property1 = val1; console.log(employee.email
this.property2 = val2; );
... console.log(employee['lastN
} ame']);
} console.log(employee['age'])
let myObj = new ;
ObjClass(value1, value2, ...); console.log(employee.getSal
ary());
Array - Ordered - Using literals: Access an element with an let nums = [45, 23, -80, 12]; Quadruples of each
collection of let myArray = [elem1, index: let element = element in : (4) [45,
elements elem2, ...]; myArray[index]; let result = []; 23, -80, 12] are
accessible using nums.forEach((num) => { (4) [4100625,
indexes - Using Array constructor: Add an element: result.push(num ** 4); 279841, 40960000,
- Dynamically let myArray = new myArray.push(element); }); 20736]
sized Array(elem1, elem2, ...);
Remove an element from console.log('Quadruples of
- From a set: the beginning: each element in :', nums,
let myArray = myArray.shift(); 'are', result);
Array.from(mySet);
Remove an element from
the end:
myArray.pop();
3
Update an element:
myArray[index] =
newElement
Function Block of code to - Using function definition: function [2025, 529, 6400,
perform a specific function myFunction(p1, ..,pn) applyExpArray(arr, n) { 144]
task {
//code of the function let result = [];
} arr.forEach((num) => {
result.push(num ** n);
});
return result;
}
Date One moment in - Using Date constructor with - Get date component (year, let myDate Sat Apr 04 2020
time or without parameter: month, day, etc.): = new Date("04.04.2020"); 00:00:00
let myDate myDate.getFullYear(), .. console.log(myDate); GMT+0200
= new Date(dateString); console.log("Year:", (Central European
let now = new Date(); - Set date component (year, myDate.getFullYear()); Summer Time)
month, day, etc.): console.log("Month:", Year: 2020
myDate.setFullYear(myYear myDate.getMonth()); Month: 3
4
); .. console.log("Day:", Day: 4
myDate.getDate());
Map - Collection of - Using Map constructor: - Add a new key-value pair: let personMap = new Marie
key-value pairs let map = new Map(); set(key, value) Map(); Jack
- Keys should be personMap.set(100, false
unique - Get the value associated to 'Marie'); 3
- Keys can be of the key: get(key) personMap.set(200, 'Bob');
any type personMap.set(300, 'Jack');
- Remove the key-value pair: console.log(personMap.get(
delete(key) 100));
console.log(personMap.get(
- Check if a key exists: 300));
has(key) console.log(personMap.has(
400));
- Remove all key-value pairs: console.log(personMap.size
clear() );
Set Unordered - Using Set constructor: - Add a new element: let carSet = new Car1: BMW
collection of let mySet = new Set([elem1, add(element) Set(['BMW', 'Ferrari', Car2: Ferrari
elements where elem2,..]); 'Toyota', 'Porsche']); Car3: Toyota
5
each element is - Check if an element exists: let index = 1; Car4: Porsche
unique - From an array: has(element) for (let car of carSet) { Size of carSet: 4
let myArray = [elem1, console.log('Car' + index Size of carSet: 0
elem2,..]; - Remove an element: + ':', car);
let mySet = new Set(myArray); delete(element) index++;
}
- Remove all elements: console.log('Size of carSet:',
clear() carSet.size);
carSet.clear();
- Get the number of console.log('Size of carSet:',
elements: size carSet.size);
WeakMap - Similar to Map - Using WeakMap constructor: - set(key, value) let key1 = {id: 100}; {name: 'Marie
- A Key must be let weakMap = new - get(key) let key2 = {id: 200}; Hitman', age: 26}
an object. WeakMap(); - delete(key) let p1 = {name: 'Marie Marie Hitman
- A Key is weakly - has(key) Hitman', age: 26}; 40
referenced: it is let p2 = {name: 'John
garbage collected Wayne', age: 40};
and its entry will let personMap = new
be removed, when WeakMap();
there is no personMap.set(key1, p1);
reference to it. personMap.set(key2, p2);
console.log(personMap.get(
key1));
console.log(personMap.get(
key1).name);
6
console.log(personMap.get(
key2).age);
WeakSet - Similar to Set - Using WeakSet constructor: - add(element) let perWeakSet = new true
- An element must let weakSet = new WeakSet(); - has(element) WeakSet(); false
be an object - delete(element) let person1 = { firstName: true
- An element is 'Joe', firstName: 'Doe'};
weakly referenced 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));
7
Object Data Types in JavaScript: Iteration
Object - Iterate over keys using for...in loop : for (let key in employee){ firstName = Marie
for (let key in myObj) { console.log(key, "=", lastName = Hitman
console.log(key + ': ' + myObj[key]); employee[key]) email =
} } [email protected]
age = 26
- Iterate over Object.keys() using forEach: salary = 5000
let keys = Object.keys(myObj); getSalary = ƒ () {
keys.forEach(key => { return this.salary +
console.log(key + ': ' + myObj[key]); '$';
}); }
Array - Using for loop: for (let num of nums) { Double of: 45 is 90
for (let i = 0; i < myArray.length; i++) { console.log('Double of:', num, Double of: 23 is 46
console.log(myArray[i]); 'is', num*2); Double of: -80 is -160
8
} } Double of: 12 is 24
for (let index in nums) { Element 45 is at the
- Using for...of loop: console.log('Element', index: 0
for (let value of myArray) { nums[index], 'is at the index:', Element 23 is at the
console.log(value); index); index: 1
} } Element -80 is at the
index: 2
- Using forEach method: Element 12 is at the
myArray.forEach(function(value) { index: 3
console.log(value);
});
Map - Iterating over keys using for..of loop: for (let value of Marie
for (let key of myMap.keys()) { personMap.values()) { Bob
console.log(key); console.log(value); Jack
} } 100: Marie
200: Bob
9
- Iterating over values using for..of loop: personMap.forEach((value, key) 300: Jack
for (let value of myMap.values()) { => {
console.log(value); console.log(key + ':', value);
} });
10
Found it useful?
11