- Published on
Data Types (Part II)
7 mins
- Authors
- Name
- Juleshwar Babu
 
 
Table Of Contents
Source Link: https://javascript.info/data-types
Array methods
- splicecan be used to add items at an index in an array (and optionally delete items). We can use negative indices as well to start from the end of the array- ["Mon", "Tue", "Wed", "Jan", "Sat"].splice(3, 1, "Thu", "Fri") // ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] ["Mon", "Tue", "Wed", "Jan", "Sat"].splice(-2, 1, "Thu", "Fri") // ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
- atcan be used to access items and it accepts negative indices as well- [1,2,3,4,5].at(-1) // 5
- We can use - concaton array-like elements,- [Symbol.isConcatSpreadable]needs to be set to- truefor it to work as expected- let moo = { 0:"a", 1:"b", length: 2 } console.log([].concat(moo)) // [{0: 'a', 1: 'b', length: 2}] ❌- let moo = { 0:"a", 1:"b", length: 2, [Symbol.isConcatSpreadable]: true } console.log([].concat(moo)) // ['a', 'b'] ✅
- indexOfdoesn’t handle- NaNcorrectly because the internal comparison algorithm has a bug.- includeswhich was added later to JS handles it correctly- [NaN].indexOf(NaN) // -1 ❌ [NaN].includes(NaN) // true ✅
- Array.sortcompares elements as strings by default 🤯 #til- let arr = [ 1, 2, 15 ]; arr.sort(); console.log( arr ); // [1, 15, 2] ❌- let arr = [ 1, 2, 15 ]; arr.sort((a,b) => +a - +b); // doing +"str" coerces str into a number console.log( arr ); // [1, 2, 15]
- reduceis a great way to reduce an array to a single value. It is a versatile method which can where you can customise the result. It can mimic- map,- filter,- forEach,- joinetc.- reduceRightreduces the array from the right
 - [1,2,3].join(';') // 1;2;3 [1,2,3].reduce((acc, curr) => `${acc};${curr}`) // 1;2;3 [1,2,3].reduceRight((acc, curr) => `${acc};${curr}`) // 3;2;1
Iterables
- https://javascript.info/iterable#symbol-iterator - [Symbol.iterator]()is the reason why- for…ofworks. When you call for…of on an object,- It calls [Symbol.iterator]method once (or errors if not found). The method must return an iterator – an object with the methodnext.
- Onward, for..ofworks only with that returned object.
- When for..ofwants the next value, it callsnext()on that object.
- The result of next()must have the form{done: Boolean, value: any}, wheredone=truemeans that the loop is finished, otherwisevalueis the next value.
 - // We will be making a object which when iterated over generates values from from to to let obj = { from: 3, to: 8, }; obj[Symbol.iterator] = function () { return { current: this.from, last: this.to, next() { if (this.current <= this.last) { return { value: this.current++, done: false, }; } else { return { done: true, }; } }, }; }; for (let x of obj) { console.log(x); // 3,4,5,6,7,8 }
- It calls 
- https://javascript.info/iterable#array-like - Iterables are objects that implement the Symbol.iteratormethod.
- Array-likes are objects that have indices and length, so they look like arrays.
 - These two feel like arrays but are not arrays! #psych 
- Iterables are objects that implement the 
Map and Set
- https://javascript.info/map-set#iteration-over-set #funny - For compatibility with a - Map’s forEach, when iterating over a- Set, you get value and then the same value again- set.forEach((value, valueAgain, set) => { alert(value); });
WeakMap and WeakSet
- https://javascript.info/weakmap-weakset#summary - [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)is- Map-like collection that allows only objects as keys and removes them together with associated value once they become inaccessible by other means. Although that comes at the cost of not having support for- clear,- size,- keys,- values…- WeakMapand- WeakSetare used as “secondary” data structures in addition to the “primary” object storage. Once the object is removed from the primary storage, if it is only found as the key of- WeakMapor in a- WeakSet, it will be cleaned up automatically. Usecases: Additional data, Caching
Object.keys, values, entries
- Explanation - Object.keys(obj) – returns an array of keys.
- Object.values(obj) – returns an array of values.
- Object.entries(obj) – returns an array of [key, value]pairs.
 
- Object.fromEntries(array)can be used to convert an array with key-value pairs into an object- let fruits = { banana: 20, apple: 5, watermelon: 100 } // Doubling the fruits into a new object const doubleFruitsObj = Object.fromEntries( Object.entries(fruits).map(fr => [fr[0], fr[1] * 2]) ) /** { banana: 40, apple: 10, watermelon: 200 } */
Content Updates
- 2023-07-29 - init