14
头图

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 声望745 粉丝

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