Gets the number of characters in a string
Getting the number of characters is a useful utility, useful in many situations. You can use it to get the number of Spaces and subsequent words, or this can be used to get the count of a delimiter in a string.
const characterCount = (str, char) => str.split(char).length - 1
Copy the code
The idea is very simple. We split the string using the passed argument char and get the length of the returned array. Because every time you split a string, you have one more string than the splitter; So minus 1, we have a characterCount single line.
Check whether the object is empty
Checking for an object’s nullity is actually more difficult than it looks. Each check to see if the object is equal to {} returns false, even if the object is null.
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
Copy the code
** Reflect.ownkeys ()** Returns an array of the target object’s own property keys.
In this line, we check whether the length of the object’s key is equal to zero and whether the argument passed is the actual object.
Wait a certain period of time before executing the command
In this single line of code, we’ll touch on some asynchronous programming. The idea is simple.
If you want to wait a certain amount of time while running code, here is wait one-liner:
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const test = async()=>{
await wait(1000)
console.log("hello world")
}
test()
Copy the code
In wait one-liner, we create a promise and resolve it after a given time using the setTimeout function.
Gets the day difference between two dates
Dates are often the most confusing part of Web application development, because there are so many concepts that can easily be miscalculated.
This is a powerful one-line program to calculate the day difference between two dates. But more needs to be done. Like me, you can create your own single line to calculate month, year, etc.
const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))
daysBetween(new Date('2021-8-26'),new Date('2021-8-16'))
Copy the code
The logic behind this single line is easy to understand. When two dates are subtracted, the return value is the difference in milliseconds. To convert milliseconds into days, we must divide them by milliseconds, seconds, minutes, and hours, respectively.
Redirect to another URL
If you’ve ever created a real website, I’m sure you’ve encountered authentication logic. For example, non-administrator users should not be able to access the /admin route. If the user tries, then you must redirect it to another URL.
This single line works just fine for the situation I mentioned above, but I think you can find more use cases.
const redirect = url => location.href = url
redirect('https://www.baidu.com/')
Copy the code
Location is a method on the global Window object that sets the href property to behave the same as when the user clicks on a link.
Check for touch support on your device
As the number of devices that can connect to the Internet grows, so does the need to create responsive websites. Twenty years ago, developers should have considered desktop websites, but today more than 50% of web traffic comes from touch devices.
So it’s such an important concept to do something with device-based touch support.
const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)
console.log(touchSupported()) // true or false
Copy the code
In this line, we are checking whether the document supports the TouchStart event.
Simplest single-line rating component
"★★★★★ ★★★★★ ★★★★★ ★★★★★ ★ ".Copy the code
JS error handling the correct posture (directly locate the cause of the error)
try {
// something
} catch (e) {
window.location.href =
"http://stackoverflow.com/search?q=[js]+" + e.message;
}
Copy the code
Learn JavaScript from a single line of code (How to quickly know all element borders)
[].forEach.call($$("*"),function(a){
a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})
Copy the code
Another common way to write this is:
Array.prototype.forEach.call(document.querySelectorAll( * ), #${parseInt(math.random () * math.pow (2,24)).tostring (16)} ')Copy the code
Fastest cache clearing method ever
<a href="javascript:alert; > Clear cache </a>Copy the code
Single line if-else statement
This is a common feature of many programming languages. Instead of writing if-else on multiple lines, you can write an entire statement in one line using the ternary operators.
Such as:
const age = 12;
let ageGroup;
// LONG FORM
if (age > 18) {
ageGroup = "An adult";
} else {
ageGroup = "A child";
}
// SHORTHAND
ageGroup = age > 18 ? "An adult" : "A child";
Copy the code
However, don’t overuse it. It makes your code more verbose. It is wise to replace simple expressions only with this to improve readability and reduce the number of lines of code.
Removes duplicates from the array
In JavaScript, a Set is a collection that allows you to store only unique values. This means removing any duplicate values.
So, to remove duplicates from an array, you can convert them to a collection and then back to an array.
const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)]; // -> [1, 20, 3, 9]
Copy the code
Confused? Let me explain how it works:
1) new Set(numbers) creates a Set from the list of numbers. Creating a collection automatically removes all duplicate values.
2) expand operator… Converts any iterable to an array. This means converting a collection back to an array. […new Set(numbers)]
Short if-else null merge
This is also short for if-else.
Instead of using if-else constructs, you can use a bullish merge to check if the value is null. The Nullish merge operation?? Returns the right if left is not defined. If so, return to the left:
let maybeSomething;
// LONG FORM
if(maybeSomething){
console.log(maybeSomething)
} else {
console.log("Nothing found")
}
//SHORTHAND
console.log(maybeSomething ?? "Nothing found")
Copy the code
Optional chain to prevent crashes
If an undefined property is accessed, an error is generated. This is where optional chains come in.
Use the optional chain operator when an attribute is undefined; undefined returns an error instead. This prevents your code from crashing.
Such as:
const student = { name: "Matt", age: 27, address: { state: "New York" }, }; // LONG FORM console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined // SHORTHAND console.log(student? .address? .ZIPCode); // Doesn't exist - Returns undefinedCopy the code
Swap two variables without a third variable
In JavaScript, you can use deconstruction to split scores from arrays. This can be applied to swapping two variables without the need for a third:
let x = 1; let y = 2; // LONGER FORM let temp = x; x = y; y = temp; // SHORTHAND [x, y] = [y, x];Copy the code
Converts any value to a Boolean value
In JavaScript, you can use!! Convert anything to a Boolean value in JS.
For example, here are some examples:
!!!!! true // true !! 2 // true !! [] // true !!" Test" // true !! false // false !! 0 // false !!" " // falseCopy the code
Extended operator
Combine two arrays using the extension operator… :
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
// LONG FORM
let newArray = nums1.concat(nums2);
// SHORTHAND
newArray = [...nums1, ...nums2];
Copy the code
You can also use this syntax instead of pushing values to arrays:
let numbers = [1, 2, 3];
// LONGER FORM
numbers.push(4);
numbers.push(5);
// SHORTHAND
numbers = [...numbers, 4, 5];
Copy the code
Transmission of deconstruction
Assign the remaining elements to the variable using the extension operator:
const student = { name: "Matt", age: 23, city: "Helsinki", state: "Finland", }; // LONGER FORM const name = student.name; const age = student.age; const address = { city: student.city, state: student.state }; // SHORTHAND const { name, age, ... address } = student;Copy the code
Use && for short circuit evaluation
Instead of using the if statement to check if something is true, you can use the && operator:
var isReady = true; function doSomething(){ console.log("Yay!" ); } // LONGER FORM if(isReady){ doSomething(); } // SHORTHAND isReady && doSomething();Copy the code
Steroid string
Inserts variables between strings by wrapping strings in backquotes and ${} for embedding values.
Such as:
const age = 41;
const sentence = `I'm ${age} years old`;
// result: I'm 41 years old
Copy the code
Finds a specific element from an array
Use the find() method to find elements that match a particular condition:
const fruits = [
{ type: "Banana", color: "Yellow" },
{ type: "Apple", color: "Green" }];
// LONGER FORM
let yellowFruit;
for (let i = 0; i < fruits.length; ++i) {
if (fruits[i].color === "Yellow") {
yellowFruit = fruits[i];
}
}
// SHORTHAND
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow");
Copy the code
Object property assignment
Do you want object keys and values to have the same name? You can do this by omitting the object text:
const name = "Luis", city = "Paris", age = 43, favoriteFood = "Spaghetti";
// LONGER FORM
const person = {
name: name,
city: city,
age: age,
favoriteFood: favoriteFood
};
// SHORTHAND
const person = { name, city, age, favoriteFood };
Copy the code
Compression For loop
Loop through the array using the built-in forEach() method in one line of code:
const numbers = [1, 2, 3, 4, 5];
// LONGER FORM
for(let i = 0; i < numbers.length; i++){
console.log(numbers[i]);
}
// SHORTHAND
numbers.forEach(number => console.log(number));
Copy the code
Default Function Parameters
You can provide default values for function arguments:
// LONG FORM
function pickUp(fruit) {
if(fruit === undefined){
console.log("I picked up a Banana");
} else {
console.log(`I picked up a ${fruit}`);
}
}
// SHORTHAND
function pickUp(fruit = "Banana") {
console.log(`I picked up a ${fruit}`)
}
pickUp("Mango"); // -> I picked up a Mango
pickUp(); // -> I picked up a Banana
Copy the code
Collects the value of an object into an array
Use object.values () to collect all the values of an Object into a new array:
const info = { name: "Matt", country: "Finland", age: 35 }; // LONGER FORM let data = []; for (let key in info) { data.push(info[key]); } // SHORTHAND const data = Object.values(info);Copy the code
Checks if an item exists in the array
This is not necessarily shorthand, as you will rarely save more than a few characters. But this is a cleaner way.
Instead of using indexOf(), you can use the includes() method to check if elements are in an array. This makes your intention very clear:
let numbers = [1, 2, 3];
// LONGER FORM
const hasNumber1 = numbers.indexOf(1) > -1 // -> True
// SHORTHAND/CLEANER APPROACH
const hasNumber1 = numbers.includes(1) // -> True
Copy the code
Compress multiple conditions
Avoid using long | | check chain multiple conditions, you can use you just learned in the previous tip things – that is, using includes () method:
const num = 1; // LONGER FORM if(num == 1 || num == 2 || num == 3){ console.log("Yay"); } / / SHORTHAND if ([1, 2, 3]. Includes (num)) {the console. The log (" Yay "); }Copy the code
Exponential operator
Do you math.pow () get used to raising a number to a power? Did you know you can also use the ** operator?
/ / LONGER FORM math.h pow (4, 2); / / 16 math.h pow (2, 3); // 8 // SHORTHAND 4**2 // 16 2**3 // 8Copy the code
Math. Floor () short
Rounding math.floor () is nothing new. But did you know that you can also use the ~~ operator?
Such as:
/ / LONG FORM math.h floor (5.25) / / - > 5.0 / / / / SHORTHAND ~ ~ 5.25 - > 5.0Copy the code
Assign multiple values in a single line of code
Allocate multiple values in a line using destruct syntax:
let num1, num2; // LONGER FORM num1 = 10; num2 = 100; // SHORTHAND [num1, num2] = [10, 100];Copy the code
This also applies to using JavaScript objects:
student = {
name: "Matt",
age: 29,
};
// LONGER FORM
let name = student.name;
let age = student.age;
// SHORTHAND
let { name, age } = student;
Copy the code
Insert a string of HTML after the element
It is common to develop Web applications that update the DOM with JavaScript. There are some basic ways to get the job done, but when things get complicated, it’s hard to overcome.
This is a single line of code that injects a string of HTML immediately after the HTML element. With a few minutes of thought and a Google search, I’m sure you can find an earlier version of this single line.
const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)
Copy the code
Shuffling arrays is a common situation that you can run into at any time during development, and unfortunately there is no built-in array shuffling method in JavaScript. But here’s the shuffle one-liner you can use every day:
Const shuffle => arr.sort(() => 0.5 - math.random ())Copy the code
It uses the sorting method of an array to sort randomly before or after the preceding element.
Gets the selected text on the web page
The browser has a built-in method called getSelection on the global Windows object.
Using this method, you can create a single line that returns highlighted or selected text on a web page.
const getSelectedText = () => window.getSelection().toString()
Copy the code
Gets a random Boolean value
When programming, especially when writing a game, there are times when you want to act randomly. In this case, the following single line is very convenient.
Const getRandomBoolean = () => math.random () >= 0.5Copy the code
The single line above has a 50/50 chance of returning true or false. Because the probability of generating a random number greater than 0.5 is equal to a smaller probability.
But, for example, if you wanted a random Boolean with a 70% chance of error, you could simply change 0.5 to 0.7, and so on.
Compute the average of the array
You can calculate the average of an array in a number of ways. But the principle is the same for everyone. You have to get the sum of the array and its length; And then the division gives you the average.
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
Copy the code
In averaging a single row, we use reduce to get the sum of the arrays in the row instead of using a loop. And then we divide that by the length of the array, which is the average of the array.