Search code examples
javascriptternary

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?


Solution

  • 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