JavaScript is a vast language with numerous built-in methods that developers use daily. While methods like map()
, filter()
, and reduce()
often steal the spotlight, there are lesser-known methods that can be equally powerful. These hidden gems can simplify your code, improve performance, and make your applications more efficient.
In this blog, we’ll dive into some of JavaScript's underrated built-in methods, explore how they work, and highlight practical use cases.
1. Object.fromEntries()
What It Does
Object.fromEntries()
transforms a list of key-value pairs (entries) into an object. It’s the reverse of Object.entries()
.
Example
const entries = [["name", "John"], ["age", 30], ["role", "developer"]];
const obj = Object.fromEntries(entries);
console.log(obj);
// Output: { name: "John", age: 30, role: "developer" }
Use Case
Convert query parameters from a URL into an object:
const queryString = "name=John&age=30";
const params = Object.fromEntries(new URLSearchParams(queryString));
console.log(params);
// Output: { name: "John", age: "30" }
2. String.prototype.padStart()
and padEnd()
What They Do
These methods add padding to a string until it reaches the desired length.
Example
const id = "123";
console.log(id.padStart(6, "0")); // Output: "000123"
console.log(id.padEnd(6, "X")); // Output: "123XXX"
Use Case
Display formatted numbers or align text for better readability:
const items = ["Apple", "Banana", "Cherry"];
items.forEach(item => console.log(item.padEnd(10, ".") + "✓"));
// Output:
// Apple.....✓
// Banana....✓
// Cherry....✓
3. Array.prototype.flat()
What It Does
flat()
flattens nested arrays into a single array.
Example
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(2));
// Output: [1, 2, 3, [4]]
Use Case
Combine multiple datasets with nested structures:
const data = [[1, 2], [3, 4], [5, 6]];
const merged = data.flat();
console.log(merged);
// Output: [1, 2, 3, 4, 5, 6]
4. Number.isInteger()
What It Does
Checks whether a value is an integer.
Example
console.log(Number.isInteger(10)); // Output: true
console.log(Number.isInteger(10.5)); // Output: false
Use Case
Validate numeric inputs in forms or APIs:
function validateInput(value) {
if (!Number.isInteger(value)) {
throw new Error("Input must be an integer");
}
}
validateInput(42); // Valid
validateInput(4.2); // Throws Error
5. Array.prototype.some()
and every()
What They Do
some()
: Checks if at least one element passes a condition.every()
: Checks if all elements pass a condition.
Example
const numbers = [10, 20, 30];
console.log(numbers.some(n => n > 25)); // Output: true
console.log(numbers.every(n => n > 25)); // Output: false
Use Case
Validate forms or datasets:
const fields = ["email", "password", "username"];
const isFilled = fields.every(field => field.trim().length > 0);
console.log(isFilled ? "All fields are filled" : "Some fields are empty");
6. Math.trunc()
What It Does
Removes the fractional part of a number, effectively truncating it.
Example
console.log(Math.trunc(4.9)); // Output: 4
console.log(Math.trunc(-4.9)); // Output: -4
Use Case
Use Math.trunc()
for fast integer extraction:
const price = 49.99;
console.log(`Price: $${Math.trunc(price)}`); // Output: Price: $49
7. Promise.allSettled()
What It Does
Waits for all promises to settle (either resolved or rejected) and returns their results.
Example
const promises = [
Promise.resolve("Success"),
Promise.reject("Error"),
Promise.resolve("Another Success")
];
Promise.allSettled(promises).then(results => console.log(results));
// Output:
// [
// { status: "fulfilled", value: "Success" },
// { status: "rejected", reason: "Error" },
// { status: "fulfilled", value: "Another Success" }
// ]
Use Case
Handle multiple API calls and ensure no errors are missed:
const urls = ["api/user", "api/posts", "api/comments"];
const requests = urls.map(url => fetch(url));
Promise.allSettled(requests).then(responses => {
responses.forEach((response, index) => {
console.log(`Request ${index + 1}:`, response.status);
});
});
8. Intl.NumberFormat
What It Does
Formats numbers according to different locales.
Example
const formatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(formatter.format(1234.5)); // Output: $1,234.50
Use Case
Display currency, percentages, or decimals in web applications:
const price = 4999.99;
console.log(new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(price));
// Output: 4.999,99 €
Conclusion
JavaScript's underrated built-in methods are true hidden gems that can drastically improve your coding experience. From simplifying array operations to managing promises and formatting data, these methods help you write cleaner, more efficient, and more readable code.
Take the time to explore and experiment with these methods. They might just become your new favorites!