Andy from Webcrunch

Subscribe for email updates:

How to REALLY Learn JavaScript Series: Part 3 Conditionals and Loops
Portrait of Andy Leverenz
Andy Leverenz

February 16, 2015

Last updated November 5, 2023

How to REALLY Learn JavaScript Series: Part 3 Conditionals and Loops

Continuing on in our series titled How to REALLY Learn JavaScript I direct your attention to some of the most powerful components of the programming language. Combining JavaScript conditionals and loops can create web applications and/or interactions to customize any web experience you can think of. Join me as we progress further into the language and start to use it in a real-world setting.

We’ve covered the fundamentals of the language but I’m sure you’re more than ready to really do something with JavaScript. I wanted to note that in order to REALLY learn the language you have to use it. Reading books or rudimentary blog posts only gets you so far. I’ll try my best to give an example where you would actually use JavaScript for the intended solution but be prepared to tackle some projects on your own. As with many things, you learn by doing.

Conditionals (aka Conditional Statements)

Conditionals are blocks of code that run a test to see whether an expression is true or false. There are different types of tests you can run all of which test whether an expression is true or false. The biggest difference between them is how they go about performing the test. Conditionals can be simple, such as telling a function to exit, or complicated, such as specifying the number of commands to execute repeatedly.

The if Statement

The if statement is one of the most frequently used in most programming languages. To dive in we start with the basic syntax to follow:

if (condition) { statement1 } else { statement2 }

Essentially, what is being performed is if the condition provided evaluates to true then statement1 is executed otherwise statement2 is executed.

I mentioned earlier that a condition tested on whether expression was either true or false. In reality, the condition placeholder in the syntax above can be any type of expression. It doesn’t always have to be a boolean value as an end result (true or false). If you aren’t sure what a boolean value is I suggest taking a step back and reading part 2 of this series. It goes over the fundamentals of data types and what their purpose is within JavaScript.

You can write the statement in one line but for legibility’s sake and the fact that JavaScript doesn’t care about whitespace it is easier to read when you write it like this:

if (condition) {
    // alert('This was true');
} else {
    // alert('This was false');    
}

This format is probably the one you will see more often. For grins another format which you might see looks like this:

condition ? expression1 : expression2 

Here the condition starts off the statement followed by a question mark which is what is questioning if the condition is true or false.
If it is true, expression1 fires and if it is false, the expression following the colon fires (expression2). Simple enough.

Let’s try a real-world example so this gets a tad more interesting.

var name = 'andy',
    password = 'webcrunchblog';
    

if ( name === 'andy' && password === 'webcrunchblog' ) { 
    document.write('Welcome ' name.charAt(0).toUpperCase() + name.slice(1));;
} else {
        document.write('Sorry, that login info appears to be incorrect. Please try again');
}

Suppose you have a username and password field on a login screen where you need to authenticate a user's credentials before logging in to their account. To do something like this you need to test the information the user supplies to the information stored in a database. This example is a static approach. In many cases, you will be comparing information not hardcoded in a variable as I have so that’s something to keep in mind.

First, we defined a variable for a username and a password. In a real-world setting these variables would be defined based on the user enters into a form. Next, we write our if statement which tests to see if the username and password match our variables. In this case, our credentials do indeed match. Since the condition is true I have written a welcoming message to the user who logged in successfully. You may also note a few character-based changes set in place simply to capitalize on the first character of the username. If the condition weren’t true I have written another message to notify the user that their credentials were incorrect and that they should try to login again.

Extending the if statement

Chaining if statements are as easy as adding another line of code.

if ( name === 'andy' && password === 'webcrunchblog' ) { 
    document.write('Welcome ' name.charAt(0).toUpperCase() + name.slice(1));;
} else if ( name === 'andy' && password === '') {
        document.write('Whoops, looks like you forgot to enter a password. Please try again');
} else {
       document.write('Sorry, that login info appears to be incorrect. Please try again');
}

Here I’ve added another scenario in the event that the user leaves a login form password field blank. If the variable set upon submit is an empty string the code outputs a message saying the password field was blank.

While this is an extremely simple example it helped me understand the different types of statements you can introduce based on specific interactions from a given user. I realized you have to think not only about a successful login but also about what happens if something goes wrong. There are a lot of outcomes but JavaScript comes to the rescue.

The do-while statement

Pressing forward I will uncover what is known as loops inside JavaScript. These expressions are used to programmatically cycle through given tests to declare whether a value is true or false. The end result can be any value but it’s all in how you set up the conditions.

The do-while loop is a post-test loop. By this, I mean that it tests a condition only after the code inside the loop has been executed. The basic body of the loop is always executed at least once before the expression is tested. This all confused me greatly until I saw it in action so I’ll try to do the same for you. Here’s a basic example:

do {
   statment
} while (expression);

And here’s an example that might actually make some sense:

var numberOfVotes = 0;

do {
numberOfVotes += 2;
} while (numberOfVotes < 10);

document.write(numberOfVotes); // 10

In this example, the loop continues as long as the variable numberOfVotes is less than 10. It increments by 2 until the final value of 10 is reached.

A do-while loop is most often used to test a condition once before continuing through a loop. If the condition is false the loop never runs and if it’s true it will.

The while statement

Unlike the do-while statement which is a post-test loop, the while statement is a pre-test loop, meaning that a condition is evaluated only after the code inside the loop has finished executing. Because of this, it’s possible the loop will never actually execute.

The syntax is simple:

while(expression) statement

An actual example:

var numberOfVotes = 0;
while(numberOfVotes < 100) {
    numberOfVotes += 2;
}

document.write(numberOfVotes); // 100

Here the variable numberOfVotes kicks off at 0 and is incremented by two each time in the loop. This is true so long as the variable is less than 100. Once it reaches 100 the loop ends.

The for Statement

The for statement is another pretest loop with added functionality for variables before entering a loop and running the code immediately following the looping process.

The syntax is as follows:

for (initialize; expression; post-loop expression) statement

An actual example:

var numberOfVotes = 10;

for ( var i = 0; i < numberOfVotes; i++) {
    document.write(i); // 0123456789 
}

Here I assign our numberOfVotes variable the number ten. Using the for statement I define a new variable i which we will use for the looping process. In the end I output the result of the looping process by writing document.write(i);.

If you were to write a for loop long hand it would involve using a while loop like this:


var numberOfVotes = 10;
var i = 0;

while (i < numberOfVotes) {
  document.write(i);
  i++;
}

This way works but it’s a bit hard to read and a little cumbersome. Most of the time you will see the first example shown above. Here is a reminder and another example of it to give you another perspective:

var peopleAttending = 300;

for (var i = 0; i < peopleAttending; i++) {
    document.write('Attendee ' + i '<br/>');
}
// Outputs from Attendee 1 - 299
/*
Attendee 1
Attendee 2
..
Attendee 299
*/

Remember that with programming everything starts at zero. This explains why the loop ended at 299 and not 300.

The for-in Statement

The for-in statement is a strict iterative statement. It is used to enumerate the properties of an object. [1]

The syntax looks like this:

for (property in expression) statement

An example:

for (var propName in window) {
    document.write(propName + '<br/>');
}
// Output
/*
close
stop
focus
blur
...
dispatchEvent
*/

This example outputs all the properties of the BOM (browser object model) window. These are all objects that get output in no specific order as it varies per browser. With these, you can use JavaScript to target, manipulate, and more. The for-in statement will throw an error if the variable representing the object to iterate through doesn’t exist or is undefined.

The switch Statement

I briefly mentioned chaining the if statement before using a syntax like this:

if (condition) {
    // output
} else if (condition) {
    // another output option
} else {
    // output if all evaluates to false
}

Say you have a lot more conditions to test and there’s no way around it. Now you could write as many if statements as you like but your code gets long and isn’t as efficient nor easy to read. The switch statement comes to the rescue. There are some new syntax patterns to be aware of but overall the code is much more valuable than writing what seems like an endless amount of if statements.

The syntax for a switch statement looks like this:

switch (expression) {
    case value : statement
    break;
    case value : statement
    break;
    case value : statement
    break;
    default : statement
    break;
}

And here’s a real example to more sense of things:

var name = "Andy";

switch(name) {
    case "Andy" : document.write("Hi, Andy");
    break;
    case "Jack" : document.write("Nope, you're not Andy");
    break;
    case "Ryan" : document.write("You can't be Andy");
    break;
    default : document.write("Your name is unknown");
    break;
}

Here I’m simply validating that my name (Andy) is the right name given to the name variable. The switch statement tests the cases and outputs the statement I wrote giving me feedback that the very first case in the switch statement was the correct one. The break; bit of code you see tells JavaScript to stop the test and exit. When the code is run it will test from top to bottom. Once it finds a match it will output and exit the program otherwise if it doesn’t find a match the default case will run.

The switch statement is very useful when you need to perform a large number of tests across a large collection of data. You could use a switch statement for things like login verification and redirection or if you want specific content to appear upon visiting a webpage based on the user who visits. The possibilities really are endless.

Another example or grins:

var totalScore = 100;
var message = "";

function score(x) {
  if(x <= 50) {
    document.write('Simply terrible...');
  } 
}

switch(Math.floor(totalScore)) {
    
    case 100 : message = "Perfect Score!";
    break;
    case 90 : message = "Great Job!";
    break;
    case 80 : message = "Good Work!";
    break;
    case 70 : message = "Average";
    break;
    case 60 : message = "Try Harder!";
    break;
    case 50 : message = "Fail!";
    break;
    default : score(totalScore);
    break;
}

document.write(message);

This code is meant to be a grading scale type of test. If a user’s score is within a given range a message is output based on the score. If the score is below 50 I have written a function that executes as the default part of the switch statement. So no matter the value entered, so long as it’s between 0 and 100 gets a custom message output.

Wrapping Up

I originally wanted to explore both conditional statements and function in this post but I decided to devote more attention to conditional statements since they are extremely important to understand in order to really grasp JavaScript. I myself have struggled with getting used out of some of these different types of statements but as long as you know the basics you can always reference the code online or from a good book on JavaScript. The next post will cover JavaScript functions. I hope you’ll continue on our journey to REALLY learn JavaScript together.

References

[1]Professional Javascript For Web Developers

The Series So Far

Link this article
Est. reading time: 12 minutes
Stats: 587 views

Categories

Collection

Part of the Beginner JavaScript collection

Products and courses