Underscore.js has two methods _.isNull and _.isUndefined which we use a lot in our code and we've also created a mix-in for _.isUndefinedOrNull.
I recently realised that I could easily use javascripts "truthiness" to achieve the same results most of the time so the question is, is that considered bad practice?
What's better?
if(someVariable){...}
or
if(_.isNull(someVariable) || _.isUndefined(someVariable){...}
They both are entirely different.
if (someVariable)
will evaluate to falsy, if someVariable is 0 or false. So it is better to have explicit checks in this case. You might like to check the truth table in this answer which shows when a variable will be evaluated to either truthy or falsy.
I recently realised that I could easily use javascripts "truthiness" to achieve the same results most of the time
If only most of the time, then your solution doesn't work. Use if (someVariable == null) instead to test for either undefined or null.
so the question is, is that considered bad practice?
Not necessarily. If you know that all the possible values for someVariable other than the null/undefined you want to test for are truthy (e.g. objects), then it's fine.
If they can be primitive values, it's usually a mistake except your condition explicitly wants to test for the falsy values of the respective type. In your null-comparison case it would a mistake.
Related
Yes, I realize that "includes()" is not necessarily used for comparison. I also realize this may be a very question. However, in my particular case, I am using it to distinguish whether or not a particular string in an array contains an identifying substring of text. In short, I have two functions that return arrays of size 3. I have the option to stick a blank parameter in one, such as changing:
my2ndFunction("identifying string",1000,true);
to:
my2ndFunction("useless parameter","identifying string",1000,true);
The purpose of this would be to distinguish the two functions (the one above and the other one of 3 arguments) by a check like this:
if(arguments.length == 4){}
else{}
Or, would it be faster to simply leave the arguments at 3, and do this:
if(arguments[0].includes("identifying")){}
else{}
Also, feel free to edit the particular way I asked the question if it is not clear.
I believe that both are okay, and it depends on the use case of your function.
If you are using the first one (==), you test only on the number of your function's parameters and it will work even if your fourth parameter is something else than an "identifying" object.
the thing than will not raise an error if you are passing another type than "identifying".
In the other hand, using includes() will test if your first parameter is an "identifying" object and if you are passing only three parameters it will work !!
It really depends on your use case and you should pay attention to your calls; Else you will loose time to identify why your code is not working.
There is a SonarQube JavaScript Rule (javascript:S2688) which says that the use of a === NaN is a bug because it's always false.
I agree with that but I think to use a !== a instead (this is suggested by SonarQube) is a very bad idea.
It's a funny JavaScript fact but certainly not a "best practice".
What about Number.isNaN(a)? Why is this not the suggested solution? Are there any differences or problems which I've missed?
the use of a === NaN is a bug because it's always false.
This behaviour is not a bug, because it is how NaN has been defined to work. But if you actually used a === NaN in a program then that would be a bug because of the always-false result.
a !== a instead ... is a very bad idea. It's a funny JavaScript fact but certainly not a "best practice".
I disagree with your "certainly". Due to problems with the original global isNaN() function (which I'll explain in a moment), a !== a was, historically the best way to test for NaN. So in fact it is a very common practice to use that technique, and I would expect the vast majority of experienced JavaScript developers to be familiar with it.
NaN is the only value that tests as not equal to itself.
What about isNaN(a)? Why is this not the suggested solution? Are there any differences or problems which I've missed?
The original, global isNaN() function doesn't actually test whether its argument is NaN. Nor does it test if its argument is some other non-numeric value. What it does is first try to convert its argument to a number and then test if the result of that conversion is equal to NaN. This implicit conversion means that, e.g., isNaN("test") returns true even though a string is not equal to the value NaN. And isNaN("") returns false because an empty string can be coerced to 0. If that behaviour is what you're looking for then yes, use isNaN().
So all of that is why ECMAScript 6/2015 introduced a new function, Number.isNaN(), which does test specifically for the value NaN, giving an equivalent result to the old-school a !== a.
As suggested in the comments, for older browsers (basically old IE) that don't support Number.isNaN(), if you want something clearer than a !== a and don't mind longer code you can do this:
typeof a == "number" && isNaN(a)
...which is one of the two Number.isNaN() polyfills suggested by MDN. (The other just uses a !== a.)
I have a timer object written in javascript and my goal is to make it as efficient and fast and thus as accurate as possible.
One of my concerns has to do with a specific case that could generally be applied to all manners of coding and I'm sure has been asked before, I just am not sure what terms to use when searching for it.
My question is which of these 2 cases is faster/more efficient?
Case 1: Assigning a variable some value in a repeated section of code, even when you know the value only needs to be assigned once.
Case 2: Checking the value of the variable, thus conditionally assigning it.
function runOnce(){
timer.someValue = { //some object...};
}
function someRepeatedFunction(){
timer.someValue = null;
//vs
if(timer.someValue){
timer.someValue = null;
}
}
Which of those cases would be faster?
Micro-optimization #1
If you insist on the conditional checking, I would bypass using the == operator (that I think Javascript uses automatically) and go for the === operator.
The identity === operator behaves identically to the equality == operator except no type conversion is done, and the types must be the same to be considered equal.The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.
Micro-optimization #2
With respect to the choice between the assignment & conditional checking, it seems logical to go for assignment in the case of using a global variable (like the one you seem to be using). Unless you plan on handling cases in an else situation there's no need to continually check what the current typeof the object or it's value is.
Is it wrong to return two different types from a JavaScript function? This is often the case in PHP. For instance PHP's strpos()-function returns an integer telling you the position or false if not found. In Java this would not be possible since it's not a loose typed language and the return type is defined with the function.
So would be be wrong to do the same in JavaScript?
E.g.
function num(x, y) {
if (x !== y) {return false;}
if (x < 5) {return 5;}
return x;
}
In above example we return an integer or boolean. But is it wrong? Would it make the life of the JavaScript engine harder and perhaps force it to de-optimize?
Or in another example, what if I have a function that creates an element and tries to put it into the DOM then returns the newly created element object. But if it can't find the parent element you send as an param it return false.
This is not wrong, since Javascript is dynamically typed.
However, it is often considered as bad taste: makes the code less readable, and might make it less efficiently translatable by JIT techniques.
It's not at all wrong. Your code will execute its job successfully. But the thing is it's not considered a very good programming practice. Though there are no hard and fast rules and in many situations such a methodology may be required, it's advisable to avoid this approach as far as applicable.
Secondly, you can consider re-factoring your code, so that it does only one thing. My suggestion would be to separate both the 'if's into two different methods.
It's not strict wrong, because javascript is dynamically typed. But if it happens, it could hide a wrong architecture of your function.
What happens in some cases?
In some case, JavaScript core returns null if there is no result. Is the case of .match function. In this case, null is something like "I've found nothing".
In other case it returns -1 (i.e. .indexOf). In this case it's appropriate because the return value should be an integer positive. -1 it's a way to tell us: "I've found nothing" or "I've not found a positive integer".
So why it returns in one case null and in other way -1 for tell us the same thing?
In the first case the match should return an Array (that's an Object).
In the second case the indexOf should return an integer. So -1 is more appropriate than null, because null it's an Object and not an integer.
Why not undefined? because undefined is something of undefined, like: "I've found nothing, and I don't know how tell you!". undefined generally is used when the function should returns a String but this string is not found. Returns "" is not elegant because it tell us: "I've found the String, and the string is empty".
Another case could be a function that returns a Boolean but in one case is undefined. So when you ask: "It's true or false?", it seems to says: "Neither!".
A beautiful example is this function:
isAlive(SchroedingersCat); // <--- undefined!!!
What if your function should be return a DOM element?
See what jQuery doing.
jQuery return always an Object. This object (instance of itself) could be empty or not.
var obj = $('#idElement') // <--- return always a jQuery object
if(obj.length == 1) {
// do something
}
This is an excellent trick in order to permit us to do a chain without force to check every time if we found something.
In JavaScript, I want to compare a value for (strict) equality to false.
From Java / C# I am used to writing:
if (!value)
//Do Something
However, I can not use it in JavaScript as null, undefined (and others IMHO) evaluate to false inside an if-statement, too. (I don't want that).
Thus, I have therefore been writing the following to formulate such a check:
if (value === false)
//Do Something
Yet, this construct looks a little bit strange to me.
Are there any more elegant ways here (which lead to the same results as the === false of course)?
Introducing a method isFalse would be an option, of course, but that's not what I am looking for as it would look even more distracting than the === false.
If you truly want to check for an explicit false value in Javascript, as opposed to a 'falsy' value (null, undefined, 0, etc.) then === false is by far the most standard way of doing so. I don't think it needs to be changed - that's part of the beauty of such a dynamic language!
Please, don't write a function isFalse() (a candidate for The Daily WTF), use the === operator even if it looks strange to you, there is no cleaner way.