Javascript Interview Question
Today I came across an interesting interview question in javascript.
function testOk(abcd){
return abcd && "ok" ||"not ok";
}
Will this work? What will be the output?
testOk(65)
>>"ok"
testOk(0)
>>"not ok"
testOk("a")
>>"ok"
testOk(true)
>>"ok"
testOk(false)
>>"not ok"
So abcd && "ok" || "not ok"; is equivalent to abcd ? "ok" : "not ok";
The trick here is for &&, it should verify both sides and for ||, it is not required all the time. For || operator, if left part is true, it is not required to process right part.
var abcd = 10;
abcd == 10 && doSomething(); // is the same thing as if (abcd == 10) doSomething();
abcd == 5 || doSomething(); // is the same thing as if (abcd != 5) doSomething();