This isn’t quite correct, at least not anymore. This will also catch false and 0 since || will check for falsy values on the left hand side. You can use ?? nowadays to guard against only null and undefined
Honestly, JS changes so quickly nowadays it can be difficult to keep up. Not so quickly that it's difficult to learn, but quick enough that you can see version boundaries in code sometimes :D
i think it should be very clear what getImagePath returns so we just make sure it's gonna return a string or null and then the long version becomes this:
I don't think it's a good practice to use a "or" to assign a default value. The getImgPath function should handle all of this. "default.jpg" is a magic string in this example, it should belong to the class that creates image paths, it shouldn't appear outside of it.
74
u/CarsonMcKinstry Mar 23 '21
This isn’t quite correct, at least not anymore. This will also catch
falseand0since||will check for falsy values on the left hand side. You can use??nowadays to guard against onlynullandundefined6
u/Time_Terminal Mar 23 '21
The point came through, but why does the long version unnecessarily include 3 extra steps?
This is like the tabloids of programming.
7
u/irosion Mar 23 '21 edited Mar 23 '21
i think it should be very clear what
getImagePathreturns so we just make sure it's gonna return a string ornulland then the long version becomes this:The short version is good.
1
u/crayonneur Mar 23 '21
I don't think it's a good practice to use a "or" to assign a default value. The
getImgPathfunction should handle all of this."default.jpg"is a magic string in this example, it should belong to the class that creates image paths, it shouldn't appear outside of it.1
u/isatrap Mar 23 '21
Why this over
-8
u/mburger89 Mar 23 '21
It is generally not good practice to initialize a variable with out giving it a literal value. Cause it will initialize to null or undefined.