Zze
Zze

Reputation: 18805

Return bool instead of operand

Is there any method to return a bool for this example instead of one of the operands?

var json = {"test":"asd", "example":"fgh"};
var exists = json.test && json.example;

console.log(exists); // returns 'fgh'
console.log(json.test && json.example); // returns 'fgh'

To achieve the equivalent of:

var json = {"test":"asd", "example":"fgh"};
var exists= json.hasOwnProperty("test") && json.hasOwnProperty("example");

console.log(exists); // returns true

Upvotes: 0

Views: 68

Answers (2)

Robert
Robert

Reputation: 10390

Simplest thing I can think of is:

var json = {"test":"asd", "example":"fgh"};
var exists = json.test && json.example;
console.log(Boolean(exists));

returns true

Upvotes: 1

Trash Can
Trash Can

Reputation: 6824

This is how you convert a non-boolean value to a boolean

var json = {"test":"asd", "example": "fgh"};
var exists = !!(json.test && json.example); // converts to boolean

console.log(exists); // returns a boolean value

Upvotes: 2

Related Questions