Check if property exists in object and is truthy
How to solve it
In another similar challenge, we had to check whether a certain property exists in an object, no matter what value the property had. But, sometimes you want to make sure that the value of the property is truthy, i.e. not null or undefined or false etc.
This can be achieved in a simple two-step process. First, we try to access the requested property using the square bracket notation (see this challenge for reference). This will give us either the value of the property or undefined if the property does not exist:
const obj = { x: false };
console.log(obj['x']);
// output: false
console.log(obj['a']);
// output: undefined
Then we transform the result to a boolean value using the Boolean function. The Boolean function transforms a truthy value to true, and false otherwise.
const a = 2;
const b = undefined;
console.log(Boolean(a));
// output: true
console.log(Boolean(b));
// output: false
If we combine both methods, we can make sure that a certain property exists in the object and its value is truthy.