Search code examples
javascripthtmllogicoperators

Why JavaScript ignores the HTML <br/> label when trying to concatenate it with the result of the operator OR?


Sorry for the question, I wasn't sure how to ask it. Basically I'm practicing JavaScript using logic operators. I have a really simple HTML code:

<body> <script src="logic_operators.js"></script> </body>

The file "logic_operators.js" has the next lines of code:

let value1 = true;
let value2 = false;

document.write(value1 && value2 + '<br/>');
document.write(value1 || value2 + '<br/>');
document.write(!value1 + '<br/>');
document.write(!value2 + '<br/>');

Basically, each document.write() sentence writes the result of each logic operant with a new line.

It works for each sentence except for the OR ( || ) one, it doesn't print the new line. I get the next result:

false
truefalse
true

I need to enclose the OR operation using parenthesis for the sentence to work:

document.write((value1 || value2) + '<br/>');

Why is that? I'm new to JavaScript and can't really figure this out.


Solution

  • + has higher operator precedence than ||. Specifically, + has 14 and || has 6. So, the + operation is done first, when there aren't parentheses grouping the three operators.

    document.write(value1 || value2 + '<br/>');
    

    is

    document.write(value1 || (value2 + '<br/>')
    

    resulting in

    document.write(true || (false + '<br/>')
    
    document.write(true)
    

    The && also has lower precedence than +. && evaluates to the last operand if the first is truthy. So

    document.write(value1 && value2 + '<br/>');
    
    document.write(true && false + '<br/>');
    
    document.write(true && (false + '<br/>'));
    
    document.write(false + '<br/>');
    

    So it happens to produce the newline like you want for these particular values of value1 and value2.

    While you can avoid this problem by using parentheses, or by using writeln instead, it would be much, much better to avoid document.write completely.