Showing posts with label syntax. Show all posts
Showing posts with label syntax. Show all posts

2020-08-15

Javascript ES6 Loops, Map, and Spread Operator

It's been a while (14 years) since I last learn about Javascript, I think at that time still ES5, but since ES6 (=ES2015, released June 2015) and newer ones already out (but most of the browsers already implemented most of ES6 features way before), I think it's time to review one of the features (I think the only features I learned was Promise and async-await few years ago). ES6 introduces new loop syntax for..of:

// old one
for(var k in arrOrObj) // iterate by key

// new one
for(const v of arrOrObj) // iterate by value
for(const v of Object.values(obj)) // iterate by value
for(const kv of Object.entries(obj)) // iterate by key-value pair
for(const [k,v] of Object.entries(obj)) // destructure

 

ES6 also introduces new data structure to store associative array, just like object, but difference:

  • unlike object, you don't have to worry that the key conflict with the object's property
  • iteration guaranteed by original insertion order, as far as I remember Object is random for Chrome and Sorted for Firefox
  • Has .size property, not Array .length
  • key not automatically converted as string, obj['1'] == obj[1]

let map = new Map(); // order by insert
map.set('a',1) // not equal to map['a']=1
map.get('a') // not equal to map['a']
map.has('a')
map.delete('a') // false if not exists

for(const [k,v] of map) // destructure
for(const k of map.keys()) // iterate by key
for(const v of map.values()) // iterate by value

ES6 spread operator also useful when dealing with Map, Object, or Array:

[...map] // get array of key-value pairs
Array.from(map) // get array of key-value pairs
[...map.keys()] // get array of keys
[...map.values()] // get array of values

map = new Map([...Object.entries(obj)].sort()) // order by key

new Map(map) // clone map
new Map([['a',1],['b',2],['c',3]]) // create from array of key-value
new Map([...map1, ...map2]) // merge map 

{...obj} // clone object
{...obj1,...obj2} // merge object

new Array(...arr) // clone array
[...arr] // clone array
[...arr1,...arr2] // concat array


Why not using .forEach method? Because you cannot break early. You can learn about new Javascript features (BigInt, Set, Promise, etc) from MDN.