r/node • u/wobsoriano • Nov 10 '20
Conditionally call a function with optional chaining.
58
u/dudeitsmason Nov 10 '20
Just because you can, doesn't mean you should
14
u/wobsoriano Nov 10 '20
Of course 👍 This is just another way of doing it.
-20
u/OmgImAlexis Nov 10 '20
This is a worse way of doing it.
11
u/threeys Nov 10 '20
Why is it worse?
1
-6
u/OmgImAlexis Nov 10 '20 edited Nov 10 '20
It’s harder to read the intent and doesn’t add anything helpful for the few chars it saves.
4
u/burnblue Nov 10 '20
Is it still a few characters when the function is deep?.inside?.an?.object?.()
2
u/ikeif Nov 10 '20
This is when I pulled it into a project.
Large JSON objects, so it was either constantly making shorthand assignments or being able to concisely do it this way.
People get so hung up on an option in a toolset. It’s not for every project, but some projects, it’s a good tool.
6
u/threeys Nov 10 '20
I think one could make the case it adds value by reducing the need to repeat the same name twice, thus reducing the potential for errors.
I'm not sure it's worth it given how nontraditional it is, and I think JS devs typically do not think of functions as objects as it is being used here, but still it's an interesting approach
1
u/inabahare Nov 10 '20
Its not as nontraditional when you consider its literally just the elvis operator but applied to function calls. Like it doesnt really so anything surprising
-4
u/OmgImAlexis Nov 10 '20
What errors? If you’re using a good editor like VS code you shouldn’t have any issues guessing here.
if(typeof myFunction === ‘function’)
This reads better than what the OP shows. Without needing to know anything else I can read that it’s checking it’s a function. The ?. doesn’t.
The only time I can see it being a benefit is when you’re using a ternary operator to set something inline.
5
u/threeys Nov 10 '20
this example is a bit contrived:
const funcA = () => true; const funcB = () => false; const value = funcA && funcA();I could accidentally change it to
const value = funcA && funcB();and intellisense would be none the wiser.
This specific scenario isn't all that convincing, but IMO in general it's safer to be more expressive with less repetition than not, because it reduces the opportunity for subtle errors in the future.
6
u/recycled_ideas Nov 10 '20
The Elvis operator on a function says "if this exists, call it", just like when you use it to get a property of an object that might be null or undefined.
Just because the operator is unfamiliar to you, doesn't mean it's bad. It just means that it's unfamiliar.
if(typeof myFunction === ‘function’)
Is significantly longer and says exactly the same thing.
Again, unfamiliar doesn't mean bad.
1
u/RufusThreepwood Nov 10 '20
Optional chaining is not quite the same as the Elvis operator.
1
u/recycled_ideas Nov 10 '20
It checks if the left hand side is null or undefined and the runs the right hand side.
There's no difference between a function call and a property access.
→ More replies (0)-7
u/OmgImAlexis Nov 10 '20
No. I’m not “unfamiliar” with it. It’s been in typescript for quite some time now. I actively disallow it.
Just use an if and test the access properly.
8
u/recycled_ideas Nov 10 '20
Of course you're unfamiliar with it, because when you look at it, it's not clear.
That's on you, because the meaning is explicit.
→ More replies (0)6
u/dertrommler06 Nov 10 '20
Why fight language improvements? Do you disallow spread because you’re used to Object.assign? Or mutate vars inside for loops instead of Array.map? I assure you if you use optional chaining you’ll find it reads far easier especially when accessing deeply nested properties on objects. 4 props or more deep is pretty hideous with &&
1
7
u/nickbreaton Nov 10 '20
In think case, why not do this if you’re in an environment that supports it? If this was in the language all along, I imagine it would be the established way for doing this.
4
u/conventionalWisdumb Nov 10 '20
Agreed. Ruby has a similar operator and the issues others have raised here never come up.
0
Nov 10 '20
[deleted]
14
u/dudeitsmason Nov 10 '20
I agree, optional chaining rocks, but there's something unsettling about using it between a function variable and it's invocation I guess?
1
u/KyleG Nov 10 '20
learn about functional optics and start using those instead! Just say no to null.
0
u/Not_Sugden Nov 10 '20 edited Nov 10 '20
it really depends on the use case for me, but i rarely run into situations where an the chaining would look more logical than chaining x && x.y
like uh
const bool = x && x.y ? x.y : false;
const bool = x && x.y ? x.y === 'smth' : false;rather than
const bool = x?.y || false;
const bool = x?.y === 'smth'the 2nd example here is a better one, what use is it comparing
undefinedto a string, using a tenary w/ && would be more logical there no?edit: this has no relevance but i just wanted to say
you could also do
const bool = Boolean(x) && (x.y === 'smth');5
84
u/anon774 Nov 10 '20
People are hating on this approach, but IMO the only reason people think this is bad or shows "unclear intent" is because it's new and they're unfamiliar with it.
It's extremely clear what this means, I don't know how you could get confused by this if you saw it in the code. Nobody has provided an example showing how this could be unclear.
8
Nov 10 '20
Its weird what the use case is for this. I am having a hard time trying to think when i needed to know if a method exists. I might just be too used to working in typed languages now.
However, language features aren't usually inherently bad. Just don't use if you don't like it, duh.
40
u/anon774 Nov 10 '20
I guess a basic example would be something like an optional callback:
function doSomething(payload, callback) { console.log('Pretend we did something with payload'); callback?.(); // or callback && callback(); // or if (typeof callback === 'function') callback(); }-2
Nov 10 '20
Even with the explanation and this example, I just don't understand.
I know if there is a callback or not. I use the function because I know what the function does, the parameter syntax, including whether or not it has a callback, and what the callback does. When do you not know if there is a callback to a function? Isn't that what reading the documentation is for?
9
u/N074R0807 Nov 10 '20
Following this specific example, you can have a function that accepts an optional callback function as an argument. The term optional is key here. In that function's implementation you have to check whether a callback function was supplied or not, so you can either invoke it or skip it.
Example:
// definition/implementation function updateUserStats(userInfo, callback) { // do something with userInfo // after doing that, the code will check is there's a callback to invoke if (typeof callback === 'function') { callback(); } } // now, using it in two different ways // without using the optional callback const user1 = { name: 'John', age: 32 } updateUserStats(user1); // using the optional callback const user2 = { name: 'Jill', age: 35 } function notifyUserUpdated() { alert('User stats was updated successfully') } updateUserStats(user2, notifyUserUpdated);1
Nov 10 '20
That makes more sense. Thank you.
1
u/N074R0807 Nov 10 '20
No problem! I guess what confused you is the fact that you were thinking in terms of using a pre-existing function not implementing your own.
4
u/gigastack Nov 10 '20
A library might implement a function with an optional callback. In that case, you don't know if a callback exists until runtime.
0
u/xroalx Nov 10 '20
Even in typed languages, e.g. C#, you can have a delegate for an event that might or might not be set. You can use the
.?syntax to safely invoke the delegate if it exists, no need forif (delegate != null) { /* invoke */ }.17
Nov 10 '20
[removed] — view removed comment
3
u/VolperCoding Nov 10 '20
Languages like C++ don't have optionals because they're low level-ish. Typescript is a superset of Javascript so if course it has to feature hull and undefined
6
u/notAnotherJSDev Nov 10 '20
Rust is also in that C++ class of languages and it also has optionals?
-6
3
Nov 10 '20
Scala and every other FP language does too. Optionals are just an abstraction on top of null pointers, you can reason about them and handle them in a more elegant way. There's nothing 'basic' about this. Java has them in the more recent versions too.
Rather than null-pointer checks everywhere, you have some really nice syntax to deal with it, and it's a lot more transparent in the code.
1
Nov 10 '20
You probably (?) wouldn't model it as
Maybe fthough. Instead you'd just require afand at the call site either provide a proper function or a noop.1
Nov 10 '20
Yeah, tbh I find the use case in the OP a bit odd, was more talking about options in a general sense.
1
u/Qildain Nov 10 '20
The billion dollar mistake... as a (primarily) JVM language dev, I abhor null checks. I'm glad they pulled it into vanilla.
1
u/johannes1234 Nov 10 '20
C++ ist lowlevel-ish. Template meta programming is more high-level than what is being done with JavaScript. It however targets to be fun at the "machine level".
Such features as mentioned here are in the pipeline for C++, C++ however is slow to take something in the core language and it's expected that a library level solution will come first. (And in fact there are already different library implementations allowing such chaining, bringing it in standard makes it interoperable)
1
u/HappinessFactory Nov 10 '20
It's definitely as clear as the alternative that was provided. But as a junior
if(cb){ cb(); }Makes a hell of a lot more sense.
I use turnarys and other shortcuts like the rest of y'all but I still thing if statements are the king of readability.
4
Nov 10 '20
Hard disagree, it's only more readable if your definition of readability is pinned to that of a beginner. As we become more knowledgeable our idea of readability should move with us.
Take this for example, beginners often don't know about ternaries:
const x = a ? b : c;The more "readable" approach as you put it would be like this:
let x; if (a) { x = b; else { x = c; }Not only is this noisier and harder to parse for anyone more experienced but it's also opened up the need to track the mutability of the variable reference that didn't exist with the ternary approach.
1
u/HappinessFactory Nov 10 '20
I was goin with that if statements read more like english.
Shifting everything into one line does shorten things. And those of us that know what a turnarys does can read it faster.
But it's not more "readable" if that makes sense.
Kinda like object parsing:
const getDataFromObj = ({data}) => data;Is quick and easy and those of us who know how it works understand how useless of a getter it is
Buuuuuut, I would argue this is more readable
var getDataFromObj = function(obj){ return obj.data; }I'm writing this on my phone so I apologize for the formatting.
Anyways, the point is while shortcuts are nice and convenient it does come at a cost of readability and we do have to be aware of that.
Youre not wrong, it is noisier, but it still closer to english which is the goal of readability.
To be clear even as a junior I understand the benefits of using these newish techniques and I implement them myself.
But they're not more readable. That's just false. It's like saying Moby Dick is more readable than see spot run. Yes it's a better book but, it's substantially harder to read.
1
Nov 10 '20
It's more readable in code which is a distinct type of language. Your second code snippet there isn't more readable, it merely has more words in it. Is that all that matters? Would you prefer
add(1, 2)over1 + 2for this reason?If you're keen for traditional language-esque readability then you ought to try Haskell, which ironically demonstrates extremely well that programming is closer to mathematics than anything else. That we currently can best express it linguistically is an irrelevance.
1
u/HappinessFactory Nov 10 '20
We clearly have different definitions of readability. I suppose this means we will just have to agree to disagree.
You do make strong points though. I agree with everything aside from code being its own distinct language. To me it is still very much english.
Like how I prefer using
.forEachinstead of you're old school for loop. It's closer to english.I haven't tried Haskell as a front end dev I am very much in js land for better or for worse. ( I like js and TS a lot tbh)
2
Nov 10 '20
I respect your perspective. One of the nicer things about Haskell is that sometimes the code comes together like this:
andFinallyThis . andSomethingElse . doAThingHopefully we'll see something similar if TC39 approves the pipeline operator proposal.The trouble is that if you optimise for linguistic familiarity above all else you sacrifice other really important properties, properties that inherently exist because programming is, or at least can and in my view should be, a logical venture.
Taking
forEachas an example, if you were to use this for mapping an array, you'd have a program that's harder to quickly parse (again, for anyone other than a beginner), and crucially the logic of the program would be harder to follow. See:const nums = [1, 2, 3]; const strs = []; nums.forEach((num) => { strs.push(String(num)); });We have to keep track of the mutability of
strs(in practice, in a functional codebase, you considerconstto mean truly immutable). We have to track the iteration overnumsand ensure we're not doing anything different in some loops.On the other hand,
Array.prototype.map:const nums = [1, 2, 3]; const strs = nums.map(String);Functor mapping implies a pure function, so when you read this code you know beyond all reasonable doubt that it will map an array given the provided function and that's it. No changes to
nums, and a predictable value atstrs. This is an enormous benefit to readability that can only be realised if you're willing to raise your definition of readability vis a vis the lowest common denominator.1
u/SnerkDRabbledauber Nov 10 '20
As we become more knowledgeable our idea of readability should move with us.
Sounds like you don't have a clear grasp of the term "readability". The goal is to avoid confusion and make the meaning clear to the widest levels of skill you can while still making it fast to scan for all levels.
1
Nov 10 '20
It's slower to scan for all but beginners. You must pick a lane.
And you likewise must define a bottom end to your skill gradient, else you couldn't even use
letorconstlest an absolute beginner not know of them. Or functions for that matter, beginners mightn't have gotten that far yet!1
u/lukashavrlant Dec 03 '20
The mutability can be easily avoided but introducing a function with an appropriate name.
function fun() { if (a) { return b; } else { return c; } } const x = fun();This is 100 % readable by anyone. And as you can't be sure everyone reading the code is on the same level as you, you should always prefer the version that is more readable by more people.
1
u/backtickbot Dec 03 '20
Hello, lukashavrlant: code blocks using backticks (```) don't work on all versions of Reddit!
Some users see this / this instead.
To fix this, indent every line with 4 spaces instead. It's a bit annoying, but then your code blocks are properly formatted for everyone.
An easy way to do this is to use the code-block button in the editor. If it's not working, try switching to the fancy-pants editor and back again.
Comment with formatting fixed for old.reddit.com users
You can opt out by replying with backtickopt6 to this comment.
1
Dec 03 '20
This is objectively less readable. A beginner would be confused why you're doing this instead of using mutability, and I'd be confused as to why you didn't just use a ternary.
1
u/lukashavrlant Dec 05 '20
Everyone who has ever written some code in any language possible, including Excel or Matlab, would understand it. While not everyone understand a ternary operator.
The only way you can make is less readable is if you are bad at naming functions and if you choose a wrong name for the function "fun". Be aware that the function can be a private method, you can move the function somewhere else or whatever. The point isn't there is a function just before the assignment. The point is you extract the code to the named function and then you can place the function anywhere else because it just became an implementation detail.
1
Dec 05 '20
Understandability and readability are not synonymous. In this case you're optimising for the former at the expense of the latter.
I'm generally a fan of small functions as I lean heavily towards FP, but for something that can be viably solved by a ternary you're likely adding needless indirection.
1
u/lukashavrlant Dec 06 '20
I think it's both: more readable and more understandable. Because if you name the function right, you don't need to read the implementation at all.
maximum(a, b)is more readable and more understandable thana > b ? a : b.1
Dec 06 '20
If you go far enough down that rabbit hole you'll find yourself needing sum types, something well beyond the understanding of your average beginner.
0
u/marcus_cemes Nov 10 '20
I don't think this is new and unfamiliar, it's simple to understand, but it is not expressive trying to read and understand somebody else's code, I prefer a more verbose but descriptive syntax. Logical statements should be used for computing logic, not control flow, even if it's possible to do so.
if (typeof result.data === "function") { result.data(options); } result.data?.(options);In my opinion, the first example is clear. See whether it's a function, execute it. The second is less clear, it requires more cognitive load to determine whether it's the ternary operator, optional chaining, a logical statement with an expression in brackets, property access (dot with weird brackets for property access), which makes it even more confusing to newcomers of the language, with JavaScript is no stranger to.
2
u/H-s-O Nov 10 '20
Also, the second one will throw if
datais not a function. This needs to be considered if building a module exposing a public function that receives the callback as an argument.
26
Nov 10 '20
I think the latter solution is very readable and clear. This will be a very useful feature in React.
4
u/Guisseppi Nov 10 '20
Node has to wait for the V8 implementation, you can add this babel plugin and use it on the frontend now: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
3
5
u/trenskow Nov 10 '20
As both a JS, Swift and C# developer I find it so nice this feature is finally coming to JS.
4
u/bonerjams99 Nov 10 '20
I like this for certain situations, like if I have a function with an optional “onEvent” method parameter. Plus it’s a common eslint rule (used by my company at least) to not allow comparisons without capturing a value like the first line is doing.
4
u/BillyBrighto Nov 10 '20
I'm undecided, I guess it would have it's uses. Maybe it might look better without the . as it kind seems like you're accessing something on the function.
myFunction?()1
1
u/FunkyFreshFarming Nov 10 '20
Can someone help ELI5 for a jr developer?
4
u/wobsoriano Nov 10 '20
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
The optional chaining ‘?.’ is an error-proof way to access nested object properties, even if an intermediate property doesn’t exist.
const user = {}; // error: Uncaught TypeError: Cannot read property 'first' of undefined console.log(user.name.first) // ok, but returns undefined console.log(user?.name?.first)2
u/FunkyFreshFarming Nov 10 '20
Okay that helps me understand how it works, thank you for the link. I still don't understand why we would want to use this however.
2
u/KyleG Nov 10 '20
It's a hacky way, with a dynamically-typed language, to write terser code with potential null values. It doesn't really solve the problem of programmers forgetting to check for nullity, since there's nothing stopping a programmer from forgetting to use
?there.1
u/TheMetalFleece Nov 10 '20
Yep. This is why I always enable "strictNullChecks" (or "strict" in general) on every typescript project. You get an "object may be undefined" error and it doesn't compile.
1
u/donner9 Nov 10 '20
interesting... is it just for typescript, right?
1
u/TheMetalFleece Nov 10 '20
Yeah. You can see more info here (along with other "strict" checks). I'ts game-changing https://www.typescriptlang.org/tsconfig#strictNullChecks
1
u/noXi0uz Nov 10 '20
there is though. Typescript and your IDE will show an error that the value you are trying to access may be undefined, forcing you to either use optional chaining or another form of null check
1
u/Not_Sugden Nov 10 '20
its mainly just clearer for specific use cases, but idk i dont find it all that useful, i've only used it like once
1
2
2
u/nevatalysa Nov 10 '20
Not a personal fan of it, as this would make it seem as if the object has a property that's the actual call (yes i know of Function.call()), which without the name seems off. If it was actually myFunc?.call(), which would optionally call the function (basically the example, just with an actual property name) I wouldn't see this as off-putting.
2
u/JonathanTheZero Nov 10 '20
It sure looks a bit weird but you just need to get used to it.. it's pretty nice actually
0
u/bitsandbytez Nov 10 '20 edited Nov 10 '20
You know I was so excited about this when I first heard about it, but then I started using it and I just don’t like it. I get the extreme use case but if anything it just confusing future developers.
Edit: downvoted for a POV?
1
3
u/KyleG Nov 10 '20
I think you'll get used to it, and future devs will have no problem with it. It's a standard feature in Kotlin and I think C#, and no one ever has a problem with it there.
2
u/RufusThreepwood Nov 10 '20
It's arguably confusing to past/current developers. Future developers will know and love optional chaining.
1
1
u/Not_Sugden Nov 10 '20
the 2nd approach looks more funky, personally i'd do
if (typeof myFunction === 'function') myFunction();
1
1
1
u/oguz279 Nov 10 '20
I prefer typeof fn === "function" && fn() as it covers cases where fn would have a truthy value but not be a function.
9
u/8lbIceBag Nov 10 '20
If you're getting even the type completely wrong something is broken.
1
u/LucasCarioca Nov 10 '20
I agree. Seems like something is being used incorrectly further up the chain.
10
u/oguz279 Nov 10 '20
Yep. And that's why kids, always use Typescript ❤️
2
u/LucasCarioca Nov 10 '20
Typescript is wonderful for preventing this ugly code
1
u/Miridius Nov 10 '20
Typescript doesn't add runtime type checks, you still have to do that yourself if you're accepting multiple types (in this case function | undefined). So no.
1
u/LucasCarioca Nov 10 '20
Which is something that should be avoided. And if you can’t avoid it then you should use an optional. Which would clearly solve that typeof mess that I was referring to. So yes.
0
u/Miridius Nov 10 '20
If you're talking about optional as in just using the "?." operator as OP showed then yes I agree with you.
But typescript won't stop there from ever being a truthy value where you expect a function because the value can come from outside your codebase in a place with missing, vague, or incorrect types - when you use a library or someone else uses your library
1
u/LucasCarioca Nov 10 '20
Dude look at the start of this thread... I’m replying to that piece of code....
1
u/Not_Sugden Nov 10 '20
unless you used a type of filter callback, and instead allowed just an object / string to be passed in?
interface OptionsForSomething { filter: ((x: string) => boolean) | string; }1
u/8lbIceBag Nov 10 '20
In this case, it'd be totally useless because nothing is being passed to the function. No
thisor argument. Which implies its scope andthisare already bound. If you had a filter string, what would it be filtering against? There's no context.For your scenario to be valid, the parent comment needed to be something like:
typeof fn === "function" && fn.call(ctx)ortypeof fn === "function" && fn(ctx)
1
Nov 10 '20
I often used something like this:
const xs = //something from an api const ys = mapFun ? xs.map(x => mapFun(x)) : xs;
where mapFun is passed as an argument but it maybe not passed at all
-8
-11
-1
15
u/wobsoriano Nov 10 '20 edited Nov 10 '20
Some use case
A function as a prop in a React component
A callback function
Edit:
Yes, an if statement would be better and readable but if you check my post, it's not an if statement I'm comparing it to.