Andrew Young
Andrew Young

Reputation: 1779

Can somebody explain to me what && does when used with calling a function?

Please explain what this is doing with regards to calling a function and using the && operator.

callback(data && data.length > 1 && JSON.parse(data));

Also, which value actually gets passed to the function?

Upvotes: 1

Views: 761

Answers (5)

Michael Petrotta
Michael Petrotta

Reputation: 60902

&& is the short-circuiting logical "AND" operator. Short-circuiting means that the next component of the expression will be evaluated only if the previous resolves to true. So, data.length > 1 will not be evaluated unless data is true, and JSON.parse(data) will not be evaluated unless data.length resolves to true.

In the end, a boolean value is passed to the method callback() - true if all three components are true:

  • data
  • data.length > 1
  • JSON.parse(data))

...and false otherwise.

Upvotes: -1

luiscab
luiscab

Reputation: 11

&& can be used to evaluate multiple statements at once. && can be thought of as "and".

So, true && false; evaluates to false.

In JavaScript, && returns the first operand if the first operand is falsy. If the first operand is truthy, it returns the second operand.

Upvotes: 0

Umesh Patil
Umesh Patil

Reputation: 10685

As per me here, only boolean variable will be passed (true/false)

  1. data: checks if data is present or null
  2. data.length>1 Does the length is more than one. At least two elements should be present in data.
  3. return value of JSON.parse(data) It can be either true or false.

It will be much clear, when you come to know what callback accepts exactly.

Upvotes: 0

nmjohn
nmjohn

Reputation: 1432

I'm guessing callback takes a boolean or an int value.

&& is a logical and operator, so it's determining if data is non zero AND data.length is greater than one AND JSON.parse(data) returns non zero, then the expression will result in a 1 or true being passed to callback. If any of those parameters are not met, then it will pass 0 or false.

Upvotes: 2

WordsWorth
WordsWorth

Reputation: 872

It is a way to say if data is true(not null) and its length is > 1 then call JSON.parse(data). If first expression is true then only second expression is evaluated and so on. Its equivalent to

if(data)

if(data.length > 1)

callback(JSON.parse(data));

Upvotes: 3

Related Questions