Building a Blogging Site with React and PHP: A Step-by-Step Guide
Uncover Lesser-Known JavaScript Hacks for Smarter Coding
Welcome to our curated collection of JavaScript tricks, which will help you optimize your code, make it more readable, and save you time.
Letβs dive into the depths of JavaScript functionalities and hacks that go beyond the conventional and discover the full potential of this powerful programming language.
Quickly convert any value to a boolean by using double negation.
let truthyValue = !!1; // true
let falsyValue = !!0; // false
Set default values for function parameters to avoid undefined errors.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
A shorthand for the if-else statement.
let price = 100;
let message = price > 50
? "Expensive"
: "Cheap";
Use template literals for embedding expressions in strings.
let item = "coffee";
let price = 15;
console.log(`One ${item} costs $${price}.`);
let [x, y] = [1, 2];
let {name, age} = {name: "Alice", age: 30};
Clone arrays or objects without referencing the original.
let originalArray = [1, 2, 3];
let clonedArray = [...originalArray];
Use logical operators for conditional execution.
let isValid = true;
isValid && console.log("Valid!");
Safely access nested object properties without an error if a reference is nullish.
let user = {name: "John", address: {city: "New York"}};
console.log(user?.address?.city); // "New York"
Use ?? to provide a default value for null or undefined.
let username = null;
console.log(username ?? "Guest"); // "Guest"
map, filter, and reduce for Array ManipulationElegant ways to handle arrays without traditional loops.
// Map
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(x => x * 2);
// Filter
const evens = numbers.filter(x => x % 2 === 0);
// Reduce
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
Function calls using template literals for custom string processing.
function highlight(strings, ...values) {
return strings.reduce((prev, current, i) =>
`${prev}${current}<strong>${values[i] || ''}</strong>`, '');
}
let price = 10;
console.log(highlight`The price is ${price} dollars.`);
Convert objects to arrays and back for easier manipulation.
let person = {name: "Alice", age: 25};
let entries = Object.entries(person);
let newPerson = Object.fromEntries(entries);
Use Set to store unique values of any type.
let numbers = [1, 1, 2, 3, 4, 4];
let uniqueNumbers = [...new Set(numbers)];
Use square brackets in object literal notation to create dynamic property names.
let dynamicKey = 'name';
let person = {[dynamicKey]: "Alice"};
Create a new function that, when called, has its this keyword set to the provided value.
function multiply(a, b) {
return a * b;
}
let double = multiply.bind(null, 2);
console.log(double(5)); // 10
Convert array-like or iterable objects into true arrays.
let nodeList = document.querySelectorAll('div');
let nodeArray = Array.from(nodeList);
Iterate over iterable objects (including arrays, maps, sets, etc.) directly.
for (let value of ['a', 'b', 'c']) {
console.log(value);
}
Run multiple promises concurrently and wait for all to settle.
let promises = [
fetch(url1),
fetch(url2)
];
Promise.all(promises)
.then(responses =>
console.log('All done')
);
Capture any number of arguments into an array.
function sum(...nums) {
return nums.reduce(
(acc, current) =>
acc + current,
0
);
}
Store function results to avoid redundant processing.
const memoize = (fn) => {
const cache = {};
return (...args) => {
let n = args[0]; // assuming single argument for simplicity
if (n in cache) {
console.log('Fetching from cache');
return cache[n];
} else {
console.log('Calculating result');
let result = fn(n);
cache[n] = result;
return result;
}
};
};
Swap the values of two variables without a temporary variable using the XOR bitwise operator.
let a = 1, b = 2;
a ^= b;
b ^= a;
a ^= b;
// a = 2, b = 1
Easily flatten nested arrays using the flat() method, with the depth of flattening as an optional argument.
let nestedArray = [1, [2, [3, [4]]]];
let flatArray = nestedArray.flat(Infinity);
Quickly convert strings or other values to numbers using the unary plus operator.
let str = "123";
let num = +str; // 123 as a number
Use template strings to create HTML fragments, making dynamic HTML generation cleaner.
let items = ['apple', 'orange', 'banana'];
let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`;
Merge multiple source objects into a target object, effectively combining their properties.
let obj1 = { a: 1 }, obj2 = { b: 2 };
let merged = Object.assign({}, obj1, obj2);
Utilize logical operators to assign default values when dealing with potentially undefined or null variables.
let options = userOptions || defaultOptions;
Access properties of an object dynamically using bracket notation, useful when the property name is stored in a variable.
let property = "name";
let value = person[property]; // Equivalent to person.name
Check if an array includes a certain value with includes(), a clearer alternative to indexOf.
if (myArray.includes("value")) {
// Do something
}
Bind a function to a context (this value) and partially apply arguments, creating more reusable and modular code.
const greet = function(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
};
const greetJohn = greet.bind({name: 'John'}, 'Hello');
console.log(greetJohn('!')); // "Hello, John!"
Prevent modifications to an object using Object.freeze(), making it immutable. For deeper immutability, consider libraries that enforce immutability more thoroughly.
let obj = { name: "Immutable" };
Object.freeze(obj);
obj.name = "Mutable"; // Fails silently in non-strict mode
I hope these JavaScript tricks provide you with new perspectives on how to approach JavaScript programming.
From leveraging the concise power of template literals to mastering the efficiency of map, filter, and reduce, these JavaScript hacks will enrich your development workflow and inspire your next project.
Let these JavaScript tricks not only refine your current projects but also spark inspiration for future innovations in your coding journey.
π» Level up with the latest tech trends, tutorials, and tips - Straight to your inbox β no fluff, just value!
Your email address will not be published. Required fields are marked *
Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!
Comments (1)