Javascript TRUE and "true" why someone uses string instead of boolean? - javascript

I see in some javascript codes that people write something like this:
var myVar = "true";
//...
if(myVar == "true") {
//...
}else{
//...
}
Why people don't use TRUE or FALSE? As far as I know boolean type is obvious for browsers.
Or is just a poor code ... and try to never write in this way.

It's just poor code. Try to never write in this way.
This kind of code is just horrible for maintainability. Both the == (instead of ===) and the true as string.
PS: besides, "true" == true // false. For the === argument, it's simply because true == 1 // true, and a lot of others look alike stuff like this.

You should not do this, unless you really expect a string that contains true for some reason :). But even in that case, using strict equality (===) would be the right choice.
In the code example you are showing, this is simply a terrible way of writing code.

It's just poor code, as you say.
A "real" developer never writes if (condition == true), but only if (condition)
Could also be written if (true == condition). This is called Yoda style and is designed to prevent unwanted assignment of variables if you mistakenly write = instead of ==.

Related

OK to use type coercion when checking for undefined/null?

Is it acceptable to use type coercion (== instead of ===) to check for undefined/null?
What are the downsides? Is there a better way to check for undefined/null?
Clarification: I am looking for a statement that will check for both undefined and null.
test(null);
test(undefined);
function test(myVar) {
if (myVar != undefined) {
alert('never gets called')
}
}
I'm going to attempt to address this question as objectively as possible, but it deals with some mushy "best practices" opinion stuff that can trigger people to forget that there's more than one way to do things.
Is it acceptable to use type coercion (== instead of ===) to check for undefined/null?
It's acceptable to write code however you see fit regardless of anyone who tells you otherwise. Including me.
That's not really helpful here, so let me expand on that a bit, and I'll let you decide how you feel about it.
Code is a tool that can be used to solve problems, and == is a tool within JavaScript code to solve a specific problem. It has a well-defined algorithm which it follows for checking a type of equality between two parameters.
===, on the other hand, is a different tool that solves a different, specific problem. It also has a well-defined algorithm which it follows for checking a type of equality between two parameters.
If one tool or the other is appropriate for your use-case, then you shouldn't hesitate to use the tool.
If you need a hammer, use a hammer.
But if all you have is a hammer, then everything looks like a nail, and this is the core issue with ==. Developers coming from other languages often aren't aware of how == works and use it when === would be appropriate.
In fact, most use cases are such that === should be preferred over ==, but as you've asked in your question: that's not true in this instance.
What are the downsides?
If you relax your standards for === and allow developers to use == you may very well get bitten by misuse of ==, which is why sticking religiously to === may be acceptable to some, and seem foolish to others.
if (val === null || val === undefined) {...
is not particularly difficult to write, and is very explicit about intent.
Alternatively,
if (val == null) {...
is much more concise, and not difficult to understand either.
Is there a better way to check for undefined/null?
"better" is subjective, but I'm going to say, "no" anyway because I'm not aware of any that improve the situation in any meaningful way.
At this point I will also note that there are other checks that could be performed instead of null/undefined. Truthy/falsey checks are common, but they are another tool used to solve yet another specific problem:
if (!val) {...
is much more concise than either of the previous options, however it comes with the baggage of swallowing other falsey values.
Additional notes on enforcement via linting:
If you follow the strictness of Crockford's JSLint, == is never tolerated, in the understanding that a tool that's "sometimes useful" but "mostly dangerous" isn't worth the risk.
ESLint, on the other hand, allows for a more liberal interpretation of the rule by providing an option to allow null as a specific exception.
== undefined and == null are both equivalent to checking if the value is either undefined or null, and nothing else.
As for "acceptable", it depends on who is looking at the code, and whether your linter is configured to ignore this special case.
I can tell you for sure that some minifiers already do this optimisation for you.
The ideal way to test for undefined is using typeof. Note you only need to test them separately if you care about a difference between undefined and null:
test(null);
test(undefined);
function test(myVar) {
if (typeof myVar === "undefined") {
// its undefined
}
if (myVar === null) {
// its null
}
}
If you don't care if its undefined/null, then just do:
test(null);
test(undefined);
function test(myVar) {
if (!myVar) {
// its undefined or null, dunno which, don't care!
}
}

Is there a way to conditionally call a function with one line of JavaScript?

I would like an elegant way to only execute a function if some condition is met. Two options that I know of are if conditions and the tertiary operator.
if
if(headerExists($listview) === false)
addHeader($listview, template);
tertiary
headerExists($listview) ? null : addHeader($listview);
To me, the if makes the logic a little harder to understand when you look at the function as a whole. The tertiary function seems smart but you never see it anywhere and having to declare null is explicitly wasted space.
The third option is to (ab)use the short-circuit behaviour of the logical operators:
!headerExists($listview) && addHeader($listview, template);
// or
headerExists($listview) || addHeader($listview, template);
However, this is only a minification technique (which doesn't even make the code a lot shorter). Use an if-statement for readability reasons, if you want without a block and in one line:
if (!headerExists($listview)) addHeader($listview, template);

More elegant alternative for "value === false"?

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.

Comparison operation - Correct Syntax?

Coming from PHP I understand the difference in using == verses === in a comparison operation, but with JavaScript is it acceptable to use == or ===?
I wanted to validate my JavaScript code and found JSLint. While running the validation with JSLint I see these types of messages.
Some examples:
var show = $('input[name=female]:checked').val() == "true";
Problem at line 278 character 70: Expected '!==' and instead saw '!='.
and
var show = $('input[name=living]:checked').val() != "false";
Problem at line 283 character 38: Expected '!==' and instead saw '!='.
So My question is, Would using the current syntax of == or != be valid/correct or do I need to use === and !== ?
EDIT: Just to point out the code does work
It is correct in a way but JSLint expects strict comparison to prevent problems with type conversion.
It is good practice to always use strict comparison and "normal" comparison only where you really need/want it (because you want to make use of type conversion for some reason).
From JSLint's documentation:
== and !=
The == and != operators do type
coercion before comparing. This is bad
because it causes ' \t\r\n' == 0 to
be true. This can mask type errors.
If you only care that a value is
truthy or falsy, then use the short
form. Instead of
(foo != 0)
just say
(foo)
and instead of
(foo == 0)
say
(!foo)
Always use the === and !==
operators.
Crockford and JSLint are somewhat dogmatic on this point, and I think over-prescriptive. Always using === rather than == is a reasonable rule of thumb for inexperienced JavaScript developers, but if you know the basic rules then there is no problem with using ==. In particular, if the two operands are guaranteed to be of the same type (such as in a typeof comparison like typeof foo == "undefined") then the two operators are specified to follow precisely the same steps.
There is also a reasonable point about habitually using === removing the need to think about which operator to use, but frankly I prefer to be forced to consider all the possible values of the two operands I'm comparing and find JSLint unnecessarily nannying.
The == syntax is valid but in some cases it can lead to rather nasty bugs in large projects. If you don't have a good reason to use == you should by default write JavaScript with === because it checks for type as you know.
It works either way, but you will save yourself pain in the future if you default to ===.
Depends on the situation.
=== is often preferred because you won't have any false-positives that you might not have considered (it might also be slightly quicker in some implementations because it compares to less potential values, although I haven't checked that, just a thought, and the speed difference would be negligible).
== is often more convenient to cover many/all cases (if I'm not mistaken, jQuery doesn't pass JSLint because in some places the code intentionally uses == to cover a multitude of cases rather than testing each one individually).
you can do just == and !=, I don't think there would be any problems with that.

Using &&'s short-circuiting as an if statement?

I saw this line in the jQuery.form.js source code:
g && $.event.trigger("ajaxComplete", [xhr, s]);
My first thought was wtf??
My next thought was, I can't decide if that's ugly or elegant.
I'm not a Javascript guru by any means so my question is 2-fold. First I want to confirm I understand it properly. Is the above line equivalent to:
if (g) {
$.event.trigger("ajaxComplete", [xhr, s]);
}
And secondly is this common / accepted practice in Javascript? On the one hand it's succinct, but on the other it can be a bit cryptic if you haven't seen it before.
Yes, your two examples are equivalent. It works like this in pretty much all languages, but it's become rather idiomatic in Javascript. Personally I think it's good in some situations but can be abused in others. It's definitely shorter though, which can be important to minimize Javascript load times.
Also see Can somebody explain how John Resig's pretty.js JavaScript works?
It's standard, but neither JSLint nor JSHint like it:
Expected an assignment or function call and instead saw an expression.
You must be careful because this short-circuiting can be bypassed if there is an || in the conditional:
false && true || true
> true
To avoid this, be sure to group the conditionals:
false && (true || true)
> false
Yes, it's equivalent to an if as you wrote. It's certainly not an uncommon practice. Whether it's accepted depends on who is (or isn't) doing the accepting...
Yes, you understand it (in that context); yes, it is standard practice in JavaScript.
By default, it will trigger a jshint warning:
[jshint] Expected an assignment or function call and instead saw an expression. (W030) [W030]
However personally, I prefer the short-circuit version, it looks more declarative and has "less control logic", might be a misconception though.

Categories

Resources