Open In App

12 JavaScript Code Snippets That Every Developer Must Know

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is by far the most popular language when it comes to web development. It is being used on both the client side and the server side. To improve coding efficiency, every developer should know essential JavaScript code snippets to make their development fast and easy.

1. Sorting an Array

Sorting helps organize data for better usability.

JavaScript
let a = [9, 3, 5, 1];
a.sort((x, y) => x - y); // Ascending
console.log(a);

a.sort((x, y) => y - x); // Descending
console.log(a);

Output
[ 1, 3, 5, 9 ]
[ 9, 5, 3, 1 ]
  • x – y sorts in ascending order, while y – x sorts in descending order.
  • sort() compares elements and arranges them based on the provided function.

2. Making API Calls Using fetch()

Fetch retrieves data from a server using HTTP requests.

JavaScript
fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error('Error:', err));
  • fetch() makes an API call, res.json() parses the response, and catch handles errors.
  • This example fetches user data and logs it to the console.

3. Find the Maximum or Minimum in an Array

Easily determine the largest or smallest number in an array.

JavaScript
let a = [12, 45, 7, 32];
let max = Math.max(...a);
let min = Math.min(...a);
console.log(max);
console.log(min);

Output
45
7

4. Removing Duplicates from an Array

Simplify an array by keeping only unique values.

JavaScript
let a = [1, 2, 2, 3, 4, 4];
let unique = [...new Set(a)];
console.log(unique);

Output
[ 1, 2, 3, 4 ]
  • Set stores unique values, and … creates a new array.
  • Duplicates are automatically removed by the Set object.

5. Creating a New Array After Mapping

Transform elements of an array into a new one.

JavaScript
let a = [2, 4, 6];
let squared = a.map(x => x ** 2);
console.log(squared);

Output
[ 4, 16, 36 ]
  • map() applies a function (x ** 2) to each element.
  • The result is a new array without modifying the original.

6. Creating a New Array After Filtering

Filter elements based on a specific condition.

JavaScript
let a = [10, 15, 20, 25];
let filtered = a.filter(x => x > 15);
console.log(filtered);

Output
[ 20, 25 ]
  • filter() creates a new array with elements meeting the condition.
  • Here, elements greater than 15 are included.

7. Find an Element Matching a Condition

Retrieve the first element satisfying a given condition.

JavaScript
let a = [5, 10, 15, 20];
let found = a.find(x => x > 10);
console.log(found);

Output
15
  • find() stops and returns the first match it encounters.
  • This is ideal when only one element is needed.

8. Find the Index of an Element Matching a Condition

Locate the position of an element in an array.

JavaScript
let a = ['apple', 'banana', 'orange'];
let idx = a.findIndex(x => x === 'banana');
console.log(idx);
  • findIndex() returns the index of the first matching element.
  • If no match is found, it returns -1.

9. Sum of All Elements in an Array

Add all elements of an array together.

JavaScript
let a = [3, 6, 9];
let sum = a.reduce((total, x) => 
	total + x, 0);
console.log(sum);

Output
18
  • reduce() accumulates values (total) while iterating through the array.
  • 0 is the initial value of the accumulator.

10. Reverse a String

Reverse the characters in a string.

JavaScript
let s = "hello";
let rev = s.split('').reverse().join('');
console.log(rev);

Output
olleh
  • split(”) converts the string into an array, reverse() reverses it, and join(”) creates the reversed string.
  • Ideal for palindromes or reversing text.

11. Flatten a Nested Array

Transform a multi-dimensional array into a single-level array.

JavaScript
let a = [1, [2, [3, 4]], 5];
let flat = a.flat(Infinity);
console.log(flat); 

Output
[ 1, 2, 3, 4, 5 ]
  • flat(Infinity) flattens all nested levels into one.
  • Infinity ensures deeply nested arrays are fully flattened.

12. Clone an Array

Create a duplicate of an array.

JavaScript
let a = [1, 2, 3];
let clone = [...a];
console.log(clone);

Output
[ 1, 2, 3 ]
  • The spread operator … copies all elements into a new array.
  • Modifying the clone does not affect the original array.


Next Article

Similar Reads