The Wayback Machine - https://web.archive.org/web/20240623234742/https://www.geeksforgeeks.org/javascript-code-snippets-that-every-developer-must-know/
Open In App

12 JavaScript Code Snippets That Every Developer Must Know

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is by far of the most popular languages when it comes to web development, powering most websites and web applications. JavaScript is not only being used on the client side (with HTML and CSS) but it also supports the server side (built using Nodejs). Today, the majority of developers and business owners keep track of JavaScript trends to ensure they don’t miss any significant chances.

12 JavaScript Code Snippets That Every Developer Must Know

Thus, here are some of the most important JavaScript code snippets which you must know as a developer. Snippets are coding templates that are usually used to accomplish a single task and can also reduce redundant work to some great extent. Finding the snippet you require can save you a lot of time and trouble while programming JavaScript. With this being said, let’s continue with the article on the best JavaScript code snippets to assist you to have a much easier time learning & building with JavaScript.

12 JavaScript Code Snippets That Every Developer Must Know 

1. Sorting an Array

JavaScript provides an inbuilt sort() method that can be used to sort the elements inside an Array object. The code snippet below provided an example to sort numbers in ascending order.

Example:

Javascript




const numbers = [102, -1, 2];
 
numbers.sort((a, b) => a - b);
 
console.log(numbers);


Output

[ -1, 2, 102 ]

Here, the sort() method is called on the numbers array, which takes the comparator function as an argument. The comparator function takes 2 arguments ‘a’ and ‘b’, which are the elements being compared. The comparator function returns a positive value if ‘a’ must come before/equal to ‘b’ and a negative value if ‘a’ must come after ‘b’. 

2. Making API calls using the fetch() method

fetch() is a global function that is provided by Fetch API which offers an interface for interacting and accessing protocol elements like requests and responses. The code snippet below provided an example that makes an API request using fetch() and logs the responses into the console. Instead of logging the result, one can also set the data into a variable.

Example:

Javascript




const fetchAPI = async(URL) => {
      const response = await fetch(URL);
       
      const data = await response.json();
       
      console.log(data)
}


Here, the code defines an async function called fetchAPI() that makes a GET request to the API at the specified URL using the fetch function. The fetch function returns a promise that is resolved with await and the response object is stored in the ‘response’ variable. The json() method is called on the response to parse the data which again returns a promise that is resolved by await and the data is stored in the ‘data’ variable. The parsed data is then logged into the console. 

Must Read: JavaScript – fetch() Method

3. Find the Maximum using a Conditional (ternary) Operator

A conditional operator is a one-line replacement for the if .. else statement. Below is the snippet example that defines a ternary operator to get the maximum number.

Example:

Javascript




num1 = 10;
num2 = 20;
 
const maxi = (num1 > num2) ? num1 : num2;
 
console.log(maxi)


Output

20

Here, if the condition i.e. `num1 > num2` is true, it returns `num1`, else it returns `num2` which is stored in the maxi variable.

Must Read: Program to Find the Largest Number using Ternary Operator

4. Creating a New Array using the Existing Array/List

JavaScript Array provides a map() method that creates a new array after applying some transformation to the existing array. The method takes a callback function as an argument which is applied to each element of the array.  The below code snippet uses the map method to find the length of all the fruits present in the fruit array.

Example:

Javascript




var fruits = ["apple", "mango", "watermelon", "orange"];
 
var fruits_len = fruits.map((ele) => ele.length);
 
console.log(fruits_len)


Output

[ 5, 5, 11, 6 ]

Here, the map() method is called on the fruits array,  which takes the callback function as an argument.  The callback function takes an element ‘ele’ as an argument and returns the length of the element i.e. ‘ele.length. The callback function is applied to all the elements of the array through the map method. The map method returns a new array made up of elements, returned by the callback function, that is stored in ‘fruits_len‘.

Must Read: JavaScript Array map() Method

5. Creating a New Array after Filtering the Existing Array

JavaScript Array provides a filter() method that creates a shallow copy of a portion of elements that are selected according to some specific criteria. The method takes a callback function as an argument which is applied to each element of the array. The below code snippet returns the list of fruits with even length.

Example: 

Javascript




var fruits = ["apple", "mango", "watermelon", "orange"];
 
var even_fruits = fruits.filter(ele => ele.length % 2 !== 0);
 
console.log(even_fruits)


Output

[ 'apple', 'mango', 'watermelon' ]

Here, the filter() method is called on the fruits array,  which takes the callback function as an argument.  The callback function takes an element ‘ele’ as an argument and returns ‘true’ if the element is of even length and ‘false’ otherwise. The callback function is applied to all the elements of the array through the filter method. The filter method returns a new array made up of elements that pass the condition from the callback function, which is stored in ‘even_fruits’.

Must Read: JavaScript Array filter() Method

6. Find an Element based on Specific Conditions

JavaScript Array provides a find() method that returns the first element from the array based on some condition[s]. The below code snippet is used to search for an element from the fruits array that satisfies the given criteria.

Example:

Javascript




var fruits = ["apple", "mango", "watermelon", "orange"];
 
var data = fruits.find(element => element.length > 6 && element.length % 2 !== 0);
 
console.log(data)


Output

watermelon

Here, the find() method is called on the fruits array,  which takes the callback function as an argument.  The callback function takes an element ‘element‘ as an argument and returns ‘true‘ if the element is of even length with a length greater than 6 and ‘false‘ otherwise. The callback function is applied to all the elements of the array till it finds the first element that passes the condition. The find() method returns the first element that passes the condition and ‘undefined’ if no such element is found inside the array.

Must Read: JavaScript Array find() Method

7. Find the Index of an Element based on Specific Conditions

JavaScript Array provides a findIndex() method that returns the index of the first element from the array based on some condition[s]. The below code snippet is used to search for the index of an element from the fruits array that satisfies the given criteria.

Example:

Javascript




var fruits = ["apple", "mango", "watermelon", "orange"];
 
var data = fruits.findIndex(element => element.length > 6 && element.length % 2!== 0);
 
console.log(data)


Output

2

Here, the findIndex() method is called on the fruits array,  which takes the callback function as an argument.  The callback function takes an element ‘element‘ as an argument and returns ‘true’ if the element is of even length with a length greater than 6 and ‘false’ otherwise. The callback function is applied to all the elements of the array till it finds the first element that passes the condition. The findIndex() method returns the ‘index‘ of the first element that passes the condition and ‘-1’ if no such element is found inside the array.

Must Read: JavaScript Array findIndex() Method

8. Sum of All Elements in an Array

JavaScript Array provides a reduce() method that runs a user-defined reducer function on each element of the array to return a single value. The below code snippet returns the sum of all elements in an array.

Example:

Javascript




var numbers = [1,2,3,4,5];
 
var initial_value = 0;
 
var total = numbers.reduce((accumulator, current_value) => accumulator + current_value, initial_value);
 
console.log(total);


Output

15

Here, the reduce() method is called on the numbers array,  which takes the callback function as an argument. The callback function is taken in 2 arguments, ‘accumulator’ which is the value resulting from the previous callback function, and the ‘current_value’ which is the value of the current element. The reducer function starts with the initial value i.e. ‘initial _value’ of ‘0’, and is applied to all the elements in the array starting from the first element. The method finally returns the sum of all the elements that are stored inside the total variable.

Must Read: JavaScript Array reduce() Method

9. Remove the First Element from the Array

JavaScript array provides a shift() method that removes the first element from the array. The below code snippet removes the first element from the array and prints the updated array.

Example:

Javascript




var numbers = [1,2,3,4,5];
 
var delete_value = numbers.shift();
 
console.log(`${delete_value} is deleted from the array`);
 
console.log("updated array: ", numbers);


Output

1 is deleted from the array
updated array:  [ 2, 3, 4, 5 ]

Here, the shift() method is called on the numbers array,  which removes and returns the first element from the array.  The returned value is stored in the ‘delete_value’ variable. The function reduces the array size by 1.

10. Insert Elements to the Start of the Array

JavaScript array provides a unshift() method that adds one or more elements to the start of the array. The below code snippet adds 2 elements to the start of the array and prints the updated array.

Example:

Javascript




var numbers = [1,2,3,4,5];
 
numbers.unshift(-1,0);
 
console.log("updated array: ", numbers);


Output

updated array:  [
  -1, 0, 1, 2,
   3, 4, 5
]

Here, the unshift() method is called on the numbers array,  which inserts 2 elements to the start of the array. The unshift method takes in 1 or more parameters that are to be added to the start of the array. The above program increases the array size by 2.

Must Read: JavaScript Array unshift() Method

11. Remove the Last Element from the Array

JavaScript array provides a pop() method that removes the last element from the array. The below code snippet removes the last element from the array and prints the updated array.

Example:

Javascript




var numbers = [1,2,3,4,5];
 
var delete_value = numbers.pop();
 
console.log(`${delete_value} is deleted from the array`);
 
console.log("updated array: ", numbers);


Output

5 is deleted from the array
updated array:  [ 1, 2, 3, 4 ]

Here, the pop() method is called on the numbers array,  which removes and returns the last element from the array.  The returned value is stored in the ‘delete_value‘ variable. Similar to the shift() method, the above snippet reduces the array size by 1.

Must Read: JavaScript Array pop() Method

12. Insert Elements to the End of the Array

JavaScript array provides a push() method that adds one or more elements to the end of the array. The below code snippet adds 2 elements to the end of the array and prints the updated array.

Example:

Javascript




var numbers = [1,2,3,4,5];
 
numbers.push(6,7);
 
console.log("updated array: ", numbers);


Output

updated array:  [
  1, 2, 3, 4,
  5, 6, 7
]

Here, the push() method is called on the numbers array,  which inserts 2 elements to the end of the array. The push method takes in 1 or more parameters that are to be added to the end of the array. Similar to unshift() method, the above program increases the array size by 2.

Must Read: JavaScript Array push() Method

Related Resources:

Conclusion

Now that you are aware of JavaScript code snippets, start implementing them now! These best JavaScript code Snippets enable you to reuse previously developed and tested code, which can help you save time and effort. By dividing your code into smaller, more manageable chunks, snippets can also assist make it easier for you or other developers to comprehend and maintain your code. Overall using snippets can help increase the effectiveness and readability of code. Start using them now to build an interesting project with less code and complexity.



Similar Reads

5 Vue.Js Advantages That Every Developer Must Know
Being called one of the most flexible, Vue has always been known to carry huge thresholds and maybe that’s why today top giants like Netflix, Nintendo, etc. are using this framework. Vue was introduced first by Evan You in 2014 who himself was a big techie and wanted to build something more stable and powerful. However, Vue.js (commonly referred to
5 min read
Top 7 Payment Gateway APIs That Every Developer Must Know in 2024
Developers can easily build a website for someone else and for their purpose of starting a business. Well, running a startup successfully can be difficult if you haven't chosen the right payment gateway service. The right payment gateway service allows customers easy transactions on your website. If you ignore the most important part of your websit
10 min read
How to Increase the Development Speed With Snippets in Visual Studio Code?
When it comes to delivering a project every company and developer wants to finish it as soon as possible. Working as a developer we always look for some tools or tricks to increase the development speed and boost productivity. Nobody loves to spend hours on writing every single line for a program or writing the same line of code at multiple places.
5 min read
How to include HTML code snippets in HTML ?
In this article, we will learn how to include HTML snippets in HTML code. We will include the HTML code snippet of "gfg.html" into "index.html". To achieve this task, we are going to write a JavaScript function in "index.html" which traverses the collection of all HTML elements in "gfg.html" and searches for elements with specific attributes. It cr
3 min read
10 Python Code Snippets For Everyday Programming Problems
In recent years, the Python programming language has seen a huge user base. One of the reasons could be that it is easier to learn as compared to other object-oriented programming languages like Java, C++, C#, JavaScript, and therefore more and more beginners who are entering the field of computer science are opting for Python. Another reason why t
8 min read
Top Online Communities Every Data Scientist Must Know
So you have decided to become a Data Scientist! But what's next? It's very easy to obtain lots of information online about how to become a Data Scientist, and there are many courses also that teach you the fundamentals of Data Science but not enough resources for how to engage with the Data Science community. It's equally important to meet like-min
5 min read
Top 7 UI/UX Trends That Every Designer Must Know
There are more than 1.93 billion websites in the world and all those successful websites exist due to beautiful UIs. Those UIs are created by none other than UI/UX designers. The more attractive UI looks, the more users get engaged with it. Are you also the one who enjoys playing with UIs? Moving forward with the technological trends, UI/UX is also
5 min read
Top Data Structures That Every Programmer Must Know
A Data Structure organizes and stores data in a computer so that we can perform operations on the data more efficiently. There are many diverse applications of data structures in Computer Science and Software Engineering. The use of data structures is most common in all computer programs and software systems. As well, data structures are an importa
15+ min read
Top UI/UX Design Terminologies That Every Designer Must Know in 2024
UI/UX is a trending domain nowadays, many people want to be UI or UX, or Product Designers. However, most people are not aware of some very important terminologies that are often used in the field or by the designers themselves. Also, in the last 5 years, the demand for UI/UX designers has increased thus creating an increase in job openings. Every
14 min read
7 VS Code Tricks That You Must Know
VS Code Tricks are in reality those powerful tools or you may also say the features which the developers may confidently load in their pockets. From constructing the VS Snippets individually to helping you while speedily navigating the multiple VB files, it is possible to do such things via these dynamic VS Code Tricks. However, it isn’t vital to r
7 min read
three90RightbarBannerImg