About Lesson
In this JavaScript lesson we are going to learn about JavaScript Set & Map, before this in JavaScript we had just object and arrays collection, but now you can use set and map in JavaScript. Map holds key value pair.
Now let’s create an example of Map in JavaScript.
1 2 3 4 5 6 7 8 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); console.log(map.get('name')); console.log(map.get('lname')); |
You can check the existence of an item in a map by using has().
1 2 3 4 5 6 7 8 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); console.log(map.has('name')) |
Also you can check the size of the map.
1 2 3 4 5 6 7 8 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); console.log(map.size); |
Now let’s iterate over the map, for this we are using for of loop.
1 2 3 4 5 6 7 8 9 10 11 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); for(element of map) { console.log(`${element[0]} : ${element[1]}`); } |
Sets are like arrays, but it stores unique values, we can not add duplicate values in the set.
1 2 3 4 5 6 7 8 9 10 11 |
let set = new Set(); set.add(1); set.add(2); set.add(3); set.add(4); for(let element of set) { console.log(element); } |