Binary variables can be created using JavaScript (see How to Use JavaScript for an introduction to creating variables using JavaScript).

## Simple Syntax

The following code computes a value of 1 if the observation has a value of 1 for any of the three input variables:

if (d1 == 1 || d2 == 1 || d3 == 1) 1; else 0

whereas this code computes a value of 1 if the observation has given a value of 1 for all of the input variables:

if (d1 == 1 && d2 == 1 && d3 == 1) 1; else 0

See JavaScript Tips if you are surprised by the use of `==`, `||,` and `&&` or are unclear about how this may relate to more complicated examples.

## Shorter Syntax

People new to JavaScript are a little surprised by these expressions, as they often think it would be better if the symbols were not repeated (e.g., writing `d1 = 1 & d2 = 1` instead of `d1 == 1 && d2 == 1`). There are good-but-technical reasons why JavaScript does not work this way (e.g., `=` is used to create variables: see Writing ‘Real’ Code. However, there are a number of ways to make the code much shorter if that is desired. There is no need for an *if statement* as any logical expression in JavaScript is automatically evaluated as a 1 or 0, and thus we can write:

d1 == 1 && d2 == 1 && d3 == 1

and, if we know that the input variables are themselves binary, only taking values of 1 and 0 (and with no missing values), we could just write:

d1 && d2 && d3

or

d1 * d2 * d3

## Comments

0 comments

Please sign in to leave a comment.