How Good C# Habits can Encourage Bad JavaScript Habits: Part 1

How Good C# Habits can Encourage Bad JavaScript Habits: Part 1

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

1. 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:

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).

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.

2. 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#.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.