let a = 1, b = 2;
[a, b] = [b, a];
// Output: a = 2, b = 1
This simple technique leverages array destructuring to exchange the values of a
and b
without the use of an intermediary variable. It's an elegant way to make your code both cleaner and more concise. The syntax [a, b] = [b, a]
works by breaking down the array on the right-hand side and reassigning it to the variables on the left-hand side.
const {name, age} = {name: 'John', age: 30};
// Output: name = 'John', age = 30
In this instance, object destructuring allows you to directly extract the name
and age
properties from an object into variables. This method streamlines the process of accessing object properties and makes the code easier to read.
const originalObj = {name: 'Jane', age: 22};
const clonedObj = {...originalObj};
// Output: clonedObj = {name: 'Jane', age: 22}
The spread operator (...
) is used to make a shallow copy of originalObj
. This method transfers all enumerable own properties from the original object to a new one.
Therefore, isn't it possible to just allocate the existing item to the new one?
const clonedObj = originalObj;
clonedObj.name = "George";
// Output: originalObj = {name: 'George', age: 22}
You have the option to do this, but clonedObj
will only serve as a reference to originalObj
. Therefore, any changes you make to the name
property on clonedObj
will also apply to the originalObj
!
const obj1 = {name: 'Jane'};
const obj2 = {age: 22};
const mergedObj = {...obj1, ...obj2};
// Output: mergedObj = {name: 'Jane', age: 22}
Just like cloning, the spread operator helps combine obj1
and obj2
into a new object. In cases where properties overlap, the values from the latter object will take precedence and overwrite those from the former.
const arr = [0, 1, false, 2, '', 3];
const cleanedArray = arr.filter(Boolean);
// Output: cleanedArray = [1, 2, 3]
This clever trick leverages Array.prototype.filter()
using the Boolean
constructor as a callback. It effectively removes all falsy values (0
, false
, null
, undefined
, ''
, NaN
) from an array.
const nodesArray = [...document.querySelectorAll('div')];
The spread operator allows you to transform a NodeList
(which you get from document.querySelectorAll
) into a JavaScript array. This conversion makes it possible to use array methods such as map
, filter
, and more.
const arr = [1, 2, 3, -1, 4];
const hasNegativeNumbers = arr.some(num => num < 0);
// Output: hasNegativeNumbers = true
The .some()
method determines whether at least one element in an array meets the condition set by the given function (in this case, whether it is negative), whereas .every()
checks if every element satisfies the condition (being positive).
const arr = [1, 2, 3, -1, 4];
const allPositive = arr.every(num => num > 0);
//Output: allPositive = false
navigator.clipboard.writeText('Text to copy');
This code snippet leverages the Clipboard API to automatically copy text to the user's clipboard. It's a contemporary method for clipboard operations, ensuring that text copying is both smooth and effective.
const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)];
// Output: unique = [1, 2, 3, 4, 5]
This leverages the Set
object, known for storing unique values, along with the spread operator to transform it back into an array. It's an efficient method to eliminate duplicates from an array.
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4, 6, 8];
const intersection = arr1.filter(value => arr2.includes(value));
// Output: intersection = [2, 4]
This example employs Array.prototype.filter()
to identify shared elements between arr1
and arr2
. The callback function verifies whether each element of arr1
exists in arr2
, yielding an array that contains the intersecting values.
const arr = [1, 2, 3, 4];
const sum = arr.reduce((total, value) => total + value, 0);
// Output: sum = 10
This one-liner leverages the reduce
method to sum up all the values within an array into one total. The reduce
method accepts a callback function with two arguments: the accumulator (total
) and the current element (value
). Beginning with an initial value of 0, it traverses the array, adding each item to the accumulated sum.
const condition = true;
const value = 'Hello World';
const newObject = {...(condition && {key: value})};
// Output: newObject = { key: 'Hello World' }
By employing the spread operator (...
) alongside short-circuit evaluation, you can effortlessly add a property to an object based on a condition. When condition
holds true, {key: value}
gets incorporated into the object; if it doesn't, no changes are made.
const dynamicKey = 'name';
const value = 'John Doe';
const obj = {[dynamicKey]: value};
// Output: obj = { name: 'John Doe' }
Computed property names enable the use of a variable as an object's key. By placing square brackets around dynamicKey
, the expression inside is evaluated and used as the property name.
const isOnline = navigator.onLine ? 'Online' : 'Offline';
// Output: isOnline = 'Online' or 'Offline'
Leverage the ternary operator in this snippet to assess the browser's online status via navigator.onLine
. If the result is true, it returns 'Online'; if false, 'Offline'. This offers an efficient method to check the user's connectivity in real-time. Additionally, you can utilize available event listeners for this purpose.
window.onbeforeunload = () => 'Are you sure you want to leave?';
This piece of code connects to the window’s onbeforeunload
event. This event initiates a confirmation dialog when a user tries to navigate away from the page, serving as a safeguard against losing any unsaved changes.
const arrayOfObjects = [{x: 1}, {x: 2}, {x: 3}];
const sumBy = (arr, key) => arr.reduce((acc, obj) => acc + obj[key], 0);
sumBy(arrayOfObjects, 'x'));
// Output: 6
This function leverages the reduce
method to add up the values associated with a specified key in an array of objects. It offers a versatile approach to computing totals from an array of objects using a particular key.
const query = 'name=John&age=30';
const parseQuery = query => Object.fromEntries(new URLSearchParams(query));
// Output: parseQuery = { name: 'John', age: '30' }
This expression changes a query string into an object. URLSearchParams
analyzes the query string, while Object.fromEntries
converts the iterable pairs into an object, making it easy to retrieve URL parameters.
const seconds = 3661;
const toTimeString = seconds => new Date(seconds * 1000).toISOString().substr(11, 8);
toTimeString(seconds));
// Output: '01:01:01'
This line transforms seconds into a string formatted as HH:MM:SS. It does this by generating a new Date object starting from the epoch and adding the specified seconds, then converting it to an ISO string and pulling out the time part.
const scores = {math: 95, science: 99, english: 88};
const maxObjectValue = obj => Math.max(...Object.values(obj));
maxObjectValue(scores));
// Output: 99
This simple line of code identifies the highest value within an object's values. First, Object.values(obj)
pulls out the values and converts them into an array. Then, by spreading this array into Math.max
, we determine the maximum value.
const person = {name: 'John', age: 30};
const hasValue = (obj, value) => Object.values(obj).includes(value);
hasValue(person, 30);
// Output: true
This function determines whether a specified value is present among an object's values. By using Object.values(obj)
, you can retrieve an array containing the values of the object. Then, includes(value)
is employed to verify if the array includes that particular value.
const scores = [45, 75, 62, 55, 90];
const updatedScores = scores.map(score => score < 60 ? score + 20 : score);
// Output: updatedScores = [65, 75, 62, 75, 90]
This simple one-liner employs the Array.map()
method to loop through each score within the scores
array. Inside the callback function, the ternary operator (condition ? exprIfTrue : exprIfFalse
) evaluates if a score falls below 60. If the condition is met, it adds 20 to the score; if not, the score remains unchanged. This is an excellent approach to applying inline conditional logic during array transformations. It's ideal for modifying data based on conditions without requiring a lengthy if-else
block.
const user = { profile: { name: 'John Doe' } };
const userName = user.profile?.name ?? 'Anonymous';
// Output: userName = 'John Doe'
This one-liner demonstrates the use of the optional chaining operator (?.
) to safely access name
within user.profile
. If user.profile
happens to be undefined
or null
, it short-circuits and returns undefined
, thereby preventing a potential TypeError
.
The nullish coalescing operator (??
) evaluates if the left-hand side is null
or undefined
. If either condition is met, the operator defaults to 'Anonymous'. This approach provides a fallback value without mistakenly triggering on other falsy values like ''
or 0
. It's especially useful for accessing deeply nested properties in data structures where some intermediate properties may be missing.
In JavaScript, you can use either the nullish coalescing operator (??
) or the logical OR (||
) to set default values. However, they operate differently when it comes to handling falsy values.
In the example above, replacing ??
with ||
would slightly alter the behavior. The logical OR operator (||
) returns the right-hand operand if the left-hand operand is falsy. In JavaScript, falsy values include null
, undefined
, 0
, NaN
, ''
(empty string), and false
. Consequently, the ||
operator will return the right-hand operand for any of these falsy values, not just null
or undefined
.
const isEligible = true;
isEligible && performAction();
// performAction is called if isEligible is true
By utilizing the logical AND (&&
) operator, this approach calls performAction()
only when isEligible
returns true
. This offers a succinct way to conditionally run a function without needing an if
statement. It can be particularly handy for executing functions based on certain conditions, such as in event handlers or callbacks.
const range = Array.from({ length: 5 }, (_, i) => i + 1);
// Output: range = [1, 2, 3, 4, 5]
Array.from()
generates a new array from any array-like or iterable object. In this instance, it processes an object that includes a length
attribute and a mapping function. The provided mapping function ((_, i) => i + 1
) leverages the index (i
) to create numbers ranging from 1 to 5. The underscore (_
) is commonly used to indicate an unused parameter.
const timeout = (promise, ms) => Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), ms))
]);
timeout(fetch('https://api.example.com'), 5000).then(handleResponse).catch(handleError);
This code snippet establishes a promise that will reject with a "Timeout" error if it isn't resolved within a designated number of milliseconds. It employs Promise.race()
to compete the provided promise
against a timeout promise that rejects automatically after ms
milliseconds. This function is ideal for implementing timeout behavior in fetch requests or any asynchronous tasks that might hang or take an excessive amount of time.
If you're new to using Promises in JavaScript, the explanation above might require a bit more detail.
In JavaScript, a Promise symbolizes the future outcome (success or failure) of an asynchronous task and the value that it produces. A Promise can exist in one of the following states:
- Pending: This is the starting phase of a Promise. At this point, the operation is still in progress and hasn't finished.
- Fulfilled: The operation was a success, and the Promise now holds a value.
- Rejected: The attempt was unsuccessful, and the Promise provides an explanation for why it failed.
Promises let you add callbacks to manage the result when it’s fulfilled or the reason it’s rejected, all without needing to directly deal with the asynchronous aspect of the task.
Utilizing Promise.race()
. Keep the atmosphere and style of the text, and maintain the original phrases and HTML tags.
The Promise.race()
method accepts an iterable containing multiple Promise objects. It produces a new Promise that either resolves or rejects as soon as any of the Promises in the iterable complete, using the value or reason of the first settled Promise.
Understanding the Functionality of the timeout
Function
Keep the same tone and relaxed mood as the original text.
The timeout
function shown in the example adds a timeout feature to any Promise, like a fetch
request. It sets up a race condition between the given Promise and a newly created Promise that automatically rejects after a set amount of time in milliseconds.
This method is especially beneficial for making sure your application can smoothly manage scenarios where an asynchronous operation may get stuck or last too long, by offering a way to "give up" and address the timeout as an error.
const fileName = 'example.png';
const getFileExtension = str => str.slice(((str.lastIndexOf(".") - 1) >>> 0) + 2);
// Output: getFileExtension = 'png'
This expression is used to retrieve the file extension from a string. It locates the final instance of the dot character (.
) and slices the string from that point onward. The bitwise operator (>>>
) guarantees a safe operation even when the dot isn't present, resulting in an empty string in those scenarios.
const isTabFocused = () => document.hasFocus();
// Output: true (if the tab is focused), false otherwise
Leverages the document.hasFocus()
method to ascertain if the document (or tab) currently has focus. This provides a simple way to figure out if the user is actively looking at or engaging with the page. Useful for pausing or resuming activities depending on user presence, such as halting video playback when the user navigates to a different tab.
const element = document.querySelector('.my-element');
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(element, 'active');
This function utilizes the classList.toggle()
method to either add or delete a class from an element's list of classes. When the class is already present, it removes it, and when it isn't, it adds it. This approach is an efficient way to manage dynamic class modifications depending on user interactions or the current state of an application. It's ideal for creating responsive design components like menus or modals that appear or disappear based on user activity.
And that’s it!
Here are 28 concise JavaScript one-liners that provide powerful features efficiently. Hopefully, today brought you some new insights!