Zhihu Q&A
[Answer] What Are Some Short but Amazing JavaScript Snippets?
March 22, 20264 min read
![[Answer] What Are Some Short but Amazing JavaScript Snippets?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2Fjavascr-74707ad4.png&w=3840&q=75)
[Answer] What Are Some Short but Amazing JavaScript Snippets?
[Answer] What Are Some Short but Amazing JavaScript Snippets?
Some short but amazing JavaScript snippets:
- Reverse a string:
const reverseString = str => str.split("").reverse().join("");
- Check whether a string is a palindrome:
const isPalindrome = str => str === str.split("").reverse().join("");
- Find the maximum value in an array:
const arr = [1, 2, 3, 4, 5];
const maxNum = Math.max(...arr);
- Remove duplicates from an array:
const arr = [1, 1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
- Calculate the sum of an array:
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, num) => total + num);
- Swap the values of two variables:
let a = 1, b = 2;
[b, a] = [a, b];
- Filter array elements that match a condition:
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.filter(num => num % 2 === 0);
- Flatten an array:
const arr = [1, [2, [3, [4]]]];
const flattenedArr = arr.flat(Infinity);
- Shuffle an array:
const arr = [1, 2, 3, 4, 5];
const shuffledArr = arr.sort(() => Math.random() - 0.5);
- Debounce:
const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
};
- Throttle:
const throttle = (func, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
inThrottle = true;
func(...args);
setTimeout(() => inThrottle = false, limit);
}
};
};
- Check whether a variable is an array:
const arr = [1, 2, 3];
const isArray = Array.isArray(arr);
- Destructure object properties:
const obj = { x: 1, y: 2 };
const { x, y } = obj;
- Deep copy an object:
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
- Calculate the average of an array:
const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((total, num) => total + num) / arr.length;
- Check whether a string starts with a specific substring:
const str = "Hello, world!";
const startsWithHello = str.startsWith("Hello");
- Check whether a string ends with a specific substring:
const str = "Hello, world!";
const endsWithWorld = str.endsWith("world!");
- Quickly check whether a number is even:
const isEven = num => (num & 1) === 0;
- Format a number as currency:
const amount = 12345.67;
const formattedAmount = amount.toLocaleString("en-US", { style: "currency", currency: "USD" });
- Create an array with a specified length and default value:
const length = 5;
const defaultValue = 0;
const arr = Array.from({ length }, () => defaultValue);
- Use
Promise.allto handle multiple async operations in parallel:
const urls = ["https://example.com/api/1", "https://example.com/api/2", "https://example.com/api/3"];
const requests = urls.map(url => fetch(url));
const responses = await Promise.all(requests);
const data = await Promise.all(responses.map(response => response.json()));
These snippets are also efficient and easy to use, but in real projects you should still pay attention to context and usage scenarios to ensure correctness and effectiveness.
![[Thought] Many viruses you’ve probably never heard of also contain DNA, such as iridoviruses](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2Fdna-39161584.png&w=3840&q=75)
![[Answer] What did you do on the night you checked your Gaokao score?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2F-e4a8ec38.png&w=3840&q=75)
![[Answer] How Can You Score 130+ on the Gaokao Math Exam?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2F130-157dba52.png&w=3840&q=75)