Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What this code "obj && obj.myFunction();" does in javascript?

I`m working on a project and I saw that at the end of some functions is called a jquery deferred object like this:

obj && obj.resolve();

What is the purpose of the &&? And what is the purpose of the self placed object in the begining (obj) ?

First I thought that calling like that is something like this:

if obj exists --> then call that function (resolve)...but I`ve tested the code with a simple object and it throws an error:

var b = {
    a:function(){alert('ok')}
};

a && a.a(); // ReferenceError: a is not defined

b && b.a(); // works...
like image 822
Gigi Ionel Avatar asked Mar 18 '26 03:03

Gigi Ionel


1 Answers

The code is saying 'if obj is intantiated and is not null, call obj.resolve()'.

It works due to Javascript treating 0, null and undefined as false, and any other value as true.

like image 112
Rory McCrossan Avatar answered Mar 19 '26 15:03

Rory McCrossan