A Deeper Understanding of JavaScript Statements

One of the unfortunate observations I have made about the JavaScript community is a very poor understanding of fundamentals of the language. I am no exception to this rule, and as a part of my quest to develop mastery of the language I plan to document my explorations in a number of short articles.

Let's take a look at statements, one of the essential building blocks of JavaScript. Statements are executable commands that ultimately define what our program does.

1 // A declaration statement
2 var myStatement = "Wow, that was easy";

Nothing scary here. However you may not be familiar with the raw syntax for a multi-line statement:

1 // Yes, this is executable code, give it a spin
2 {
3     var anotherStatement = "Wait.. what's going on here?";
4     console.log("This looks like an object declaration!");
5 }

As you may have gathered, we aren't declaring an object. Rather, we are using the syntax for a compound statement -- which is strikingly similar. This pattern is core to JavaScript, and we see it in just about every other aspect of the language. One such example is the if statement:

1 if (condition) {
2     console.log("We did something");
3 }

The code above reads "If condition is true, then run the contents of this statement". Remember that the code we placed inside the curly braces acts the exact same way as the single declaration of myStatement earlier. For this same, reason, we can simplify this code (although some would argue this is bad form):

1 if (condition) console.log("We did something");

Same rules apply: if the condition is true, run this statement. This is nothing profound, however it provides an explanation for why curly braces are not required for if statements, loops, and other flow control. Effectively, they perform the same role. For this same reason, we can have some more fun:

1 // Remember, while (condition is true) [statement] ...
2 var a = 0;
3 var keepGoing = true;
5 while (keepGoing) if (a < 10) a++; else {
6   console.log(a);
7   keepGoing = false;
8 }

Obviously, this is insane, and it should never be used for anything other than experimental purposes. Having said that, I would encourage you to play around with examples such as this as they are excellent for solidifying these concepts.

By learning more about the specifics of statements and how they are executed writing flexible code becomes much easier. This is a major step towards separating oneself from dependency on libraries such as jQuery and it helps to build a greater appreciation for what these tools do. It exposes the expressiveness of JavaScript and turns it into an exceptionally powerful language.