2

I've seen code on the web like this (simplified):

    var abc = {}; 
    Object.defineProperty(abc, 'example', {
        enumerable: 0,
        configurable: 1,
        writable: 1,
        value: function() {}
    });

where in place of true and false they use 1 and 0. I prefer this method for its simplicity, but I need to know:

Is this defining format nonstandard and inconsistent across browsers and should be avoided, or is it safe to use in production-level code?

Kithraya
  • 358
  • 2
  • 10
  • 3
    what is wrong with explicit values (read: the values need no implicit conversion)? – Nina Scholz Aug 28 '20 at 07:16
  • Nothing per-se. Its a matter of preference. It's slightly faster to type, and saves a few bytes. If implicit conversion is allowed, it allows for cool runtime tricks like `enumerable: ( retrieve(someVar) || getCurrentInheritance(someVar) )` – Kithraya Aug 28 '20 at 07:25
  • 3
    it saves nothing. it is confusing the reader and the expectation of allowed values. for example has `2` a meaning? – Nina Scholz Aug 28 '20 at 07:28
  • This might cause issues due to inconsistent behaviour: https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals – Sam Scholefield Aug 28 '20 at 07:29
  • 1
    if browsers consistently allow implicit conversion in this case, `2` would be the same as `1`, (`true`), as its a truthy value. `NaN` is `false`, etc. Specifically for numbers, `1` and `0` are synonymous with `true` and `false` anyway, so I don't see anyone being confused by this if we stick with `1` and `0` only. – Kithraya Aug 28 '20 at 07:31

1 Answers1

-2

It looks shorter in the code you wrote but having boolean is actually faster in many situations. You would have to write

if(writable===1){
...
}

instead of

if(writable){
...
}

same with the use of question marks which I find really nice in some situation:

writable? doThisIfTrue : doThisIfFalse

It's my first answer on the site and I'm a junior developer so I hope it helped!

Tsuina
  • 51
  • 4
  • `if(writable)` checks the "truthyness" of `writable`, it can be any value, not strictly a boolean value. The same is true for `writable ? true : false` – Olian04 Aug 28 '20 at 07:42