user12282936
user12282936

Reputation: 167

Ternary expression with a javascript object

Let's say I have the following javascript object:

var __error__ = {0: 'ok'}

I want to return an empty string if the key is not in the obj, and an error message otherwise. For example:

var value = __error__[col_num] ? "The value cannot be converted" : ""

How could this be done with a ternary expression properly? Do I need to do __error__[col_num] == undefined ? Or does the above expression evaluate to false by itself?

Upvotes: 2

Views: 3496

Answers (2)

nick zoum
nick zoum

Reputation: 7295

If you only want to check if they key exists in the object and not that the troothy of the value is false you should use the in operator

var value = col_num in __error__ ? "The value cannot be converted" : ""

You can also use Object.hasOwnProperty which returns true only if the object has that property (will return false if the property was inherited).

Here are a couple of examples to illustrate the differences

var parent = {
  foo: undefined
};

var child = Object.create(parent);

console.log("foo" in parent); // parent has the "foo" property
console.log("foo" in child); // child has the "foo" property

console.log(parent.hasOwnProperty("foo")); // parent has the "foo" property
console.log(child.hasOwnProperty("foo")); // child has the "foo" property but it belonds to parent

console.log(child.foo !== undefined); // the foo property of child is undefined
console.log(!!child.foo); // the troothy of undefined is false

console.log(parent.foo !== undefined); // the foo property of parent is undefined
console.log(!!parent.foo); // the troothy of undefined is false

Upvotes: 2

brk
brk

Reputation: 50291

You can also use hasOwnProperty which returns a boolean indicating whether the object has the specified property

var __error__ = {
  0: 'ok'
}

var value = __error__.hasOwnProperty(1) ? "The value cannot be converted" : "Empty";
console.log(value)

Upvotes: 1

Related Questions