Nulling JavaScript

K - Aug 25 '17 - - Dev Community

Don't you love huge object graphs in JavaScript? Like, when you get some nice data from that JSON API and have to look so deep into it, you just hope it doesn't look back?

Well, more often than not it does and then things get messy and you curse that damn JavaScript for not providing you with better tools and you forget that you just have modeled out that data structure with nice access interfaces in the first place.

Like most of you lazy bums I just love my plain old JavaScript objects and if I wanted the language to help me I would have used a statically typed one anyway, right? ;)

Long time, the solutions (besides really modeling your data) were looong checks or third party libs.

    let myValue = "default";
    if (response && response.body && response.body.somethingElse) {
      myValue = response.body.somethingElse.myValue;
    }

    import _ from "lodash";

    const myValue = _.get(response, "body.somethingElse.myValue", "default");
Enter fullscreen mode Exit fullscreen mode

But, fear no more my fellow JavaScripters, for we will soon conceive the infamous Null Propagation Operator!

What does it do?!

It lets you access the depth of your data without the fear of everything blowing up when that darn back-end dev just changed the structure again.

    const myValue = response?.body?.somethingElse?.myValue || "default";
Enter fullscreen mode Exit fullscreen mode

It will even work with arrays or functions


    const someValueFarAway = myArray?.[993];

    const calculatedIfAvailable = myFunc?.(10);

Enter fullscreen mode Exit fullscreen mode

But when will we have it?!

I have no idea...

At the moment this proposal seems to be Stage-2 and a Babel plugin is in the works.

The question is now, is it a blessing or a curse from the JavaScript gods?

Will it make code more robust with less thinking or will all the silent errors accumulate to silent time bombs under our asses?

Like so often, I just don't know...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player