0

I'm wondering if there's a shorthand way to write something like this in JavaScript

if (thingExists) {
    thingExists.manipulate
}

I think I remember seeing something along the lines of

thingExists?.manipulate

but that may have been TypeScript or something.

Anyway, any knowledge on that matter is appreciated,

Thanks!

1 Answers1

0

You can use && for short circuiting:

    thingExists && thingExists.manipulate

thingExists.manipulate will be evaluated if and only if thingExists is truthy.

Example:

var obj = { func: function() { console.log("func is called"); } };

obj && obj.func();                        // => func is called 

var falsy = null;

falsy && falsy.imaginaryFunc();           // => nothing
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73