1. Technology

JavaScript Making Decisions

3. Assigning Boolean Values


Assigning the result of a Boolean calculation into a variable is no different than assigning the result of number calculations or text string joins.

The following are examples of assigning the results of comparisons into new or existing Boolean variables.

1 var timeToEat = me === hungry;
2 var affordable = price < budget;
3 passed = mark >= pass;

Assigning the results of a comparison to a Boolean variable

1 Creates a new Boolean variable timeToEat that will be true if and only if the current values in me and hungry are both the same data type and value, otherwise it will be false

2 Creates a new Boolean variable affordable that will be true if the value in price is less than the value in budget.

3 updates the existing variable pass (or creates a new global variable if it doesn't) that contains true if the value in mark and pass are equal or the value in mark is greater than the value in pass

You only need to assign the result of a comparison to a Boolean variable like this when you need to test that result in multiple places in your code. Where the result of the comparison is only needed once it is more common to test the comparison itself, rather than assigning it to a variable first.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 2. Decision Making
  7. JavaScript Assigning Boolean Values

©2014 About.com. All rights reserved.