Take the 2-minute tour ×

The following code is from 'JavaScript by Example Second Edition' EXAMPLE 15.24
I don't understand the code var evt = e || window.event; //Browser differences
I think the var evt should be true or false, so evt.target should be null, right?

function colorText(e){
  var evt = e || window.event; //Browser differences
  var evtTarget= evt.target || evt.srcElement;
else if(evtTarget.id == "second"){
else{ div3.className="green";}
share|improve this question
possible duplicate of Do the && and || operators convert their operands to booleans? –  Bergi Jul 19 '13 at 17:46

5 Answers 5

up vote 1 down vote accepted

The keyword expression returns the value of the first expression operand if it's not null falsey, otherwise the value of the second.

Javascript is weak typed, so you can always use || as a boolean, because everything which isn't false or null evaluates to true. But it's actually returning the value here, s. So evt becomes either e (the argument) or if e doesn't exist has a falsey value, it becomes window.event.

share|improve this answer

All of the answers so far are technically true. The full story:

The || operator returns the value of the first operand if the result of casting it to a boolean value is truthy. Otherwise, it returns the value of the second operand. ES5 Spec

Many different values are "falsy", including null and undefined. Nailing down exactly what falsy is can be tricky, but you can count on those, which is useful for catching variables and properties that may not be present in different browsers. If you want to check for an undefined variable yourself, though, it's usually best to use typeof instead.

share|improve this answer

If e is not set, meaning you did not call the function with a parameter, then evt will be window.event. If e is set, then evt will be whatever e is.

There's a concept known as short circuit evaluation and that means if the condition is met without fully evaluating it, then it doesn't need to fully evaluate it. That is the case here. If e is set, you don't care what window.event is, because you already have something you can set evt to.

share|improve this answer
Question: How did you get that codeblock formatting to be inline with the rest of your sentence? Also, what is the syntax for codeblock formatting text to look like a command? –  L0j1k Sep 27 '12 at 2:02
Wrap the text in a backtick `. Check editing help for more info. –  sachleen Sep 27 '12 at 2:03

No, in JavaScript || does not cast to boolean, instead it short-circuits to which ever value (from left to right) first evaluates as truthy.

It preserves the expression's evaluation.

share|improve this answer
var evt = e || window.event;

This line sets the variable evt to e if e is not empty. Otherwise (if e is null, for example if e was not passed to this function), evt is set to window.event.

share|improve this answer

Your Answer


