JS Intermediate – How Javascript Methods Works

Home /

Table of Contents

Javascript Methods

In JavaScript, methods are functions that are associated with objects. They can be used to perform a variety of operations on the object or to retrieve information about the object’s properties and values.

JavaScript includes many built-in methods that can be used to manipulate strings, arrays, numbers, and other data types. Methods are a powerful tool for working with objects in JavaScript. By understanding how to use and create methods, you can perform complex operations on objects and create more modular and reusable code.

For Each

For-Each is a functional method for traversing an array in Javascript. forEach is a method of callback function with parameters such as value, index, and the array itself in order. The method doesn’t execute for empty elements. For-Each is used to call a function for each element of an array. The function is also given the element, the index of the element, and the array itself.

Example:

var arr = [11,22,33]
 
arr.forEach(function (value, index, array) {
   console.log(value, index, array);
})

Output:

11 0 [ 11, 22, 33 ]
22 1 [ 11, 22, 33 ]
33 2 [ 11, 22, 33 ]

Note: Any kind of programming operation can be done by this method one by one element in this array.

Example:

var arr = [11,22,33]
 
arr.forEach(function (value, index, array) {
   array[index] = value + 5
   console.log(value, index, array);

Output:

11 0 [ 16, 22, 33 ]
22 1 [ 16, 27, 33 ]
33 2 [ 16, 27, 38 ]

Map

The map() is a method of creating a new array associated with the results of calling a given function on every element in the calling array. After implementation, the original array remains preserved. When working with them, we frequently convert maps into and out of arrays since arrays have more integrated ways to transform the contents.

Example:

var arr_1 = [1, 2, 3]
 
var arr_2 = arr.map(function (value) {
   return Math.random() * 100
})
 
console.log(arr_1);
console.log(arr_2);

Output:

[ 1, 2, 3 ]
[ 86.84531048845763, 47.47820124702977, 95.77057747915659 ]

Note: Here map() method is implemented on the arr_1 array. The arr_1 has 3 elements in the array. After implementation arr_1 still has the same elements and values but here creates a new array stored on the arr_2 variable with the result of the function completed.

Example:

var arr = [1, 2, 3]
 
var sqrArr = arr.map(x => x*x)  //passing a arrow function to map
 
console.log(arr);
console.log(sqrArr);

Output:

[ 1, 2, 3 ]
[ 1, 4, 9 ]

Filter

The filter() method creates a copy of a portion of a given array filled with elements that pass a test provided by a function without changing in the new array. The filter() method returns a shallow copy of a portion of a given array that has been filtered down to only the elements of the given array that pass the test implemented by the provided function. filter() calls a provided callbackFn function once for each element in an array and creates a new array of all the values for which callbackFn returns a true value. callbackFn is only called for array indexes that have values assigned to them; it is not called for indexes that have been deleted or have never had values assigned to them. Array elements that fail the callbackFn test are skipped and do not appear in the new array.

Example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
 
var evenNum = arr.filter((x) => x % 2 == 0);
 
console.log(arr);
console.log(evenNum);

Output:

[ 1, 2, 3, 4, 5, 6, 7, 8 ]
[ 2, 4, 6, 8 ]

Reduce

The reduce() method calls a user-supplied “reducer” callback function on each element of the array in turn, passing in the result of the previous element’s calculation. The result of running the reducer across all array elements is a single value. There is no “return value of the previous calculation” the first time the callback is executed. In its absence, an initial value may be used. Otherwise, the array element at index 0 is used as the starting point, and iteration begins with the next element (index 1 instead of index 0).

Example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function myReduce(arr, cb, acc){
   for (var i=0; i<arr.length; i++){
       acc = cb(acc, arr[i])
   }
   return acc
 }
var sum =myReduce(arr, function(prev, curr){
   return prev + curr
}, 0)
var max = myReduce(arr, function (prev, curr) {
   return Math.max(prev, curr)
}, 0)
var min = myReduce(arr, function (prev, curr) {
   return Math.min(prev, curr)
}, 0)
console.log(sum, max, min);

Output:

36 8 0

Note: Until there are no more elements to add, the reducer goes through the array element by element, adding the value of the current array element to the result from the previous step (this result is the running sum of all previous steps). The reduce() method does not alter the array it is applied to. The array can, however, be mutated by code inside the callback function. These are the various array mutation scenarios and how to reduce() behaves in them.

Example:

var arr = [11, 22, 33, 44, 55, 66, 77, 88];
 
var intValue = 0;
var sumOfValue = arr.reduce((prev, curr) => prev + curr, intValue);
 
console.log(sumOfValue);

Output:

396

Find

The find() method is used for finding any elements in a given array by a callback function. The find() method always returns a Boolean value. The first element in the given array that satisfies the testing function is returned by the find() method. Undefined is returned if no values satisfy the testing function. The find method calls the callbackFn function once for each index of the array until it returns a true value. If this is the case, find returns the value of that element right away. Otherwise, find returns an undefined value.

callbackFn is called for every index in the array, not just those with values assigned to them. This suggests that it may be less efficient for sparse arrays than methods that only visit assigned values.

If a thisArg parameter is passed to find, it will be used as this value inside each callbackFn invocation. If it is not provided, the default value is undefined.

Example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
 
var result_1 = arr.find(x => x==5)
var result_2 = arr.find(x => x==11)
 
console.log(result_1);
console.log(result_2);

Output:

5
undefined

Find Index

The findIndex() method is used for finding the index of any elements in a given array by a callback function if the elements exist in the array. The findIndex() method always returns a number value. The findIndex() method calls the callbackFn function once for each index in the array, in ascending order, until it finds one that returns a true value.

If such an element is found, findIndex() returns the element’s index immediately. FindIndex() returns -1 if callbackFn never returns a true value (or the array’s length is 0).

Example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
 
var result_1 = arr.findIndex(x => x==5)
var result_2 = arr.findIndex(x => x==11)
 
console.log(result_1);
console.log(result_2);

Output:

4
-1 

Here, In the output -1 means false, the value didn’t found

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article