π 15 JavaScript Snippets to Supercharge Your Coding Skills! π
Sachin Gadekar
Posted on August 6, 2024
Hey #Developers! π Ready to elevate your JavaScript game? Dive into these essential snippets that simplify tasks and boost efficiency! π‘
i. Array Filtering: Easily filter elements based on conditions.
const filteredArray = array.filter(item => condition);
ii. Object Cloning: Quickly clone objects without deep copy issues.
const clone = { ...original };
iii. Array Flattening: Flatten nested arrays to a specified depth.
const flatArray = array.flat(depth);
iv. Debouncing Functions: Improve performance by limiting function calls.
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
v. Shuffling Arrays: Randomly shuffle array elements.
const shuffledArray = array.sort(() => Math.random() - 0.5);
vi. Removing Duplicates: Effortlessly remove duplicates from an array.
const uniqueArray = [...new Set(array)];
vii. Deep Merging Objects: Merge objects deeply for complex structures.
const mergedObject = Object.assign({}, obj1, obj2);
viii. Object Entries to Map: Convert an object to a Map for easier manipulation.
const map = new Map(Object.entries(obj));
ix. Query String Parameters: Easily access URL query parameters.
const params = new URLSearchParams(window.location.search);
x. UUID Generator: Generate unique identifiers.
```javascript
const uuid = crypto.randomUUID();
```
xi. Nullish Coalescing: Handle nullish values elegantly.
```javascript
const result = value ?? defaultValue;
```
xii. Optional Chaining: Safely access deeply nested properties.
```javascript
const nestedValue = obj?.property?.subProperty;
```
xiii. Fetching Data: Fetch API data with promise-based syntax.
```javascript
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
```
xiv. Async/Await Syntax: Simplify asynchronous code handling.
```javascript
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
return data;
}
```
xv. Local Storage: Store data in the browser for persistent access.
```javascript
localStorage.setItem('key', 'value');
```
Series Index
Posted on August 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.