Is it possible to use the core Node.js Assert module to check if a property exists on an object even if the property is falsy?
.html
normally we could check if an object has a property by running
var assert = require('assert');
assert(obj.prop);
but if obj.prop exists but is falsy, this won't work. I prefer using the Node.js assert module and would rather avoid other solutions, thanks.
Perhaps the best way to do this is:
var assert = require('assert');
assert(prop in obj);
Is it possible to use the core Node.js Assert module to check if a property exists on an object even if the property is falsy?
https://nodejs/api/assert.html
normally we could check if an object has a property by running
var assert = require('assert');
assert(obj.prop);
but if obj.prop exists but is falsy, this won't work. I prefer using the Node.js assert module and would rather avoid other solutions, thanks.
Perhaps the best way to do this is:
var assert = require('assert');
assert(prop in obj);
Share
Improve this question
edited Mar 11, 2016 at 0:12
gnerkus
12.1k7 gold badges54 silver badges74 bronze badges
asked Feb 18, 2016 at 0:45
Alexander MillsAlexander Mills
101k166 gold badges537 silver badges918 bronze badges
1
-
4
Your second snippet is best, works even if
prop
is set toundefined
. – Jared Smith Commented Feb 18, 2016 at 0:50
2 Answers
Reset to default 7It is possible to assert that an enumerable property exists on an object. The suggested code works excellently:
var assert = require('assert');
assert(prop in obj);
If the property does not exist, an AssertionError
is thrown.
When you try pare the attribute, if is undefined thrown an error, you need hasOwnProperty:
const assert = require('assert');
assert.equals(obj.hasOwnProperty('attribute'), true);