ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Beginner JavaScript Tutorial Series: Program Logic Statements - if....else, while, for, and switch Statements

Updated on March 22, 2014

Recap of the First Tutorial in this Series

In the first tutorial in this series entitled, "A Beginner JavaScript Tutorial Series: An Introduction to JavaScript - Identifying Basic Requirements". we covered some very basic items to see that the environment was appropriate for "doing" JavaScript.

We checked that JavaScript was enabled in the browser by creating a short HTML file which included a JavaScript <script> block which performed a Hi there write to the screen. We discussed comments in JavaScript which can be good placeholders to new features to be added. Or a place to put a question during the learning process.

Variables were introduced and their dynamic nature discussed. The dual purpose "+" (plus sign) was introduced not merely as an arithmetic operator but also as a concatenation operator. We used these concepts to introduce the notion of a function.

Goals for this Tutorial

The goal for this tutorial is to introduce the main logical constructs which JavaScript uses: if...else, for, while, and switch. This is done for several reasons. First, most computer initiates by the time they start to learn JavaScript have seen these statements in learning one or more computer programming classes, so belaboring the process is somewhat wasted time. Secondly, from experience in teaching, I find that once introduced, with repetition as the statements are used even newcomers quickly identify with their use. Also having logic introduced early on provides more of a framework in which to introduce other of the language elements in less time.

The if...else Statements

There are three variations of the if statement:

  • if (condition is true) { execute some code }
  • if (condition is true) { execute some code} else { execute alternative code}
  • if (condition1 is true){ execute some code} else if (condition2 is true) { execute code} else {execute code if neither condition1 or condition2 is true}

The first two forms of the if statement are rather straight forward as examples in the snapshots illustrate.

The third form it should be noted can be continute beyond two conditions

consider the second line:

.....else {executte code if neither condition1 or condition2 is true} could be substituted by

.....else if (condition3 is true) {execute code if neither condition1 or condition2 is true}

.....

There is a simpler way to handle the third form of this statement. It is in using the switch statement.

The Simple if... Statement

The code illustrating a simple if statement.
The code illustrating a simple if statement.
The output of the web page. Note the use of == (comparison) rather than = (assignment).
The output of the web page. Note the use of == (comparison) rather than = (assignment).

A Simple if...else... Statement

In this example the value of the variable x is equal to 8. The comparison fails and the code following the else is executed.
In this example the value of the variable x is equal to 8. The comparison fails and the code following the else is executed.
The statement following the else is executed.
The statement following the else is executed.

An if..else...if Statement

Code for an if...else...if... statement.
Code for an if...else...if... statement.
The value of the first comparison fails. Thus the else clause is evaluated. The else clause is evaluated.
The value of the first comparison fails. Thus the else clause is evaluated. The else clause is evaluated.

The Exactly Equals === Comparison Operator

The following example illustrates a point that is generally not found in other languages, "the exactly equals comparison operator, ===. Not only do the values have to be equal they must also be of the same type. In this case the variable x is a string being compared to an integer value.

As we have equals (==) comparison operator and (===) the exactly equals operator. We also have a not equals comparison operator, (!=) and a not exactly equals operator (!==) meaning that the operands are of different types.

Using the === Comparison Operator

Note the comments in the code the string 8 does not match the integer 8.
Note the comments in the code the string 8 does not match the integer 8.
Ouput from the preceding snapshot.
Ouput from the preceding snapshot.

The Switch Statement

The switch statement allow you to avoid using a cumbersome if...else.....if....else.... construct.

The format of the switch statement looks like:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2

}

The details are as follows. The reserved keyword switch is used with a parameter expression. The value of that expression is tested against the first case. If that compariosn evaluates to true then the code block is evaluated. If it evaluates to false the comparison is made with the next case. If that evealuates to true then the code block in that case is executed. If it evaluates to false then the comparison is made with the next case. Often a default case is specified. If all case comparisons fail the defualt case is executed. The last statement is each cas is generally a break statement. It ends the switch statement and execution continues at the next statement after the end of the switch statement.

The snapshot shows a comparison for the day of the week.

Switch Statement Example

We could add a default case here if the value given for the switch was not one of 0 through 6. The case might read: default: document.write("I don't know what day it is");
We could add a default case here if the value given for the switch was not one of 0 through 6. The case might read: default: document.write("I don't know what day it is");

Loops in JavaScript

JavaScript supports four different looping constructs. We will disucss three of them here:

  • for - loops through a block of code a number of times
  • while - loops through a block of code while a condition is true
  • do/while - loops through a block of code while a specified condition is true. The do/while loop always executes at least one.


The for Loop in JavaScript

The for look has the following structure:

for (statement #1; statement #2; statement #3)
{
the code block to be executed
}

  • statement #1 is an initialize. It is executed before any other statement.
  • statement #2 is a conditional statement. It determines if the code block should be executed.If it evaluates the false even the first time the statement is encountered the code block is never run
  • statement #3 is executed after the code block is run.

The for Loop

A simple for loop. The variable is initialized to 0. The loop will continue printing the statement until i=5.
A simple for loop. The variable is initialized to 0. The loop will continue printing the statement until i=5.

The While Loop

The syntax of the while loop is as follows:

while(condition is true){

execute the code block

}

The condition must somehow be modified within the loop or an endless loop wil occur as in this simple example.

var i = 0;

while(i<10) {

document.write("the number is" + i + "<br>");

}

The variable i is never modified. Thus, the condition in the while loop would be true forever.

To have this loop end you should modify the value of the variable i. The following code wouuld terminate after printing out 10 statements.

var i = 0;

while(i<10) {

document.write("the number is" + i + "<br>");;

i = i + 1;

}


The while Loop

A simple while loop.
A simple while loop.

The do....while Loop

The syntax of the do while loop is as follows:

do {

code block

} while (condition is true.

This code block is guaranteed to run at least once. It the snapshot an "error" was intentionally made and the variable i was initialized to 10 rather than the intended value of 0.

do
{
x=x + "The number is " + i + "<br>");
i= i + 1;
}
while (i<10);

A Simple do.....while Loop

A "mistake" was made here in setting the initial value of i to 10 rather than 0. This illustrates that the loop is always executed at least once.
A "mistake" was made here in setting the initial value of i to 10 rather than 0. This illustrates that the loop is always executed at least once.

Wrap Up and What's Next

We have demonstrated the various if..... statements, the switch statement, and three out of the four looping constructs available in JavaScript. The fourth looping construct known as the for/in loop will be covered in a future tutorial as it deals with more advanced materials. We introduced our first comparison operators, the == (is equal) and === (is exactly equals).

The next tutorial will consist of a number of items:

  • some built-in functions
  • the full set of assignment operators
  • the full set of comparison operators
  • the Boolean types

Was This Tutorial Understandable?

Cast your vote for Please rate this tutorial for clarity and completeness.
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)