JavaScript OR Assignment Operator

In JavaScript, there may be times when you want to assign one variable to a non-null value. The JavaScript OR assignment operator can be used to quickly assign the value of a variable to one of two options based on one value and if it is null or undefined.

The below code shows a function called ‘getNotNull’ which takes two parameters ‘a’ and ‘b’. If the value of ‘a’ is defined and isn’t null, it is returned, otherwise, the variable ‘b’ is returned. This doesn’t prevent a null value being returned though, as if both ‘a’ and ‘b’ are null then the value of ‘b’ will be returned and therefore a null value will be returned.

A ternary operator can also be used to the same effect. In the below code a ternary operator is used to set the value of the variable ‘result’ to either the value of ‘a’ if it defined and not null otherwise it will be set to the value ‘b’. Again, this does not prevent a null value if both variables are null or undefined.

The JavaScript OR assignment operator is represented with two pipe ‘|’ symbols. This can be used to achieve the same effect as the above two code snippets. The value of the ‘result’ variable will be assigned to the value of ‘a’ if it is defined or not null otherwise it will be assigned to the value of ‘b’.

The OR assignment operator does not need to be used with variables, it can be used with raw values too. The below code snippet shows using the OR operator to set the value of the ‘result’ variable uses raw values, ‘null’ or the number ‘2’. The value of the ‘result’ variable will be 2 as the left side of the OR assignment operator is null.

The OR assignment operator can be used to assign the value of one variable to either one or another value based on if the first value is null or undefined. Using the OR assignment operator does not prevent the variable from being assigned a null or undefined value, if both sides of the OR assignment operator are null then the resulting value will also be null.

One thought to “JavaScript OR Assignment Operator”

Leave a Reply