Why | and || are similar to a semicolon in Javascript?

Viewed 105

I was testing some stuff on Console on Chrome and then I ran that piece of code:

alert() | window.confirm();
alert() || window.confirm();

My problem was to run both alert and confirm methods in a single line without using semicolon. It turns out that both | and || worked and I can't imagine why it worked, firstly because || means an OR operator which should run one of them not both and secondly | I don't know what it is. Can someone explain what happened and what else should work instead of ;?

3 Answers

A semicolon indicates the end of a statement.

If you aren't already aware, an expression is something which evaluates to a value. For example, 5, 'foobar', and myFn() are all expressions, because they evaluate to values.

Statements can be composed of multiple expressions. For example, const result = fn('foo') passes the 'foo' expression into the function call, and the function call returns a value which is assigned to result.

In your code, both lines are composed of two expressions, but each line happens to be a single statement. With this line:

alert() || window.confirm()

will first evaluate alert. Since alert returns undefined, the || operator then evaluates the expression on the right, which is window.confirm().

You can put multiple expressions together on the same by using operators like |, ||, or =. You can also evaluate multiple expressions by putting each as a separate statement, like

alert();
window.confirm();

Both will result in an alert box and a confirm dialog coming up.

The || is an operator, like + or /; it calculates something. In the case of ||, it calculates whether one OR the other value is true.

Normally, you'd use that in something like an if statement: if (i===0 || j===0) {...} but it's not restricted to that; for instance, you could put the result in a variable, then use it in an if statement later: have_zero = i===0 || j===0; ...; if (have_zero) {...}

The || (and &&) operators do have one special thing: if the left side determines the answer, they don't bother calculating the right side (called "short-circuit evaluation").

Here, you're calculating alert() || window.confirm(), so it calls alert(); as others have noted, this returns undefined which doesn't determine the answer to the ||, so Javascript then calls window.confirm(). The answer is then thrown away, because you're not putting it in a variable or otherwise using it, but that's OK - you wanted to call the methods, you weren't interested in the answer.

Related