Be the first user to complete this post
|
Add to List |
JavaScript Objects and Arrays Useful Methods
JavaScript Objects and Arrays have many useful methods that can help you write clean and maintainable code. In this post we will talk about following methods:
Object.keys()
Array.prototype.forEach()
Array.prototype.map()
&Array.prototype.reduce()
Array.prototype.push()
&Array.prototype.shift()
Object.keys()
It returns an array of enumerable properties of an object. The advantage of usingObject.keys()
over for ... in
is that, it does not look up in the prototypical inheritance chain of the given object.
Syntax : Object.keys(obj)
Input : valid JavaScript Object (either array or JSON)
Output : an array
[wpgist id="51a89cde8b6097bea242" file="keys.js"]Array.prototype.forEach()
This methods calls the callback for each valid element in the array. The callback has the access to the index variable which can be used to access the index of the element in the array.Syntax : arr.forEach(callback)
[wpgist id="51a89cde8b6097bea242" file="forEach.js"]Array.prototype.map()
It calls the callback on each valid element of an array and returns a new resulting array.Syntax : arr.map(callback)
Output : array
[wpgist id="51a89cde8b6097bea242" file="map.js"]Array.prototype.reduce()
It calls the callback on each valid element of an array and returns a single resulting value.Syntax : arr.reduce(callback)
Output : single value
[wpgist id="51a89cde8b6097bea242" file="reduce.js"]Array.prototype.push()
It returns the length of the new array and it adds the element at the end of the array.Syntax : arr.push(e1 ,..., eN)
Output : array
[wpgist id="51a89cde8b6097bea242" file="push.js"]Array.prototype.shift()
It returns the first removed element from an array and it removes the first element from the original array.Syntax : arr.shift()
Output : first removed element from an array
[wpgist id="51a89cde8b6097bea242" file="shift.js"]The example shown below uses all the methods we just talked about and solves a real world problem using these methods. [wpgist id="51a89cde8b6097bea242" file="transform.js"]
PS: I like visiting my old code and refactoring it with some of the new methods introduced in the language. And then including those language features in day to day programming. This example is one demonstration of it.
Also Read:
- How to get the data of a node in d3
- Getting the parameters and arguments of a javascript function
- Getting started with es6 generator functions