DEV Community

Cover image for Top 5 most used javascript functions with examples that you must try.
Akash Chauhan
Akash Chauhan

Posted on

Top 5 most used javascript functions with examples that you must try.

Javascript functions are very useful because they allow us to reuse code. We can write a function once and then call it whenever we need it. This saves us a lot of time and makes our code more organized.

Javascript functions are also great for making our code more modular. By breaking our code up into smaller pieces, we can make changes to one part without affecting the rest of the code. This makes debugging and maintenance much easier.

Javascript functions are a great tool that we should take advantage of. They can save us a lot of time and help us keep our code more organized and manageable.

When it comes to programming, there is a wide range of functions that can be used in order to make code more efficient.

However, with JavaScript specifically, there are a few functions that tend to be more useful than others. This article will highlight the five most useful javascript built-in functions with source code.

In this article , Today we are going to be discussing about top 10 most useful javascript functions with example that you must try.

1. JavaScript foreach

JavaScript foreach function in javascript is a powerful tool that allows you to iterate through arrays or objects. This article will show you how to use the foreach function and how it can be used to simplify your code.

The foreach function takes two arguments, the first is the array or object to iterate through and the second is a callback function. The callback function takes three arguments, the first is the value of the current element, the second is the index of the current element and the third is the array or object being iterated over.

JavaScript foreach function executes the callback function once for each element in the array or object. The value of this within the callback function is set to the array or object being iterated over.

Javascript foreach functions have key, value that works as back bone for javascript foreach so,

You can exit early from a foreach loop by returning false from within your callback function.

JavaScript foreach function example:

let students = ['Yogesh', 'Avinash', 'Kamal'];

// using forEach
students.forEach(myFunction);

function myFunction(item, index, arr) {

    // adding strings to the array elements
    arr[index] = 'Hello ' + item;
}

console.log(students);
// ['Hello Yogesh', 'Hello Avinash', 'Hello Kamal'];
Enter fullscreen mode Exit fullscreen mode

2. JavaScript filter

When working with arrays, it is often necessary to only select certain elements that meet certain criteria. For example, you may want to find all of the users in a database who are over the age of 21. The JavaScript filter function makes this task easy.

To use the javaScript filter function, you first need to create a callback function that defines the criteria for inclusion in the new array. This callback function should take in one argument (the element being evaluated) and return a Boolean value indicating whether or not the element should be included in the new array.

Once you have defined your callback function, you can pass it into the filter function along with the original array. The filter function will then return a new array containing only those elements from the original array that met the criteria specified by your callback function.

JavaScript filter function example:

const colors = [
  { name: "red", quantity: 2 },
  { name: "black", quantity: 0 },
  { name: "blue", quantity: 5 },
];

function isBlack(color) {
  return color.name === "black";
}

console.log(colors.find(isBlack));
// { name: 'black', quantity: 0 }
Enter fullscreen mode Exit fullscreen mode

3. JavaScript map

JavaScript map function is a built-in method in JavaScript that allows you to transform one array into another.

The map function calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The map function is often used to transform an array of data into a new array of data. For example, you could use the map function to convert an array of strings into an array of numbers.

If you have an array of data that you need to transform, the map function is a great tool to use.

//create an array of total no
var totalNo = [10, 30, 10, 22, 14];

//javascript map calls a function where "element" passed as parameter
//this map will pass each element of totalNo as "item" in this 
 result = totalNo.map(function(element) {
  return element*2;
});

console.log(result); 
// [20, 60, 20, 44, 28]
Enter fullscreen mode Exit fullscreen mode

4. JavaScript find and findIndex

JavaScript find() method returns the value of the first element in an array that passes a test implemented by a callback function. It executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, it returns undefined.

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

JavaScript find example:

function searchItem(itemKey, myArray){
    for (var i=0; i < itemArray.length; i++) {
        if (itemArray[i].name === itemKey) {
            return itemArray[i];
        }
    }
}

var itemArray = [
    { name:"string1", value:"1" },
    { name:"string2", value:"2" }
];

var resultObject = searchItem("string1", itemArray);

console.log(resultObject);

// { name: "string 1" value: "this" }
Enter fullscreen mode Exit fullscreen mode

JavaScript findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.

JavaScript calls the findIndex() method on an array, passing in a callback function as an argument. The findIndex() method then calls that callback function once for each element in the array until it finds an element where callback returns a true value. If such an element is found, findIndex() returns the index of that element; otherwise, it returns -1.

For example, let's say you have an array of objects and you want to find the first object that has a particular property value. Now let's have a look at example for javascript find index of object in array by key value

JavaScript findIndex example:

var itemArray = [-10, -20, 30,10, 40, -9, -50];

var foundObj = itemArray.findIndex(function (element) {
     return element > == 10;
});

console.log(foundObj);

// 3
Enter fullscreen mode Exit fullscreen mode

5. JavaScript Object key

JavaScript object key() is a function that returns a list of all the keys in an object. The keys are returned in the order they were added to the object.

If you need to get the keys of an object in a specific order, you can use the key() function. By default, the key() function returns the keys in the order they were added to the object.

However, you can also specify a compare function to control how the keys are sorted before being returned.

The key() function is useful for looping through objects. For example, you could use it to get an array of all the usernames on a website.

JavaScript Object key example:

const location = {
  Street: 'Gouverneur Street',
  City: 'New York',
  Country: 'USA'
};

console.log(Object.keys(location));
Enter fullscreen mode Exit fullscreen mode

Summary

So , we discussed top 5 most used javascript functions including JavaScript filter, javascript map, javascript foreach, javascript find and findindex, javascript object key etc in this article.

Each of these functions has a different purpose and can be used in a variety of ways. Try using each of these functions in your own code to see how they work.

Original source at: akashminds.com

Related Articles:

Top 9 commonly used javascript functions with example | Akashminds

How Javascript games can improve your coding skills
The 10 essential frontend developer skills that you will need to know in 2023.
How much Javascript is required for Selenium Automation tester ?

Top comments (0)