12 JavaScript Code Snippets That Every Developer Must Know
Last Updated :
10 Dec, 2024
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);
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);
- 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);
- 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);
- 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);
- 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);
- 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);
- 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);
- 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);
- The spread operator ... copies all elements into a new array.
- Modifying the clone does not affect the original array.
Similar Reads
7 JavaScript Concepts That Every Web Developer Should Know JavaScript is Everywhere. Millions of web pages are built on JavaScript and itâs not going anywhere at least for now. On one side HTML and CSS give styling to the web pages but on the other side, it's the magic of JavaScript that makes your web page alive. Today this language is not just limited to
10 min read
10 JavaScript DOM Tips and Tricks That Every Developer Should Know The DOM stands for âDocument Object Modelâ, itâs a programming interface for HTML (Hypertext Markup Language) and XML (Extensible Markup Language) documents. DOM represents the structure of a document which means a hierarchical tree-like structure, where each existing element in the document are rep
12 min read
Top 10 JavaScript Fundamentals That Every Developer Should Know Javascript is an object-oriented language that is lightweight and used for web development, web applications, game development, etc. It enables dynamic interactivity on static web pages, which cannot be done with HTML, and CSS only. Javascript is so vast that even mid-level professionals find it dif
8 min read
15 Must Have JavaScript Tools For Developers It's true to say that JavaScript rules the world in the field of web development. According to GitHub, it is the most popular programming language in the world. As per the latest reports, more than 97% of the websites use JavaScript on the client side. There are more than 15 million software develop
9 min read
8 Tips and Tricks For JavaScript Developers It is statistically proven JavaScript is the most widely used language by programmers globally. One of the most important reasons for this is that it is developer friendly. A recent study suggested that the number of JavaScript developers has surged in the past 4 years and currently out of 1.8 Billi
9 min read