Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'&&' operator in Javascript vs in Java

I am currently reading JavaScript from JavaScript: The Definitive Guide. On page 76, there is this statement written,

o && o.x // => 1: o is truthy, so return value of o.x

Being a Java programmer I want to ask, why is it returning 1 instead of 'true' In Java this was not the case, but anyway I know JavaScript is different but the Logical AND mechanism is the same everywhere.(In C it returns 1 as true.)

I am asking is, why does it makes sense for this behavior at all?
Is there any way, I can ensure to return only the true or false values?

like image 956
Manish Kumar Sharma Avatar asked Jun 11 '15 05:06

Manish Kumar Sharma


5 Answers

As per the Spec for Binary Logical Operators

The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.

This is a feature used in javascript a lot, one common use case is to assign a default value to a variable if it is not defined. Like assume you are expecting a options object as a param but is not mandatory so the user may not pass it

function x(options){
    options = options || {};
    //now your can access optionx.a without fearing whether options is undefined
}

You can do something like !!(o && o.x) to always get a true/false

like image 57
Arun P Johny Avatar answered Oct 13 '22 09:10

Arun P Johny


if we have:

expr1 && expr2

&& Returns 'expr1' if it can be converted to false; otherwise, returns 'expr2'. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

So if we have:

Var xyz = a && b; //where a is undefined(false) and b is 123, then it will allocate undefined.

In case of if statements, these values are specifically converted to boolean.

Refer the following link: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators"

like image 37
Nikhil Batra Avatar answered Oct 13 '22 08:10

Nikhil Batra


You can use Boolean(o && o.x); to get true or false

like image 35
Jens Avatar answered Oct 13 '22 08:10

Jens


It's returning the value of the right operand. If the value of o.x was true, it would return true. If the value of o.x was 'banana', it would return 'banana'.

var o = {x:true};
console.log(o && o.x);
like image 45
Bitwise Creative Avatar answered Oct 13 '22 07:10

Bitwise Creative


Technically && operator implemented to return the first operand if it's value is not zero, and returns the second operand otherwise in a lot of languages including Java, C/C++, Javascript, Perl... While most of the languages accepts any type of operands, Java forces you to use boolean operands so it always returns true or false. In order to force a boolean result in Javascript use:

Boolean(a && b)
like image 1
regulus Avatar answered Oct 13 '22 07:10

regulus