Docsity

JavaScript Flow Control & Loops: if, switch, while, for, Slides of Introduction to Computing

Partial preview of the text

Download JavaScript Flow Control & Loops: if, switch, while, for and more Slides Introduction to Computing in PDF only on Docsity!

CS101 Introduction to Computing

Lecture 23

Flow Control & Loops

(Web Development Lecture 8)

During the last lecture we had a discussion on Data Types, Variables & Operators

  • We found out about JavaScript data types
  • About variables and literals
  • We also discussed several operators supported by JavaScript

Variables

  • Variables give us the ability to manipulate data through reference instead of actual value
  • Variables are containers that hold values

Declaring Variables

Although JavaScript allows variable declaration, it does not require it - except in the case when we want to declare a variable being local (more on local variables later in the course!)

JavaScript Operators

JavaScript has numerous operators, classified in many categories. We will look at only a few of them belonging to the following categories:

  • Assignment operators
  • Arithmetic operators
  • Comparison operators
  • Logical operators
  • String operators

comments let

the code speak

for itself!

Today’s Lecture: Flow Control & Loops

  • We’ll try to understand the concept of flow control using the “if” and “switch” structures
  • And also the concept behind the “while” and “for” looping structures
  • We will solve simple problems using flow control and loop structures

Flow Control

JavaScript Flow Control Structures

if … else

switch

if: Example 1

if ( day == “Sunday” ) bhola = “Cool” ;

Set the value of the variable ‘bhola to ‘Cool’ if the ‘day’ is equal to ‘Sunday’ 14

The condition enclosed in parentheses (^) semicolon

if: Example 2

if ( day == “Sunday” ) { bhola = “Cool” ; mood = “Great” ; clothing = “Casual” ; }

Set the value of the variable ‘bhola to ‘Cool’, ‘mood’ to ‘Great’, and ‘clothing’ to ‘casual’ if the ‘day’ is equal to ‘Sunday’

16

These curly braces group the multiple statements into a single compound statement

if: Example 2

if ( day == “Sunday” ) { bhola = “Cool” ; mood = “Great” ; clothing = “Casual” ; }

Set the value of the variable ‘status’ to ‘Cool’, ‘mood’ to ‘Great’, and ‘clothing’ to ‘casual’ if the ‘day’ is equal to ‘Sunday’

17

Note: No semicolon after the closing curly brace

Compound Statements

  1. This is done simply by enclosing any number of statements within curly braces, { }
  2. NOTE: Although the statements within the block end in semicolons, the block itself doesn’t

if: Example 3

if ( (day == “Sunday”) || (day == “Saturday”) ) {

bhola = “Cool” ; mood = “Great” ; clothing = “Casual” ;

}