20 Practical JavaScript Tips

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


九旬的博客
关注我,每周输出一篇前端技术文章, 博客地址:[链接]

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
0 条评论
推荐阅读
单文件组件下的vue,可以擦出怎样的火花
与时俱进吧,看着 vue3 和 vite,虽然不会用,但还是心痒痒,然后就把原先基于 vue@2 的实现做了重构。不周之处,大家见谅!下面关于过期的内容,我就用删除线标记了。

leftstick64阅读 45.1k评论 18

从零搭建 Node.js 企业级 Web 服务器(零):静态服务
过去 5 年,我前后在菜鸟网络和蚂蚁金服做开发工作,一方面支撑业务团队开发各类业务系统,另一方面在自己的技术团队做基础技术建设。期间借着 Node.js 的锋芒做了不少 Web 系统,有的至今生气蓬勃、有的早已夭折...

乌柏木140阅读 11.9k评论 10

从零搭建 Node.js 企业级 Web 服务器(十五):总结与展望
总结截止到本章 “从零搭建 Node.js 企业级 Web 服务器” 主题共计 16 章内容就更新完毕了,回顾第零章曾写道:搭建一个 Node.js 企业级 Web 服务器并非难事,只是必须做好几个关键事项这几件必须做好的关键事项就...

乌柏木60阅读 5.9k评论 16

再也不学AJAX了!(二)使用AJAX ① XMLHttpRequest
「再也不学 AJAX 了」是一个以 AJAX 为主题的系列文章,希望读者通过阅读本系列文章,能够对 AJAX 技术有更加深入的认识和理解,从此能够再也不用专门学习 AJAX。本篇文章为该系列的第二篇,最近更新于 2023 年 1...

libinfs39阅读 6.1k评论 12

封面图
从零搭建 Node.js 企业级 Web 服务器(一):接口与分层
分层规范从本章起,正式进入企业级 Web 服务器核心内容。通常,一块完整的业务逻辑是由视图层、控制层、服务层、模型层共同定义与实现的,如下图:从上至下,抽象层次逐渐加深。从下至上,业务细节逐渐清晰。视图...

乌柏木39阅读 7.1k评论 6

CSS 绘制一只思否猫
欢迎关注我的公众号:前端侦探练习 CSS 有一个比较有趣的方式,就是发挥想象,绘制各式各样的图案,比如来绘制一只思否猫?思否猫,SegmentFault 思否的吉祥物,是一只独一无二、特立独行、热爱自由的(&gt;^ω^&lt...

XboxYan41阅读 2.8k评论 14

封面图
还在用 JS 做节流吗?CSS 也可以防止按钮重复点击
举个例子:一个保存按钮,为了避免重复提交或者服务器考虑,往往需要对点击行为做一定的限制,比如只允许每300ms提交一次,这时候我想大部分同学都会到网上直接拷贝一段throttle函数,或者直接引用lodash工具库

XboxYan34阅读 2.2k评论 2

封面图

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
宣传栏