How Good C# Habits can Encourage Bad JavaScript Habits: Part 2 – False-y, Testing and Default Values, Comparisons, and Looping

This is the second post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.

The first post covered the following topics:

  • 1. Having Variables & Functions in Global Scope
  • 2. Not Declaring Arrays & Objects Correctly


This post continues to focus on areas where C# developers tend to make poor decisions when writing JavaScript based on their previous training. The languages are syntactically similar enough that C# developers tend to not invest the time to learn JavaScript’s differences.

The following post points out several misunderstandings that can get you into some confusing situations.


More Bad Practices

3. Not Understanding False-y Values

Unlike C# there are many values that JavaScript has that act false-y. Inside an if statement truth-y values will proceed into the then branch and false-y values will drop into the else branch. It is important to understand these special false-y values not only when writing your code, but when trying to understand other people’s code.

The False-y values are:

"" (empty string)
NaN (not a number)

All other values that aren’t listed in the above list will be considered truth-y (including all objects, the strings “0”, “false”, and many other strange combinations).

Best Practice

When it comes to understanding the outcome of a logical statement, you should know the false-y values in JavaScript. Since these rules are considerably different than C#, you should take the time to understand them.

We will examine the implications of knowing these false-y values a little further in the next few sections.

4. Not Testing & Setting Default Values Correctly

You can easily spot a C# developer if you see them checking for null inside of an if statement or when setting a default value.

Checking for Null

It is common and considered a best practice in C# to check for null before using a variable. If you don’t, then you might fall victim to the dreaded “Object reference not set to an instance of an object” exception. Also, when dealing with strings you’ll also want to test if it is empty or not. The following code snippet is a typical way to do this in C#.

  1. // C# example. Don't do this in JavaScript
  2. if ( someString != null &&
  3.     someString.length > 0 ) {
  4.     //Do something here...
  5. }
Hide/show line number

In fact, the above code snippet is such a common practice that there is a special IsNullOrEmptymethod in the .NET framework to help simplify this case.

  1. // C# code to simplify checking for null and empty string
  2. if ( !string.IsNullOrEmpty(someString) ) {
  3.     //Do something here...
  4. }
Hide/show line number

As it turns out, when considering the JavaScript false-y values, you can shorten all this logic to the following code snippet. The following code snippets checks to see if the variable is not undefined, not null, and is not empty.

  1. // Simplified JavaScript syntax to check for
  2. // undefined, null, & empty string values
  3. if ( someString ) {
  4.     //Do something here...
  5. }
Hide/show line number

As a side note, the above someString variable is more likely to be undefined than it is null due to variable hoisting, but thanks to false-y values that is being checked.

Setting A Default Value

Another common scenario you’ll run into is setting a default value to a variable. In C#, you might be be tempted to write some code like the following.

  1. // C# example. Don't do this in JavaScript
  2. if ( someString == null ) {
  3.    someString = "default Value";
  4. }
  6. // Slightly better, but don't do this either
  7. someString = someString ? someString : "default value";
Hide/show line number

Instead, there is a much simpler way to perform this in JavaScript that uses the logic or operator.

  1. // JavaScript syntax to set a default value
  2. someString = someString || "default value";
Hide/show line number

Best Practice

Based on the false-y rules we learned earlier, if we want to check if a variable is undefined, not null, and has a value then all we need to do is check the object itself.

5. Using the Wrong Comparison Operators

Knowing that JavaScript is loosely typed and having the False-y values fresh in our mind from the previous section, let’s focus now on common mistakes when using the comparison operator.

Coming from C# you will intuitively use the == and != in your if statements, however, this may yield some results that you didn’t expect.

Problems When Using == or != Comparison Operators

When using the == and != comparison operators, JavaScript tries to help you by coercing the two values into the same type so that it can compare them. This sounds like a good idea, but in the end it can lead to some very confusing results. Check out the following for some of these unexpected results.

// Unexpected Comparisons using the == Operator
0          ==  ''        //true
0          ==  '0'       //true
false      ==  '0'       //true
null       ==  undefined //true
' trn ' ==  0         //true

You Should Use the === or !== Instead

A better way to compare is to use the === and !== operators (also known at the identify operators), which are much more rigorous. They will not only check the value, but also check the type as well. The results of these comparisons are probably more what you would expect in a strongly typed language. The following code uses the same comparison as the above example, but uses the identify operator instead.

// Expected Comparisons using the === Operator
0          === ''        //false
0          === '0'       //false
false      === '0'       //false
null       === undefined //false
' trn ' === 0         //false

Best Practice

When you are comparing two values in JavaScript you should use the Identify Comparison Operators (=== & !==).

6. Not Using the for…in Statement Correctly

For those of you who regularly write C#, you probably don’t use the classic for loop much, but use the for…in loop instead. If you aren’t careful this can byte you in several different ways.

Using the for…in Statement on Arrays

You may see the for…in statement used to iterate over arrays, but don’t! You can get into some weird issues. You should instead use the for statement when looping over arrays.

The for…in statement does not guarantee the order of the items that are going to be retrieved, plus you can get into some interesting problems.

In the following example we are creating an array and then setting the 5th index with a value of “test”. Since we have an item at the 5th index, the array is marked as having a length of 6 items. So far, there shouldn’t be any surprises here.

  1. var myArray = [], name;
  2. myArray[5] = "test";
  3. console.log( myArray.length ); //6
Hide/show line number

However, if you used the statement on this array, you would only see the one item that you inserted in the array, which is probably not what you intended. If this is what you intended, then you should probably not be using an array and should be using an object instead.

  1. var myArray = [], name;
  2. myArray[5] = "test";
  3. console.log( myArray.length ); //6
  5. for ( name in myArray ) {
  6.     console.log( name, myArray[name] );
  7.     //Outputs...
  8.     //   5, test
  9. }
Hide/show line number

You can execute and modify the above code from


You should use the standard for loop when iterating over an array. The following example does loop over the entire range of indexes, although most of them are undefined since we didn’t set their values.

  1. var myArray = [], name;
  2. myArray[5] = "test";
  3. console.log( myArray.length ); //6
  5. for ( var i = 0, length = myArray.length; i < length; i++ ) {
  6.     console.log( i, myArray[i] );
  7.     //Outputs...
  8.     //   0, undefined
  9.     //   1, undefined
  10.     //   2, undefined
  11.     //   3, undefined
  12.     //   4, undefined
  13.     //   5, test
  14. }
Hide/show line number

You can execute and modify the above code from


If you are not convinced, there is another problem that you can run into when using the for…instatement on an array. Now just suppose that you or some other library changed the prototype of the Array object? If someone where to add a property to the Array.prototype it would also show up as one of the keys in the for…in.

  1. var myArray = [], name;
  2. myArray[5] = "test";
  3. console.log( myArray.length ); //6
  5. Array.prototype.someVariable = "Where did this come from?";
  6. for ( name in myArray ) {
  7.     console.log( name, myArray[name] );
  8.     //Outputs...
  9.     //   5, test
  10.     //   someVariable, Where did this come from?
  11. }
Hide/show line number

You can execute and modify the above code from


This actually brings up our next subtopic about using the for…in statement correctly when using an object.

Using the For…In Statement Incorrectly with Objects

As we discussed briefly in the above section, hopefully you are only using the for…in statement with objects and not arrays. You might have seen the for…in used like the following

  1. for ( var name in object ) {
  2.     //Your code here
  3. }
Hide/show line number

That seems harmless, right? And in many cases it does exactly what you want it to. As it turns out, you should be careful using the above syntax. The for…in statement will actually iterate through all the properties of the object and also the properties that are inherited from the prototype! Since you probably don’t want to iterate over your inherited prototype properties, you should check the object you are enumerating to see if it contains the property before proceeding.

Your modified code snippet should look something like the following instead.

  1. /* Check if object has property before
  2. iterating, because functions inherited
  3. from prototype are also included */
  4. for ( var name in object ) {
  5.    if ( object.hasOwnProperty(name) ) {
  6.       //Your code here
  7.    }
  8. }
Hide/show line number

The following code snippet shows an example of when the for…in statement might show some undesired results.

  1. var Person = function( firstName, lastName ) {
  2.   this.firstName = firstName;
  3.   this.lastName = lastName;
  4.   return this;
  5. };
  7. Person.prototype = {
  8.   isMarried : false,
  9.   hasKids: false
  10. };
  12. var john = new Person( "John", "Smith" ),
  13.   linda = new Person( "Linda", "Davis" ),
  14.   name;
  16. john.isMarried = true;
  18. console.log( "Not Checking hasOwnProperty" );
  19. for ( name in john ) {
  20.   console.log( name + ": " + john[name] );
  21.   //Outputs
  22.   //  firstName: John
  23.   //  lastName: Smith
  24.   //  isMarried: true
  25.   //  hasKids: false
  26. }
  28. console.log( "Checking hasOwnProperty" );
  29. for ( name in linda ) {
  30.   if ( linda.hasOwnProperty(name) ) {
  31.     console.log( name + ": " + linda[name] );
  32.     //Outputs
  33.     //  firstName: Linda
  34.     //  lastName: Davis
  35.   }
  36. }
Hide/show line number

You can execute and modify the above code from jsFiddle.

In the above code we created two Person objects and set it’s prototype to include two new properties (“isMarried” and “hasKids”). We then loop over the properties of the “john” person, you will see that not only are his firstName and lastName displayed, but also the inherited “isMarried” and “hasKids” prototype values! In contrast, by checking .hasOwnProperty() when looping over linda’s properties, we only see that her immediate properties are displayed, instead of displaying her inherited properties as well.

Best Practice

The take aways for this point are:
* Use the for statement for arrays
* Use the for…in statement when iterating over objects and check the hasOwnProperty method


This article has covered some of the common issues you might address coming from C# to JavaScript. I have committed just about everyone of the above Bad Practices myself when I starting to code in JavaScript heavily.

With the recent serge of jQuery hitting the market and other great JavaScript libraries, it is important that we as developers understand the language instead of just thinking that our previous language knowledge will get us by.

This article only covers some of the things you should know. The next post in the series will be published next week. In the meantime please feel free to add comments of any other gotchas that you’ve experience coming from a C# background. I would love to hear about it.


This post is collected from: