Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and getting a boolean object property in JavaScript

So I just submitted my very first pull request on a collaborative software project (a web app built with Ember.js), and I noticed that I had carelessly included a boolean variable (conditionally set inside a function) in an object literal using only the variable name rather than a key-value pair, like so:

function fruitStand () {
  // do something here to decide if this basket is pretty, and if not..
  var prettyBasket = false;

  var myObj = {
    apples : 1,
    oranges : 2,
    prettyBasket
  };

  return myObj;

}

I was surprised that accessing the boolean later with

var stand = fruitStand();
var truthy = stand.prettyBasket;

seems to work, but is this valid JavaScript? Otherwise poor form? Setting it with something like prettyBasket : prettyBasket feels less DRY if the above is OK.

like image 936
HowlingFantods Avatar asked Jul 06 '15 19:07

HowlingFantods


People also ask

What is boolean object in JavaScript?

The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

How do you declare a Boolean function in JavaScript?

var a1 ="true"; var a2 ="false"; Boolean() function in JavaScript: Boolean function returns the boolean value of variable. It can also be used to find boolean result of a condition, expression etc. Note: A variable or object which has value are treated as true boolean values.

How do you assign a boolean?

Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.


1 Answers

You are unintentionally utilizing a feature of ES6, specifically shorthand object literal notation, which you can read more about here.

Also, depending on whether or not the application you are working on is built with Ember-cli (and is using an ES6 transpiler) or you are building a regular Ember application (potentially without transpilation), you should be cognizant that only the latest browsers will support that code unless it is being transpiled to standard object literal notation.

like image 153
rgbchris Avatar answered Sep 26 '22 12:09

rgbchris