头图

11 common JS tips

In our daily development process, we often encounter numbers and strings conversion, check whether there is a corresponding value in an object, conditionally manipulate object data, filter error values in an array, and so on.

Here, I have sorted out some commonly used tips. These tips are my favorite ❤️, which can make our code leaner, cleaner, and very practical.

  1. Add properties to objects by conditional judgment
 const isValid = false;
const age = 18;

// 我们可以通过展开运算符向对象添加属性
const person = {
    id: 'ak001',
    name: 'ak47',
    ...(isValid && {isActive: true}),
    ...((age > 18 || isValid) && {cart: 0})
}

console.log('person', person)
  1. Check if a property exists in an object
 const person = {
    id: 'ak001',
    name: 'ak47'
}

console.log('name' in person); // true
console.log('isActive' in person); // false
  1. destructuring assignment
 const product = {
  id: 'ak001',
  name: 'ak47'
}

const { name: weaponName } = product;

console.log('weaponName:', weaponName); // weaponName: ak47

// 通过动态key进行解构赋值
const extractKey = 'name';
const { [extractKey]: data } = product;

console.log('data:', data); // data: ak47
  1. Loop through the keys and values of an object
 const product = {
  id: 'ak001',
  name: 'ak47',
  isSale: false
}

Object.entries(product).forEach(([key, value]) => {
  if(['id', 'name'].includes(key)) {
    console.log('key:',key, 'value:',value)
  }
})

// key: id value: ak001
// key: name value: ak47
  1. Use optional chaining to avoid errors when accessing object properties
 const product = {
  id: 'ak001',
  name: 'ak47'
}

console.log(product.sale.isSale); // throw error

console.log(product?.sale?.isSale); // undefined

Note⚠️: In actual usage scenarios, some scenarios are not necessary for the properties we want to obtain, we can avoid errors by the above method; but in some scenarios, some properties are required, otherwise it will affect our actual function, at this time, try to give a clear error message to solve this kind of error.

6. Check the value of falsy in the array

 const fruitList = ['apple', null, 'banana', undefined];

// 过滤掉falsy的值
const filterFruitList = fruitList.filter(Boolean);
console.log('filterFruitList:', filterFruitList); 
// filterFruitList:['apple', 'banana']
// 检查数组中是否有truthy的值
const isAnyFruit = fruitList.some(Boolean);
console.log('isAnyFruit:', isAnyFruit); // isAnyFruit: true

7. Array deduplication

 const fruitList = ['apple', 'mango', 'banana', 'apple'];

const uniqList = [...new Set(fruitList)]
console.log('uniqList:', uniqList); // uniqList: ['apple', 'mango', 'banana']
  1. Check if it is an array type
 const fruitList = ['apple', 'mango'];

console.log(typeof fruitList); // object
console.log(Array.isArray(fruiltList)); // true

9. Number & String Type Conversion

 const personId = '007';
console.log('personId:', +personId, 'type:', typeof +personId); 
// personId: 7 type: number

const personId = 119;
console.log('personId:', personId + '', 'type:', typeof (personId + '')); 
// personId: 119 type: string
  1. Clever use of null value coalescing (??)
 let data = undefined ?? 'noData;
console.log('data:', data); // data: noData

data = null ?? 'noData';
console.log('data:', data); // data: noData

data = 0 ?? null ?? 'noData';
console.log('data:', data); // data: 0

// 当我们根据变量自身判断时
data ??= 'noData';
console.log('data:', data); // data: noData
Difference between and or (||) operator? \
The OR operator is for falsy values (0,' ', null, undefined, false, NaN), while null coalescing only works for null and undefined;
  1. Boolean conversion via !!
 console.log('this is not empty:', !!'')
// this is not empty: false

console.log('this is not empty:', !!'Data')
// this is not empty: true

Finally, I hope these little tips can help you in your daily development. If you have a better way, please leave a message to share 😊


冷星的前端杂货铺
大道至简,知易行难,知行合一,得到功成;大道至简,悟在天成。

一个在程序猿修炼生涯中的修行者

1.6k 声望
742 粉丝
0 条评论
推荐阅读
浅谈Intl对象(DateTimeFormat、ListFormat、RelativeTimeFormat)
在JavaScript中,Intl对象是一个内置对象,它提供了处理国际化(i18n)的API。Intl对象包含了一系列的子对象,其中最常用的三个子对象是:Intl.DateTimeFormat、Intl.ListFormat和Intl.RelativeTimeFormat。下面...

前端荣耀阅读 395

封面图
ESlint + Stylelint + VSCode自动格式化代码(2023)
安装插件 ESLint,然后 File -> Preference-> Settings(如果装了中文插件包应该是 文件 -> 选项 -> 设置),搜索 eslint,点击 Edit in setting.json

谭光志34阅读 20.9k评论 9

安全地在前后端之间传输数据 - 「3」真的安全吗?
在「2」注册和登录示例中,我们通过非对称加密算法实现了浏览器和 Web 服务器之间的安全传输。看起来一切都很美好,但是危险就在哪里,有些人发现了,有些人嗅到了,更多人却浑然不知。就像是给门上了把好锁,还...

边城32阅读 7.4k评论 5

封面图
涨姿势了,有意思的气泡 Loading 效果
今日,群友提问,如何实现这么一个 Loading 效果:这个确实有点意思,但是这是 CSS 能够完成的?没错,这个效果中的核心气泡效果,其实借助 CSS 中的滤镜,能够比较轻松的实现,就是所需的元素可能多点。参考我们...

chokcoco24阅读 2.3k评论 3

你可能不需要JS!CSS实现一个计时器
CSS现在可不仅仅只是改一个颜色这么简单,还可以做很多交互,比如做一个功能齐全的计时器?样式上并不复杂,主要是几个交互的地方数字时钟的变化开始、暂停操作重置操作如何仅使用 CSS 来实现这样的功能呢?一起...

XboxYan25阅读 1.8k评论 1

封面图
在前端使用 JS 进行分类汇总
最近遇到一些同学在问 JS 中进行数据统计的问题。虽然数据统计一般会在数据库中进行,但是后端遇到需要使用程序来进行统计的情况也非常多。.NET 就为了对内存数据和数据库数据进行统一地数据处理,发明了 LINQ (L...

边城17阅读 2.1k

封面图
过滤/筛选树节点
又是树,是我跟树杠上了吗?—— 不,是树的问题太多了!🔗 相关文章推荐:使用递归遍历并转换树形数据(以 TypeScript 为例)从列表生成树 (JavaScript/TypeScript) 过滤和筛选是一个意思,都是 filter。对于列表来...

边城18阅读 7.9k评论 3

封面图

一个在程序猿修炼生涯中的修行者

1.6k 声望
742 粉丝
宣传栏