JavaScript continues to grow and develop,
Because it's one of the easiest languages to pick up, it opens the door for new "become tech geeks" in the market. (True or false?)
Indeed, JavaScript can do a lot of wonderful things! There is still a lot to learn.
And, whether you're new to JavaScript or a more professional developer, learning something new is always a good thing.
I'll go over some very useful one-liners (20+ bonuses) that can help you be more productive and can help debug your code.
What is actually a single line of code?
One line of code is a coding practice in which we perform some function with only one line of code.
01 - Randomly get boolean values
This function will return a boolean value (true or false) using the Math.random() method.
Math.random creates a random number between 0 and 1, then we check if it is greater or less than 0.5.
This means there is a 50/50 chance of getting right or wrong.
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
02- Check if the date is a weekend
With this feature, you will be able to check if the date provided is a weekday or a weekend.
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
03 - Check if a number is even or odd
Simple utility function to check if a number is even or odd.
const isEven = (num) => num % 2 === 0;
console.log(isEven(5));
// false
console.log(isEven(4));
// true
04- Get unique values in an array
Very simple way to remove all duplicate values from an array. This function converts the array to Set and then returns the array.
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
05- Check if the variable is an array
A clean and easy way to check if a variable is an array.
Well, there can be other ways too 😉
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
06 - Generate a random number between two numbers
This will take two numbers as arguments and will generate a random number in between!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
07 - Generate random string (unique ID?)
Maybe you need to create a temporary unique ID for something, here's a trick you can use to generate random strings on the go.
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
08 - Scroll to the top of the page
The window.scrollTo() method puts an x and y coordinate to scroll to.
If you set them to zero and zero, it will scroll to the top of the page.
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
09 - toggle boolean
Switching boolean values is one of the very basic programming problems that can be solved in many different ways.
Instead of using an if statement to determine which value to set the boolean to, you can use a function to use ! Flip the current value . "Not" operator.
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
10 - Swap two variables
The following code is one of the easier ways to swap two variables with just one line of code without using a third variable.
[foo, bar] = [bar, foo];
11- Calculate the number of days between two dates
To calculate the number of days between two dates,
We first find the absolute value between two dates, then divide it by 86400000 (equal to the number of milliseconds in a day), and finally round the result and return it.
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
12- Copy text to clipboard
PS: You may need to add a check to see if navigator.clipboard.writeText exists
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text);
};
13- Different ways to merge multiple arrays
There are two ways to merge arrays. One of them is to use the "concat" method. The other is using the spread operator ("...").
PS: We can also use the "settings" object to copy anything from the final array.
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
14- Get the actual type of a javascript primitive
People sometimes use libraries to find the actual type of something in JavaScript, and this little trick can save you time (and code size).
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
15 - Truncate string at end
Need to truncate the string from scratch, that's not a problem!
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(
truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
16- Truncate the string from the middle
How about truncating the string from the middle?
The function takes a string as the first argument, then the size of the string we need as the second argument, then how many characters are needed to start and end from the 3rd and 4th arguments.
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // total size needed
13, // chars to keep from start
17, // chars to keep from end
),
);
// A long story ... eventually ends!
17 - uppercase string
Well, unfortunately JavaScript doesn't have a built-in function to capitalize strings, but this workaround should help you achieve your goal.
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
18- Check if the current tab is in view/focus
This simple helper method returns true or false depending on whether the tab is in view/focus
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
19- Check if the user is on an Apple device (judging the device system when doing compatibility)
Returns true if the user is using an Apple device
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
20 - Ternary operator
This is a good code saver when you just want to write an if..else statement in one line.
// Longhand
const age = 18;
let greetings;
if (age < 18) {
greetings = 'You are not old enough';
} else {
greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
Bonus - Short-Circuit Evaluation Shorthand
When assigning a variable value to another variable, you may need to ensure that the source variable is not null, undefined or empty.
You can write long if statements with multiple conditions, or use short-circuit evaluation.
// Longhand
if (name !== null || name !== undefined || name !== '') {
let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';
Source of translation <br>Author: Muhammad Ovi
Original link: 20 JavaScript One-Liners That Will Help You Code Like a Pro
Source: Dev.to
Article is authorized
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。