Is it safe to use length instead of ==""? - javascript

Is it safe to use length property instead of =="" for empty string validation?
Is it valid on all bool operators?
It might be a very simple question and I am pretty sure that the answer is a yes/yes, but I am using it a lot recently and I am a bit worried about any possible pitfall.
For completeness, here is a simple example
var valid = name.length && (foo.length||bar.length);

It is always safe to use .length IF you know for sure that you have something in the variable that can have properties (like a string).
But, if the variable might be undefined or null, then .length will not be valid and will not do what you want and name === "" would be safer.
Many Javascript developers simply do:
if (name) {
//
}
This checks for any truthy value in name. So, the if will not be satisfied if name is undefined, null or even an empty string "" and, in some cases, protects your code a bit more than what you were doing.
Or, in your example, you could perhaps just do:
var valid = name && (foo || bar);
This will require name and either foo or bar to be truthy. This won't protect against name, foo or bar being some type of data without a .length property like your original code would, but it would do a better job of protecting against any of these variables being undefined or null.
Remember that an empty string "" is a falsey value so you can use that to your advantage in boolean comparisons.

Related

ReactJS: Is it safe to use a conditional in the event of an undefined props?

I have an Immutable.Map with a couple of key value pairs.
Object {1: -200, 2: 13540}
<Component
items={this.props.items.get(key) || 0}
/>
The key may or may not exist in the map. In the case that it doesn't exist I just want to pass in zero to the component. It is a required props.
Is the conditional in there safe? What is a better approach if it's not safe?
A conditional is safe, but the way you have is ambiguous - you are likely going to get the result of the boolean expression, not the actual value.
I would do it like this to be explicit:
let val = this.props.items.get(key);
items={val ? val : 0}
This explicitly returns either val or 0, rather than the result of the boolean expression val || 0.
Your code looks like it's not going to compile just yet without some heavy modification, but yes you can certainly be doing that sort of thing.
The key is that Immutable.js does not throw an error on a missing key but returns the JS value undefined which is falsy, so undefined || 0 evaluates to 0 via the very-type-lax "if this first thing is truthy, return whatever it is, otherwise return whatever that second thing" behavior of ||.

Javascript comparisons == null alternatives

In JavaScript code I want to replace the double-equals structure of the following if-statement:
if( name == null ) {
//do stuff
}
The double equals fail for the jshint rule "eqeqeq", where it's recommended to replace double equals with triple equals. For a moment, let's imagine the above code changed from == null to === null like this:
if( name === null ) {
//do stuff
}
This would work for a variable explicitly defined having the value null, but unfortunately would fail for any unset variables like this.
var a = null; // works correctly
var b; // will fail in comparison
Previously when the triple-equals rule was important to me I would do the following
if( name === null ||| typeof(name) === 'undefined' )
but I find this extremely bloated.
The best alternative I can come up with now is to use the nature of the if-statement and let it evaluate to a false-ish expression like here where I negate the expression and simply remove the == null part:
if( !name ) {
//do stuff
}
For me, this is much simpler, easy to read, and completely avoids explicit equals comparison. However, I am uncertain if there are any edge causes I am missing out here?
So the question is, can I generally replace == null with the negated expression if statements? If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
My criteria for picking a solution will be
clean code
easy to read and quickly understand
validates jshint rules
works in modern browsers (as of writing January 2015)
I am aware of other slightly related questions for discussing difference in the equality operators == vs ===, but this is merely for a discussion of the evaluation compared to null-ish inside the if-statement.
So the question is, can I generally replace == null with the negated expression if statements?
Probably not universally, no, but perhaps in some places.
If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
The !value check will be true for all of the falsey values, not just null and undefined. The full list is: null, undefined, 0, "", NaN, and of course, false.
So if you have name = "" then
if (!name) {
// ...
}
...will evaluate true and go into the block, where your previous
if (name == null) {
// ...
}
...would not. So just doing it everywhere is likely to introduce problems.
But for situations where you know that you do want to branch on any falsey value, the !value thing is very handy. For instance, if a variable is meant to be undefined (or null) or an object reference, I'll use if (!obj) to test that, because any falsey value is good enough for me there.
If you want to keep using JSHint's === rule, you could give yourself a utility function:
function isNullish(value) {
return value === null || typeof value === "undefined";
}
The overhead of a function call is nothing to be remotely worried about (more), and any decent JavaScript engine will inline it anyway if it's in a hotspot.

Is it safe to use comparison "if(foo)" instead of "if(foo == null)" on non-primitive types in JavaScript?

Assuming the foo is declared as a non-primitive type variable, but might be uninitialized, is there any possibility to use on non-primitive object comparison as this:
if (foo) {
...
}
or is it better to do it the longer way like this?
// not using "===" here on purpose, because the variable is non-primitive, so the value can't be 0 or empty string
if (foo != null) {
...
}
If it is not equal, then why.
By "non-primitive type" you mean object? Yes, all objects are truthy, so it is enough to distinguish them via if (foo) from any falsy values that the foo variable might contain, such as the primitive values undefined and null.
However, notice that you cannot "declare a variable as a non-primitive type" in JavaScript, so you must ensure by other means that it never has a truthy primitive value. If you could ensure that it always contains an object, you wouldn't need the condition at all.
In my experience, I have found it to be safest to specify exactly what you want in boolean expressions and never rely on type coercion.
If you don't want it to be equal to 0 or null or empty string, then:
if (foo !== 0 && foo !== '' && foo !== null) {
/* note that if foo = undefined, this will still get executed. */
}
Some libraries like Underscore or a framework like Angular have convenience functions for things like that, so you can do:
if (_.isObject(foo) === true) {
/* execute this */
}

boolean in an if statement

Today I've gotten a remark about code considering the way I check whether a variable is true or false in a school assignment.
The code which I had written was something like this:
var booleanValue = true;
function someFunction(){
if(booleanValue === true){
return "something";
}
}
They said it was better/neater to write it like this:
var booleanValue = true;
function someFunction(){
if(booleanValue){
return "something";
}
}
The remark which I have gotten about the "=== true" part was that it was not needed and could create confusion.
However my idea is that it is better to check whether the variable is a boolean or not, especially since Javascript is a loosetyped language.
In the second example a string would also return "something";
So my question; Is it neater to loose the "=== true" part in the future, or is it good practise to check the type of the variable as well.
Edit:
In my "real" code the boolean represents whether an image has been deleted or not, so the only values boolValue should ever have is true or false.
0 and 1 for example shouldn't be in that variable.
First off, the facts:
if (booleanValue)
Will satisfy the if statement for any truthy value of booleanValue including true, any non-zero number, any non-empty string value, any object or array reference, etc...
On the other hand:
if (booleanValue === true)
This will only satisfy the if condition if booleanValue is exactly equal to true. No other truthy value will satisfy it.
On the other hand if you do this:
if (someVar == true)
Then, what Javascript will do is type coerce true to match the type of someVar and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid == because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid == entirely.
As an example of how confusing it can be:
var x;
x = 0;
console.log(x == true); // false, as expected
console.log(x == false); // true as expected
x = 1;
console.log(x == true); // true, as expected
console.log(x == false); // false as expected
x = 2;
console.log(x == true); // false, ??
console.log(x == false); // false
For the value 2, you would think that 2 is a truthy value so it would compare favorably to true, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true to the number 1 so it's comparing 2 == 1 which is certainly not what you likely intended.
So, buyer beware. It's likely best to avoid == in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.
So, it really depends upon the expected values for booleanValue and how you want the code to work. If you know in advance that it's only ever going to have a true or false value, then comparing it explicitly with
if (booleanValue === true)
is just extra code and unnecessary and
if (booleanValue)
is more compact and arguably cleaner/better.
If, on the other hand, you don't know what booleanValue might be and you want to test if it is truly set to true with no other automatic type conversions allowed, then
if (booleanValue === true)
is not only a good idea, but required.
For example, if you look at the implementation of .on() in jQuery, it has an optional return value. If the callback returns false, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false was returned, they check the return value explicity for === false because they don't want undefined or 0 or "" or anything else that will automatically type-convert to false to also satisfy the comparison.
For example, here's the jQuery event handling callback code:
ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
You can see that jQuery is explicitly looking for ret === false.
But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
If you write: if(x === true) , It will be true for only x = true
If you write: if(x) , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.
In general, it is cleaner and simpler to omit the === true.
However, in Javascript, those statements are different.
if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.
if (booleanValue === true) will only execute if booleanValue is precisely equal to true.
In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN;
otherwise the result is true.
String The result is false if the argument is the empty
String (its length is zero); otherwise the result is true.
Object true.
But comparison with === does not have any type coercion, so they must be equal without coercion.
If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.
if(x===true){
...
} else if(x===false){
....
} else {
....
}
It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.
If the variable can only ever take on boolean values, then it's reasonable to use the shorter syntax.
If it can potentially be assigned other types, and you need to distinguish true from 1 or "foo", then you must use === true.
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.
Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true
Since you already initialized clearly as bool, I think === operator is not required.
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the === comparison. I think that there are three reasons for that:
It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefined or null value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.
Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput() returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput() is only called if the given input is a string that contains non-whitespace characters.
In JavaScript && returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized will be undefined if someString was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null or undefined values, which would clutter up the code. In JavaScript that is not needed.
In Javascript the idea of boolean is fairly ambiguous. Consider this:
var bool = 0
if(bool){..} //evaluates to false
if(//uninitialized var) //evaluates to false
So when you're using an if statement, (or any other control statement), one does not have to use a "boolean" type var. Therefore, in my opinion, the "=== true" part of your statement is unnecessary if you know it is a boolean, but absolutely necessary if your value is an ambiguous "truthy" var. More on booleans in javscript can be found here.
Also can be tested with Boolean object, if you need to test an object
error={Boolean(errors.email)}
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE would ever confuse anyone who knew what they were doing.
Revisa https://www.w3schools.com/js/js_comparisons.asp
example:
var p=5;
p==5 ? true
p=="5" ? true
p==="5" ? false
=== means same type also same value
== just same value

Javascript - If statements check both expression and definition declaration? This is confusing

var boolTrue = true;
var randomObject;
if (boolTrue)
// this will fire
if (randomObject)
// this will fire, because the object is defined
if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'
Coming from a C++ and C# background, I am very familiar with the basic if(expression) syntax. However, I think it is not very readable to have both expressions (true/false) and have object existence also being a expression. Because now if I see a function like below, i don't know if the data coming in is an object (existence/undefined check) or a boolean.
function(data) {
if (data)
// is this checking if the object is true/false or if the object is in existence?
}
Is this just the way it is? I mean, is there anyway to easily read this? Also, where is this documented anywhere in the JS spec (curious)?
In Javascript everything is "true" (or "truthy" to be more precise using Javascript parlance) except false, 0, undefined, null, NaN and empty string.
To avoid confusion use:
if (data === true) // Is it really true?
and
if (typeof data === 'undefined') // Is the variable undefined?
You can check for (non-)existence separately:
if ( typeof variable == 'undefined' ) {
// other code
}
However, the syntax you show is commonly used as a much shorter form and is sufficient in most usecases.
The following values are equivalent to false in conditional statements:
false
null
undefined
The empty string ”
The number 0
The number NaN
It checks whether it is truthy.
In JavaScript, everything is truthy except false, 0, "", undefined, null and NaN.
So, true will pass, as well as any object (also empty objects/arrays/etc).
Note that your third comment is true if you mean "declared but not defined" - a variable that has never been declared throws a ReferenceError on access. A declared, non-defined variable (var something;) is undefined (so, not truthy) so it will indeed pass the condition if you negate it.

Categories

Resources