Monday, November 18, 2024
Google search engine
HomeLanguagesJavascript12 JavaScript Code Snippets That Every Developer Must Know

12 JavaScript Code Snippets That Every Developer Must Know

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments