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!

4
  • Can you give a more complete example? How do you want to use such a construct? Is thingExists.manipulate supposed to be a value of a property or a function call? Commented Aug 22, 2018 at 0:04
  • 1
    You can short circuit it with &&. thingExists && thingExists.manipulate, although it's not that readable.
    – Wreigh
    Commented Aug 22, 2018 at 0:06
  • Yes, JS doesn’t have ?. yet. There are proposals for this. Commented Aug 22, 2018 at 0:17
  • @Xufox you mean ?: :) Commented Aug 22, 2018 at 0:18

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.