Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Double Bar "||" bitwise operator? 1

Status
Not open for further replies.

sen5241b

IS-IT--Management
Sep 27, 2007
199
US
I am doing code archeology (digging up someone else's code) and I see the use of two vertical bars in what appears to be a bitwise operator. Can't find any explanation of this on the web and my experiemt below doesn't really explain it all. The code I dug up looks like this:

JavaScript:
answer = (ScriptThatMightReturnTRUE) || (ScriptThatReturnsString);

My experiments:

JavaScript:
<!DOCTYPE html>
<html>
<body>
<p>difference between a single vs double "|"?.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = [u]true | 5[/u];}  [b]// prints 5[/b]
</script>
</body>
</html>


JavaScript:
document.getElementById("demo").innerHTML = [u]false | true[/u];  [b]// prints 1[/b]

document.getElementById("demo").innerHTML = [u]"fred" | false[/u]; [b]// prints 0[/b]

document.getElementById("demo").innerHTML = [u]"fred" | true[/u]; [b]// prints 1[/b]

document.getElementById("demo").innerHTML = [u]true || 5[/u];   [b]// prints true[/b]

document.getElementById("demo").innerHTML = [u]5 || true[/u] ;   [b]// prints 5[/b]

document.getElementById("demo").innerHTML = [u]false || true[/u] ;  [b]// prints true[/b]

document.getElementById("demo").innerHTML = [u]true || false[/u] ;  [b]// prints true[/b]

 
Double pipe is logical OR
Single pipe is bitwise OR

 
Right, but in this example what ends up in the var answer? If left operand is true, answer is assigned boolean true? If left operand is false the string from the right operand is assigned to answer?

JavaScript:
answer = (ScriptThatMightReturnTRUE) || (ScriptThatReturnsString);
 
I found an answer: the right hand operand is evaluated only if the left one is false. So if ScriptThatMightReturnTRUE returns false then the value returned by ScriptThatReturnsString will be get assigned to answer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top