0
votes

I am learning JavaScript and going through the JavaScript: The Complete Reference, Third Edition 2012. Considering the abstract from the same book.

Like many languages, JavaScript short circuits the evaluation of a logical AND (&&) or logical OR (||) expression once the interpreter has enough information to infer the result. For example, if the first expression of an || operation is true, there really is no point in evaluating the rest of the expression, since the entire expression will evaluate to true, regardless of the other value. Similarly, if the first expression of an && operation evaluates to false, there is no need to continue evaluation of the right-hand operand since the entire expression will always be false. The script here demonstrates the effect of short-circuit evaluation:

    var x = 5, y = 10;

    // The interpreter evaluates both expressions
    if ( (x >>= 5)  &&  (y++ == 10) )
        document.write("The y++ subexpression evaluated so y is " + y);

    // The first subexpression is false, so the y++ is never executed
    if ( (x << 5) && (y++ == 11) )
        alert("The if is false, so this isn't executed. ");

    document.write("The value of y is still " + y);

My O/P gets reflected as :

The value of y is still 10

whereas that of author's as:

The y++ subexpression evaluated so y is 11
The value of y is still 11

I see that this expression doesn't gets executed:

if ( (x >>= 5)  &&  (y++ == 10) )

I see the red line drawn under the second '&' in the above expression in Eclipse IDE with this:

The entity name must immediately follow the '&' in the entity reference.

What is the reason behind this?

1

1 Answers

2
votes

x is 5 which is binary 101, (x >>= 5) is therefore zero, x is assigned zero, and y++ in the first statement is not executed.

(x << 5) is likewise zero since x is now zero, so the y++ in the second statement also does not execute. The value of y remains 10, since no y++ is executed.

I don't know where your author is getting y == 11 from, it's wrong.

The IDE error is a red herring - it does not understand your file contains javascript (or you delimiited the javascript incorrectly) and is trying to parse it as XML / HTML.