Checking For Property Existence In JavaScript
In JavaScript code, when checking for a property sometimes a truthy check or undefined check is incorrectly used since they work in most cases. For example, for the truthy check (The correct output should only give "other" as false):
let weight; const car = { name: 'miata', hp: 0, weight, }; console.log('Has "name":', car.name ? true : false); // Has "name": true console.log('Has "hp":', car.hp ? true : false); // Has "hp": false console.log('Has "weight":', car.weight ? true : false); // Has "weight": false console.log('Has "other":', car.other ? true : false); // Has "other": false
console.log('Has "name":', car.name !== undefined); // Has "name": true console.log('Has "hp":', car.hp !== undefined); // Has "hp": true console.log('Has "weight":', car.weight !== undefined); // Has "weight": false console.log('Has "other":', car.other !== undefined); // Has "other": false
Instead the in operator should be used directly in this case:
console.log('Has "name":', 'name' in car); // Has "name": true console.log('Has "hp":', 'hp' in car); // Has "hp": true console.log('Has "weight":', 'weight' in car); // Has "weight": true console.log('Has "other":', 'other' in car); // Has "other": false
Using in also ensures that property deletion is separated from reassignment. Since the only way to delete a property is to use the delete keyword explicitly:
delete car.hp; console.log('Has "name":', 'name' in car); // Has "name": true console.log('Has "hp":', 'hp' in car); // Has "hp": false console.log('Has "weight":', 'weight' in car); // Has "weight": true console.log('Has "other":', 'other' in car); // Has "other": false
Finally, it is important to keep in mind in will check all properties in an object including ones inherited from parent objects. Usually this is what is intended, but if not the Object.hasOwnProperty() method can be used
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/in.js