JavaScript and other language that use losely defined vars - javascript

Hey anyone out there that uses JavaScript in a professional environment. I wanted to know the standard when comparing values using == and === operators. I was watching a video the explained that if you compared a sting with a value of '5' and an int with a value of 5 it returns true using the == operator. They then suggested to use the === for everything. I know this is wrong because what if you wanted to compare some value nested in some polymorphic objects with different type defs say one being a student and the other being an instructor the === would always return false.
After much thought I came to the conclusion that it might be best to use === whenever possible and the == when only necessary.
Can you give me some insight on what the rule of thumb is in a professional environment?

The rule is simple:
Always use === and !== unless you explicitly WANT a type conversion to be allowed and have thought through the consequences of that type conversion. In otherwords, you should be using === and !== nearly all the time.
Your exception for polymorphic objects does not apply because == and === both require two objects to be the exact same object when comparing two objects. There are no type conversions in that case. If you were comparing two properties of polymorphic objects, then only the type of the property is looked at, not the type of the containing object.
For detailed rules on type conversions with ==, see this http://es5.github.com/#x11.9.3. There are some odd ones like this:
var x; // x is undefined
alert(x == null);​ // alerts true

Check out http://jshint.com which helps enforce these best practices. They (and everyone else pretty much) recommend using ===.
I can rarely think of a reason to use == over ===.
Here's a fancy example of using === even when == might feel easier.
var person = {
name: "Cody",
age: "44"
}
var targetAge = 40;
// explicit type conversion, no wonder what's happening
if (parseInt(person.age, 10) === targetAge) {
alert("You won!")
} else {
alert("Sorry You Lost!");
}
See Also: JavaScript: The Good Parts and Maintainable JavaScript, which also recommend the practice.

it's commonly used in this type of statements:
var x = 0;
if(x == false) {
// this will be executed
}
if(x === false) {
// this not
}
if(false == '') {
// this will be executed
}
if(false === '') {
// this not
}
another example - function which is returning FALSE on error or string on success
function foo(bar) {
// magic
return ''; // this is SUCCESS
}
var result = foo(123);
if(result === false) {
// omg error!!
}else{
// some string returned, event empty one is OK
}
to be honest it's really rare to use === in statements

Related

get property safely from an object in a node application

First a little bit of context (you can skip this part if you prefer to focus on code).
I joined a new project that will be integrated in a nodeJS's platform. Our team does have experience with JEE enterprise Web Apps. That sets up our background. This new project will consume REST APIs, aggregate some data, implement some business logic and pass these data to front-end consumer. Sort of lightweight microservice architecture.
Some co-workers started to work on the project and I found it that in the source code we do have a lot of code snippet like if (foo != null && foo.property != null) {return foo.property.value;}
Foo being supposed to be an object passed as an argument to a function which would implement that kind of test.
A snippet example will talk more.
Let's pretend that's the response of an API i am consuming. I want to write a small function which would return statusValue if the object does exist, if it's not null or undefined, not empty and the property does exist and isn't blank or empty for instance.
var response = {
"services":[],
"metadata": {
"status": "statusValue"
}
};
That's how it is as for now :
function getStatusValue(response) {
if (response != null && response.metadata != null) {
return response.metadata.status;
}
};
What would be considered as a best JS practise to implement that (we are also using lodash so maybe it's a better option to use lodash internals for that). I am just fearing we are transposing our Java habbits.
Basically i would like to know how to check for null, undefined, empty, blank safely (if that makes sense). What would be the JS best practice for that in 2016 with libraries such as lodash and stuff.
When checking for properties of an object, checking for loose equality to null is not enough.
Loose equality (==) employs type hinting in JavaScript, which attempts converting the members to a common type that can then be used for determining whether they are equal or not.
As such, best practices for JavaScript dictate that strict equality (===) is always to be used, in order to avoid edge-case scenarios or unknown behavior when checking for values or types.
You can find more info about loose vs strict equality here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Equality_comparisons_and_sameness
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
While this is not a must-have in your function, it is a good practice to follow and develop as a habit, so that on later code the implications of loose equality (==) could be avoided (e.g. avoiding '3' == 3, when a number or string type is expected).
Although considered a downside of the language by some, using null is similar in intent as checking for undefined, but is actually meant to express in the code that the coder is expecting an object (or lack of) to be provided, instead of a primitive type (number, string, boolean, function). This differs from Java, or any other typed language, where null is used for Object type defined variables; but in JavaScript there's no constraining a variable to given type.
You can find out more details about null at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
In practice, and especially when dealing with values that come outside of a unit - which is the case of any API - is considered a best practice to actually check for the type being an object, in order to make sure it has properties.
While your code is not incorrect, it does show that there's not much attention to best practices, which eventually will lead to writing buggy code.
My suggestion for your code, following best practices and independent of any library, is:
function getStatusValue(response) {
// must be of type `object`, to have properties.
if (typeof response === 'object' &&
// any variable of type `object` might be `null`, so exclude that.
response !== null &&
// `metadata` property must be of type `object`, to have properties.
typeof response.metadata !== 'object' &&
// `metadata` is of type `object`, check for not being `null`.
response.metadata !== null) {
// `status` property is expected to be a string, given by the API spec
if (typeof response.metadata.status === 'string' &&
// on strings, we can access the `length` property to check if empty string (0 chars).
response.metadata.status.length > 0) {
// all good, return `status` property.
return response.metadata.status;
} else {
// `status` property is either not a string, or an empty string ('').
}
} else {
// invalid `response` object.
}
}
Also, it might be easier to create or use from any libraries you integrate, a function to check for a valid object; something like _.isObject or this:
function isObject(o) {
return (typeof o === 'object' && o !== null);
}
which you could later be used in the above snipped like so:
function getStatusValue(response) {
if (isObject(response) && isObject(response.metadata)) {
if (typeof response.metadata.status === 'string' &&
response.metadata.status.length > 0) {
return response.metadata.status;
} else {
// `status` property is either not a string, or an empty string ('').
}
} else {
// invalid `response` object.
}
}
As a final thought, as it is clearly visible, following best practices does increase the size of your code, but the benefit is that the resulting code is much safer, with less chances of throwing exceptions (root of many app crashes), easier to collaborate on, and easier to build tests/coverage for.
Using Lodash, you can use the _.isNil(response) function documented here.
In general, I would check a variable like this:
if (typeof x !== 'undefined' && x !== null) {
// x has some value
}
You should not check whether x === undefined because if x is undefined, you'll get a dereference error.
I would implement this using the following function:
var response = {
"services":[],
"metadata": {
"status": "statusValue"
}
};
function getStatusValue(res) {
if (res && res.metadata)
return res.metadata.status || 'not found';
else
return 'not found';
}
console.log(getStatusValue(response));
The if statement will return false if res or res.metadata are undefined and if they both exist, it will return res.metadata.status only if it's defined or 0, otherwise it'll return 'not found'.
Here is a (more concise) way to do such a thing with just JS:
var obj = ...;
var val = obj && obj.prop && obj.prop.val;
val will be undefined/null if either obj or obj.prop are; otherwise it will be obj.prop.val.
This works because of the short-circuit evaluation of &&. It's literal behavior is this: if the first operand is falsey, it evaluates to the first operand. Otherwise, it evaluates to the second. This works as expected for booleans, but as you can see, it can be useful with objects.
|| has similar behavior. For example, you can use it to get a value, or a default if the value is falsey (e.g. null):
var val2 = val || "not found";
Note that this would evaluate to "not found" if val is anything falsey, including 0 or "".

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.

Does order of operands in equality matter? (e.g. 1 == x vs x == 1)

So I'm trying out the Google Closure Compiler and I've noticed that it switches all my equality parameters so that the variables are always on the right side of the comparison.
So now instead of typeof XMLHttpRequest=="undefined" I have "undefined"==typeof XMLHttpRequest and I have if(null!==a) instead of if(a!==null), just as some examples.
I know they accomplish the same thing, but it's just not the style I'm used to. Is there some sort of benefit that you get for having these switched? I can't see how there would be.
Can someone explain to me why the Closure Compiler decides to do this? Is it just a preference of whoever wrote that part of Closure?
Edit: To clarify, people are telling me why it might be considered good coding practice. That's fine, but this is after compilation. Is there a performance benefit or is the Closure Compiler just trying to prove a point?
Commonly done in languages like C / C++ so you can't accidently do
if (a = null) {
// sets a to null and everyone is happy.
// but probably meant to check if a is null or not.
// via (a == null)
}
if (null = a) {
// won't compile
}
The compiler switches the order for a very simple reason: it compresses better with gzip. The compiler doesn't care a wit about improving comprehension or making it easier to edit. By switching the order common comparisons such as "if (x == null) ... if (y == null) ..." become "if (null == x) ... if (null == y) ..." Gzip finds "if (null ==" and is able to replace it with a single token. It isn't a big improvement, but it adds up in a large code base.
Yes, you can't assign to a constant, and == is easy to mistype (sometimes you may forget one, and use =).
For example, what's the difference between...
if (a == 1) { }
...and...
if (a = 1) { }
? The second one will always evaluate to true, not matter what the value of a.
If you flip the LHS and RHS, you can see the immediate benefit...
if (1 == a) { }
...will work as expected and...
if (1 = a) { }
...will fail, as you can't assign to a constant.
The reason I know is is done to prevent
if (x = 5) { }
If you reverse it to
if (5 = x) { }
You would get a compiler error.
But if you write it as
if (5 == x) { }
It will compile fine.
My brain parses
if( x < y )
slightly faster than
if( y > x )
probably because real axis is always oriented from left to right, thus making condition easier to visualize.
However, in java it is more practical to write
if( "string".equals(x) ) {...
as opposed to "more natural"
if( x.equals("string") ) {...
to eliminate any opportunity for NPE.
Just a cheap replacement of static analysis of particular case of common mistake/

Why is it good practice to use if (myBoolean === true) in JavaScript? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As a follow-up to this question: Is there ever a reason to write "if (myBoolean == true)" in a JavaScript conditional? -
Why is it good practice to use if (myBoolean === true) in JavaScript? As a relatively inexperienced JavaScript user, I'm trying to work out in what specific, real-world scenarios you'd end up with a value that might be a Boolean true or might be a "truthy" value, so that you would need to check if (myBoolean === true) rather than if (myBoolean)
I'll challenge the premise of the question: I don't think it's good practice, nor do I think there's a general consensus that it is. :-)
The only reason for using === true would be if you weren't sure that myBoolean was actually a boolean and you wanted the result to be false if it weren't. There are use cases for that, but they're quite limited. 99.9% of the time, simply if (myBoolean) suffices, even though it will be true for 1, "foo", and other truthy values.
There are times when using strict equality for other reasons is quite a good idea, because JavaScript's rules for loose equality if the operands are of different types are quite complex. But if you're using something as a flag, there's little if any point to using === on it.
One particular place where I've seen === used with boolean values is in code inspired by jQuery, where a callback function can cancel an action by returning false, but doesn't have to return anything. When a function has no explicit return value, the result of calling that function is undefined, which is, of course, falsey. So code that wants to check whether the function returned false, not just undefined, would do this:
if (callback(args) === false) {
// The callback explicitly returned false (not just a falsey value), cancel
// ...
}
But that's a relatively infrequent use case, and of course it involves === false as opposed to === true...
Some random example:
function CreateSomeObject(param)
{
if (param == "1")
{
return new Stuff();
}
return null;
}
var myBoolean = CreateSomeObject("1") || true;
if (myBoolean === true)
{
//doesn't execute
}
if (myBoolean)
{
//executes just fine
}
In case of null only , you want to do that , although I never used this because it feels like more verbose and long string. No problem using it or avoiding it.It is more of style you want to write the code.
I constructed a slightly convoluted answer and then realised that the main reason is in the falsy values rather than the truthy ones. Usually, a function returns one kind of thing, and there is only one falsy value (the empty string for a string function, or 0 for a numeric one, or whatever).
However, when you aren't sure if something is defined or not, it can be instructive:
waitForResponse(request, 5000);
if(!request.ResponseValue) {
alert('Server failed to respond');
}
vs
waitForResponse(request, 5000);
if(request.ResponseValue === 'false') {
alert('Server says no');
}
Although I'd argue that you should check for undefined rather than boolyness:
if(typeof request.ResponseValue === 'undefined') {
//...
}
Incidentally, typeof is fast, at least it was in Chrome last time I checked.
Personally, I don't like statements like it's good practice to x. IMO, it all depends on the context: if you want to check some object exists, if(objectX) will do just as if (objectX === undefined) or if (typeof objectX === 'undefined') and even if (typeof objectX == 'undefined').
The reason why some people, like Douglas Crockford, strongly advocate the use of value and type checking (===) is that falsy and truthy values can, in rare cases, produce unexpected results:
var falsy = '';
if (falsy)
{//only when falsy is truthy, but an empty string is falsy
console.log('could be seen as counter-intuitive: var was declared and assigned an empty string, but is falsy');
}
var obj = {falsy:''}
if (!obj.falsy)
{
console.log('I might assume falsy is not set, although it was:');
console.log(obj.hasOwnProperty('falsy'));//true
}
Again, this might just be my opinion, but in the vast majority of cases this won't break your code. I'd even go one step further: Douglas Crockford might claim that using checking for falsy values isn't a good idea, but he does like the logical OR (||) operator:
var falsy ='';
var someVar = falsy || 'default value';//this relies heavily on falsy values
The only "solid" arguments for strict comparison are:
if you need the variable to be a boolean, but then again falsy = !!falsy; coerces to a boolean all the same
strict comparisons are marginally faster, but you'll have to do a whole lot of comparisons before you'll be able to notice the difference
Having said that, I do tend to use strict comparisons an awful lot, again, it might be a personal thing, but I like to know what the actual type of a variable is:Given that '1' == 1 evaluates to true, but '1' === 1 is false, it at least allows you to coerce a var to the type you need:
var foo = '00001';
var elements = [foo = ('00000' + (+(foo)+1)).substr(-5)];
while(elements[+(foo)-1])
{
foo = ('00000' + (+(foo)+1)).substr(-5);
elements.push(foo = ('00000' + (+(foo)+1)).substr(-5));
}
Now this isn't what you'd call good code, but there's a lot of type-juggling going on. At the end of the ride, you might want to know what value was assigned to foo. That's not an issue in this snippet, but suppose you want to use the numeric value of foo inside the while loop, if it's an odd number:
var foo = '00001';
var elements = [foo = ('00000' + (+(foo)+1)).substr(-5)];
while(elements[+(foo)-1])
{
foo = ('00000' + (+(foo)+1)).substr(-5);
elements.push(foo = ('00000' + (+(foo)+1)).substr(-5));
if (+(foo)%2 === 1)
{
foo = +(foo);
//do stuff with foo
}
}
The easiest way to check weather or not foo is a string after the loop is completed is to check foo directly: if (foo === +(foo))
I am well aware that this example is a little far-fetched, but I have encountered a case quite similar to this one. It's at times like this where the advantages of strong-typed languages really show. speaking of which: new Date() >= someDateObject vs Date() >= someDateObject... try it in your console and you'll soon see what I'm on about.

Using underscore.js for null checking

var name = "someName";
if(name !=null) {
// do something
}
I am right now using http://underscorejs.org/#isNull, how would i do
the same using underscore.js
Does it give any slight improvement in terms of performance for such
functions.
In underscore, you can use
if(!_.isNull(name)) {}
and in plain Javascript, you should use
if(name !== null) {}
You should avoid the loose inequality operator != because it does type coercion and undefined != null will return false.
Using plain Javascript is slightly faster because it doesn't have to invoke a function, but it will be imperceptible and it should hardly be a consideration.
I don't have a strong preference either way as far as readability goes, but it seems a little excessive and verbose to call a library function for such a simple check.
In underscore.js you must write this to achieve that functionality.
var name = "someName";
if(!(_.isNull(name ))) {
// do something
}
In underscore.js function isNull is written like this
_.isNull = function(obj) {
return obj === null;
};
So the difference is using == in your code and === in underscore.js.For more details about that difference you can look in this question.
Which equals operator (== vs ===) should be used in JavaScript comparisons?
P.S. I will suggest to write your own condition instead of using any library in such simple place.
var name = "someName";
if(name !== null)) {
// do something
}
Well your original code is flawed because if name is an empty string, false, the number 0 or any other falsy value then it will be considered null as far as your test is concerned.
As a general rule, calling ANY function is an overhead that should be avoided if possible. In this case, calling a function just to test if a value is null, when you could very easily just write if( name === null), is just stupid, IMO...
if ((!(_.isUndefined(data)) || _.isEmpty(data))) {
//Valid Data
}else {//Not Valid}

Categories

Resources