[Javascript] Check both prop exists and value is valid

Sometime you need to check one prop exists on the object and value should not be ´null´ or ´undefined´.

One problem people may occur with:

const {get} = require('lodash')
const obj = {a: 123}
const existing = typeof get(obj, 'a') !== undefined // true

Here we missed if the value of 'a' is null:

const obj = {a: null}
const existing = typeof get(obj, 'a') !== undefined // false, because typeof null === 'object'

 

To solve the problem we can actully using

get(obj, 'a') != null // double equals null checks both null and undefined cases

 

posted @ 2019-04-01 15:11  Zhentiw  阅读(149)  评论(0)    收藏  举报