0% found this document useful (0 votes)
4 views

Object Data Types in JavaScript

The document provides an overview of object data types in JavaScript, categorizing them into primitive and object types. It details eight object types, including Object, Array, Function, Date, Map, Set, WeakMap, and WeakSet, along with their creation methods and main methods. Additionally, it explains how to iterate over these object types using various techniques.

Uploaded by

ta89725
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Object Data Types in JavaScript

The document provides an overview of object data types in JavaScript, categorizing them into primitive and object types. It details eight object types, including Object, Array, Function, Date, Map, Set, WeakMap, and WeakSet, along with their creation methods and main methods. Additionally, it explains how to iterate over these object types using various techniques.

Uploaded by

ta89725
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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.

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.

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 Data Types in JavaScript: Creating and Main Methods

Type Description Creating Main Methods Code Snippet Code Output

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;
}

let arr = [45, 23, -80, 12];


console.log(applyExpArray(
arr, 2));

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() );

- Get the number of the


key-value pairs: size

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

Type Iterating Over Code Snippet Code Output

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]); '$';
}); }

- Iterate over Object.entries() using forEach:


let entries = Object.entries(myObj);
entries.forEach(([key, value]) => {
console.log(key + ': ' + value);
});

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);
});

- Using map method:


myArray.map(value => { console.log(value); });

- Using for...in Loop:


for (let index in myArray) {
console.log(myArray[index]);
}

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);
} });

- 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);
});

Set - Using for..of loop: let citySet = new Set(['Vienna', Vienna


for (let item of setName) { 'Salzburg', 'Graz', 'Klagenfurt', Salzburg
console.log(item); 'Innsbruck']); Graz
} Klagenfurt
citySet.forEach((city) => { Innsbruck
- Using forEach: console.log(city);
setName.forEach((value) => { });
console.log(value);
});

10
Found it useful?

Follow for more:


linkedin.com/in/noura-boudiaf-115aa845

11

You might also like