Top Commonly Used JavaScript Functions
Functions are one of the most important aspects of JavaScript. This article will explore the top nine commonly used JavaScript functions with examples.
Join the DZone community and get the full member experience.
Join For FreeFunctions are one of the most important aspects of JavaScript. Without JavaScript functions, it would be very limited. Functions in JavaScript are used to perform a certain action or task.
They can be written into the code, or they can be created using the Function constructor.
JavaScript functions or methods in Java can take arguments and return values. Arguments are values that are passed into the function when it is called. The return value is the value that is returned by the function after it has been executed.
Functions can be defined inside of other functions, which are called nested functions. Nested functions have access to the variables and arguments of the outer function.
This allows for some interesting and powerful programming techniques.
As a programming language, JavaScript has many features that make it unique and important. One of these features is the function.
JavaScript functions are also important for other frameworks like angular. Angular is a JavaScript framework for building web applications and apps in JavaScript, HTML, and TypeScript.
Angular is used by millions of developers all over the world. It is one of the most popular frameworks for building single-page applications.
This article will explore the top nine commonly used JavaScript functions with examples.
1. JavaScript Filter
The filter function in JavaScript is used to filter out elements from an array based on a certain condition. In other words, the filter function will return a new array with only those elements that satisfy the condition.
For example, if we have an array of numbers and we want to only get the even numbers, we can use the filter function with a condition that checks for even numbers.
Similarly, if we have an array of objects and want only to get the objects with a certain property value, we can use the filter function with the condition that checks for that property value. There are many other uses for the filter function as well.
JavaScript Filter Example:
// Array Filter function let numbers = [15, 2, 50, 55, 90, 5, 4, 9, 10];
console.log(numbers.filter(number => number % 2 == 1));
// Filtering odd numbers => result is [15, 55, 5, 9]
2. JavaScript Foreach
JavaScript foreach loop is a handy tool for iterating over arrays in JavaScript. It allows you to execute a certain set of code for each element in an array without having to write a for a loop. We’ll look at how the foreach loop works and how you can use it in your code.
We will discuss what kind of operations we can perform with foreach in JavaScript. JavaScript Foreach is a looping construct available in several programming languages, including JavaScript.
The main purpose of foreach is to allow the programmer to iterate over a collection of data, such as an array or list.
To use the JavaScript foreach, you first need an array. This can be created using the Array() constructor or by simply assigning a comma-separated list of values to a variable:
Once you have your array, you can start iterating over it using the JavaScript foreach loop. The syntax for the foreach loop is as follows:
JavaScript Foreach Example:
<p id="items"></p>
<script> let text = "";
const fruits = ["Apple", "Orange", "Cherry", "Banana"];
fruits.forEach(myFunction); document.getElementById("items").innerHTML = text;
function myFunction(item, index) {
index =index + 1 text += index + ": " + item + "";
}
</script>
3. JavaScript Map
JavaScript map function is a built-in method in JavaScript that allows you to process each element in an array.
The map() method in JavaScript transforms elements in an array according to a function. The function is executed on each element of the array, with the element being passed as an argument.
JavaScript map() method returns a new array containing the transformed elements.
If you have an array of numbers and you want to double them, you can use the map() method with a function that multiplies each number by two.
In this case, the original array is not modified. Instead, a new array is created with the doubled values:
var newArr = arr.map(num => num * 2);
Let’s Take a Look at Another Example of a JavaScript Map Function.
const users = [ {firstname : "Abhishek", lastname: "Kumar"}, {firstname : "Jay", lastname: "Sharma"},
{firstname : "Rupal", lastname: "Sharma"} ];
users.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(", ");
}
// Output: Abhishek Kumar, Jay Sharma, Rupal Sharma,
4. JavaScript Conacat
JavaScript string concatenation is the process of joining two or more strings together. The most common way to concatenate strings in JavaScript is to use the + operator. However, there are other ways to do it as well.
One way to concatenate strings in JavaScript is by using the += operator. This operator adds the string on the right side of the operator to the string on the left side of the operator. For example:
str1 += str2; // now str1 equals “Hello World”
Another way to concatenate strings in JavaScript is using the .concat() method.
Js concat method is used to merge two or more strings together. This is useful if you want to build a single string out of multiple smaller strings.
JavaScript Concat() method does not change the existing strings but returns a new string containing the merged strings' text.
JavaScript Concat Example:
const arr1 = ["Abhishek", "Rupal"];
const arr2 = ["Divya", "Rahul", "Harsh"];
const allUsers = arr1.concat(arr2);
// Output: Abhishek, Rupal, Divya, Rahul, Harsh
const arr1 = ["Abhishek", "Rupal"];
const arr2 = ["divya", "Rahul", "Harsh"];
const arr3 = ["kamal", "Rohit"];
const allUsers = arr1.concat(arr2, arr3);
// Output: Abhishek, Rupal, Divya, Rahul, Harsh, Kamal, Rohit
5. JavaScript Find
When working with arrays, the find function can be a helpful tool. This function will return the first element in an array that meets the given condition.
If we have an array of numbers and we want to find the first number that is greater than five, we can use the find function. The JavaScript find function takes a callback as its first argument.
This callback is passed through three arguments: the current element being processed, the index of that element, and the array itself.
The callback should return true if the element meets the condition and false otherwise. In our example, we would return true if the current element is greater than five.
JavaScript find function is not just limited to numbers. It can be used on strings as well.
JavaScript Find Function Example:
const marks = [30, 70, 98, 77];
console.log(marks.find(checkMarks));
function checkMarks(mark) {
return mark > 90;
}
// 98
Another Example of the JavaScript Find Function:
const fruits = [ { name: "apple", count: 10 }, { name: "banana", count: 18 }, { name: "mango", count: 3 } ]; const findMango = fruits.find(fruit =>fruit.name === "mango"); // { name: "mango", count: 3}
6. JavaScript Findindex
When working with arrays, there may be times when you need to find the index of a particular element. This can be done using the JavaScript findIndex() method.
JavaScript findIndex method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
The findIndex JavaScript method is similar to the JavaScript find function, but it returns the index instead of the value.
The findIndex() function takes two arguments a callback function and an optional object that can be used as this keyword inside the callback function.
JavaScript FindIndex Function Example:
const marks = [30, 70, 98, 77];
console.log(marks.findIndex(checkMarks));
function checkMarks(mark) {
return mark > 90;
}
// 2
Another Example of JavaScript FindIndex Function:
const fruits = [ { name: "apple", count: 10 }, { name: "banana", count: 18 }, { name: "mango", count: 3 } ]; const findMango = fruits.findIndex(fruit =>fruit.name === "mango");
// 2
7. JavaScript Includes
JavaScript includes() an inbuilt function that checks whether a string contains another string. If the specified string is found, it returns true. Otherwise, it returns false.
JavaScript includes function is case-sensitive, meaning it will differentiate between uppercase and lowercase letters, meaning it will treat “Java” and “java” as two different strings.
To check if a JS string contains another string, simply pass in the string you want to check as the first argument and the string you’re checking for as the second argument.
For example, check if the string “Hello World” contains the word “world.” Since the search is case-sensitive, it will return false.
const birds = ["Birds", "peacock", "Dove", "Sparrow"];
console.log(birds.includes("Dove"));
// true
8. JavaScript Split
JavaScript split function JavaScript is a String function used to split a string into an array of substrings and return the new array.
Split(str, separator, limit)
The original string is not modified. The syntax for the split function is:
Str — The string to be split.
Separator — The character to use as a separator. If omitted, a single space (‘ ‘) is used as the separator.
Limit — An integer that specifies the number of splits to be made. If omitted, the string will be split into an array of substrings with no limit.
The separator is a string that defines where the string should be split. The limit is an integer that specifies the maximum number of splits.
If the separator is not specified, the string will be split by whitespace characters. If the limit is not specified, it will default to 0, which means there is no limit.
JavaScript split function return value is an array of substrings. If the string cannot be split, it will return an empty array.
let text = "Hello this is Akashminds";
console.log(text.split(" "));
// ["Hello", "this", "is", "Akashminds"];
let text = "Hello this is Akashminds";
console.log(text.split(" ", 3));
// ["Akashminds"];
9. JavaScript Substr
JavaScript substr function is used to extract a part of the string. It has two parameters: the start position and the length of the substring. The function returns a new string containing the extracted part of the original string.
If the start position is negative, it is counted from the end of the string. If the length parameter is omitted, the JavaScript substr extracts all characters from the start position to the end of the string.
JavaScript substr function can be used to extract a part of a string or to create a new string by concatenating two substrings. It can also be used to find out whether a certain character or substring exists in a given string.
const test = "Hey!, this is Akashminds, have a nice day ahead.";
console.log(test.substring(0, 30));
// Hey!, this is Akashminds, have
As one of the most versatile and widely-used programming languages, JavaScript has a long history and a bright future. In this article, we have explored the top nine commonly used JavaScript functions with examples.
Using functions in JavaScript has several advantages.
First, if you have a lot of code you need to reuse, putting it in a function makes it easy to call again whenever you need it.
Second, using functions can help make your code more readable by breaking it up into smaller pieces.
These are the top nine commonly used JavaScript functions with examples. Mastering these functions will help you write better code and become a more proficient programmer.
Published at DZone with permission of Akash Chauhan. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments