0% found this document useful (0 votes)
102 views

Decision Control, For Loop and Operators

1) The document discusses different types of loops in JavaScript including for, while, and do-while loops. It provides the syntax and examples of each loop type. 2) Key loop constructs covered are the for loop, which is best when the number of iterations is known. The while loop executes until a condition fails, and do-while always executes the block at least once before checking the condition. 3) Examples are given to illustrate each loop type, such as a for loop counting to 5 and a do-while displaying a message with a condition that is initially false.

Uploaded by

Revati Menghani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

Decision Control, For Loop and Operators

1) The document discusses different types of loops in JavaScript including for, while, and do-while loops. It provides the syntax and examples of each loop type. 2) Key loop constructs covered are the for loop, which is best when the number of iterations is known. The while loop executes until a condition fails, and do-while always executes the block at least once before checking the condition. 3) Examples are given to illustrate each loop type, such as a for loop counting to 5 and a do-while displaying a message with a condition that is initially false.

Uploaded by

Revati Menghani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Section-5: Decision Making using if and switch

5.1 Block and Compound Statement


A statement in a code which states that something will happen with this line is called the
single statement. A simple expression, assigning value or check the condition are the example
of single statement.

When we want to execute the more than one statements in response of the condition which
is true then these types of statements are surrounded by curly braces. The effect of
wrapping which wrap the many statements as a single statement is called the compound
statement.

A block is a set of statements enclosed in braces as single statement. It is used with the
decision making or looping statements. If condition is true then whole block will be executed
otherwise whole block will be skipped.

The decision-making construct like if, else, switch executes the blocks once if condition is true
or skip the block. The looping construct repeatedly executes the block until condition is false
or loop is not terminated.

5.2 Control Structures in JavaScript JavaScript has a similar set of control structures like the
other languages such as c, c++ and Java. conditional statements are supported by if and else
nal
statements as defected :

1) if (statement)specify a block of code to be executed, if the specified condition is true

2) else (statement) specify a block of code to be executed, if the same condition is false

3)else if (statement) specify a new condition to test, if the first condition is false

4) switch (statement) specify many alternative blocks of code to be executed


Syntax for if()
if (condition

block of code to be executed if the condition is true

else

block of code to be executed if the condition is false

For example:

<html>

<head>

<script type="text/javascript">

var a= prompt("Enter a number for a");

if(a >=50 )

document.write("Number is greater");

else

document.write("Number is less than 50");

</script></head></html
Nested if

The ‘else if’ Statement is used to specify a new condition if the first condition is false.

syntax:

if (condition1)
{
block of code to be executed if condition1 is true
} else if (condition2)
{
block of code to be executed if the condition1 is false and condition2 is true
} else
{
block of code to be executed if the condition1 is false and condition2 is fals
}

For example:

<html>
<head>
<script type="text/javascript">
var a= prompt("Enter a letter");
if(a=='R' || a=='r' )
{
document.write("Red colour");
}
else if(a=='P' || a=='p')
{
document.write("Pink Colour");

}
else if(a=='B' || a=='b')
{
document.write("Blue colour");
}
else
{
document.write("Colour is not in the list");
}
</script>
</head>

</html>
The switch statement
The switch statement is used to select one of many blocks of the code to be executed in a program
described below. The switch expression is evaluated once and the value of the expression is
compared with the values of each case. If there is a match found, then the associated block of code
is executed otherwise default code block is executed.

Syntax:

switch (expression)

{ case n: code block

break;

case n: code block

break;

default: default code block}

For example:
<html>
<head>
<script type="text/javascript">
var week= Number(prompt("Enter week number(1-7): "));
switch(week)
{
case 1:
document.write("Monday");
break;

case 2:
document.write("Tuesday");
break;

case 3:
document.write(" Wednesday");
break;

case 4:
document.write(" Thursday");
break;
case 5:
document.write("Friday");
break;

case 6:
document.write("Saturday");
break;

case 7:
document.write(" Sunday");
break;

default:
document.write("Unkown day");
}
</script>
</head>

</html>

Answer the following questions:


Q. 1: Explain if () condition with give some examples.
Q. 2: What is the purpose of the switch statement? give some examples.
Q. 3: What is the purpose of the break statement?
Q. 4: Write a JavaScript program that accepts inputs two integers and display the
larger one.

Fill in the blanks


(a) Switch statements start with ____keyword.
(b) if none of the case values in the switch statement match then ............. is
executed.
(c) ......................... , and are all conditional statements that can be used in
JavaScript
(d) ......................... should not be used as a variable name because it is a reserved
keyword in JavaScript.
(e) Js has two types of variable scope ..................... & ...................... .
(f) JavaScript variables are declared using ...................... as the keyword.

Section-6: Looping Structure


6.1 Loops
Loops can be used to execute the same code over and over again,
particularly useful
when dealing with arrays as shown in figure 3.3. JavaScript supports
different kinds of loops described below:
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• while - loops through a block of code while a specified condition
is true
• do/while - also loops through a block of code while a specified
condition is true

For Loop
The for loop is best suited when you already know the number of times
the statements should be executed. the loop executes until the condition
becomes false.

Syntax:
for(initialization; condition; increment)
{
//statements
}
When a for loop executes
1. The initializing expression is get executed and this expression usually
initializes one or more loop variables.

2. The condition expression is evaluated. if the value of condition is


true, the loop statements are executed. if the value of condition is
false, for loop terminates.
3. The increment expression executes and increments the value by the
specified step value.
4. The statements execute, and control returns to step 2.
Example

<!DOCTYPE html>
<html>
<body>
<p> For loop Example</p>
<script type=”text/javascript”>
for (i = 0; i < 5; i++) {
document.write("Hello Life! You are so Good" +"<br>"); }
</script>
</body>
</html>
Example explained
From the above example we can notice that

statement 1 sets a variable before the loopstarts (var i = 0).

Statement 2 defines the condition for the loop to run (i must be less
than5).

statement 3 increases a value (i++) each time the code block in the loop
has beenexecuted. in JavaScript, we normally use statement 1 to initiate
the variable used in theloop (i = 0). although, this is not always the case,
JavaScript doesn’t care. statement 1is optional.

We can initiate many values in statement 1 (separated by comma):

The while loop:

The While loop is another commonly used loop in JavaScript. the


purpose of the while loop is to execute a block of statements over and
over again until the condition fails. it is best suited in a scenario where
we don’t know in advanced as to how many times the loop will be
executed as shown in figure 6.2.
Syntax for while loop
var i = 1;
while (i < 10)
{
alert(i);
i = i + 1; / i++;
}

We can write the same program which was discussed in For Loop
section with the While loop. Major difference is For loop is easy to
write with one line syntax whereas in while loop the parts of loop are
written separately.

Example: This is the same example of For Loop Section but executed
with while loop rather than for loop.
<!DOCTYPE html>
<html>
<body>
<p>While loop Example</p>
<script type=”text/javascript”>
var i=0;
while( i <5)
{
document.write("Hello Life! You are so Good" +"<br>");
i++;
}
</script>
</body>
</html>

Another example

<html>
<body>
<p> While loop Example</p>
<script type=”text/javascript”>
var t = prompt("Enter Table to calculate up to 10");
x = parseInt(t);
var i=1;
while( i <= 10)
{
value = x *i
document.write( x +" * " + i + " = "+value +"<br>");
i++;
}
</script>
</body>
</html>

do While loop

This is another kind of loop and different from the for loop and the while
loop. this loop will execute the statement at least once that is the
statements inside the loopwill always get executed at least once, even if
the condition is false. the condition is checked happens after the loop
has been executed. the loop will continue to execute orwill terminate
according to on the condition as shown in figure 6.3. do while syntax:
var i = 1;
do {
alert(i);
i = i + 1;
} while (i<10)
Example: This example shows the difference between while and do-while.

<!DOCTYPE html>
<html>
<body>
<p> Do-While loop Example</p>
<script
type=”text/javascript”>
var i=1;
while( i < 0)
{
document.write("Hello Life! You are so Good" +"<br>"); i++;}
</script>
</body></html>

We use the condition which is false initially. If you use this condition in
while loop it won’t be executed but in do-while it will execute at least
once.

Using do-while loop


<!DOCTYPE html>
<html>
<body>
<p> Do-While loop Example</p>
<script
type=”text/javascript”>
var i=1; do
{
document.write("Hello Life! You are so Good" +"<br>"); i++;
}while( i < 0)
</script>
</body>
</html>

Output:
Hello Life! You are so Good
Example: This is the same example of For Loop Section but executed
with while loop rather than for loop.
Example: Calculate the factorial of a value entered by the user.

<html>
<body>
<p> Do-While loop Example</p>
<script>
var d = prompt ("Enter number to calculate factorial"); n =
parseInt(d); var f=1; var i=1; do
{ f = f* i;
i++;
} while( i <= n);
document.write("factorial of value " + n + " is " + f );
</script>
</body>
</html>
Section-3: Operators
3.1 Operators
An operator is a symbol that is used to perform an operation. in
this section we will learn how to use JavaScript operators.

1) Assignment Operators
Assignment operators help in assigning values to a variable. the
following table shows
how assignment operators work in JavaScript.here we consider two
variables x and y assuming x=90 and y=20. upon execution,
theassignment operator will generate the following results.
operator example Same as result

= x=y x=90

+= x+=y x=x+y x=110

-= x-=y x=x-y x=70

*= x*=y x=x*y x=1800

/= x/=y x=x/y x=4.5

%= x%=y x=x%y x=1

the equal to (=) sign is used to assign a value to a variable.


2) Arithmetic Operators
There are following arithmetic operators supported by JavaScript

operator description example

+ adds two operands a + b will give 30

- Subtracts second operand from the first a - b will give -10

* Multiply both operands a * b will give 200

/ divide numerator by denominator b / a will give 2

Modulus operator and remainder of after an integer


% division b % a will give 0

language: assume variable a hold 10 and variable b holds 20 then:

++ increment operator, increases integer value by one a++ will give 11

decrement operator, decreases integer value by one


-- a-- will give 9

There are following comparison operators supported by JavaScript


language.
Assume variable a hold 10 and variable b holds 20 then
3) Comparison Operators

operator description example


Checks if the values of two operands are equal or
not, if yes then the condition becomes true. (a == b) is
==
not true.

Checks if the values of two operands are equal or not,


if values are not equal then condition becomes true. (a != b) is
!=
true.

Checks if the value of left operand is greater than the


value of right operand, if yes then the condition (a > b) is
>
becomes true. not true.

Checks if the value of left operand is less than the


value of right operand, if yes then the condition (a < b) is
<
becomes true. true.
checks if the value of left operand is greater than or
equal to the value of right operand, if yes then the (a >= b) is
>=
condition becomes true. not true.

checks if the value of left operand is less than or equal


to the value of right operand, if yes then the
condition becomes true. (a <= b) is
<=
true.

4) Logical Operators
There are following logical operators supported by JavaScript language.
assume variable a hold 10 and variable b holds 20 then:
operator description example

called logical and operator. if both the operands are non-


&& zero then condition becomes true. (a && b) is true.

called logical or operator. if any of the two operands are


|| non-zero then the condition becomes true. (a || b) is true.

called logical not operator. use to reverse the logical state


of its operand. if a condition is true then logical not
! operator will make it false. ! (a && b) is false.
5) Bitwise Operators
There are following bitwise operators supported by JavaScript
language. assume variable a hold 2 and variable b holds 3 then:

operator description example

& called bitwise and operator. it performs Boolean and (a & b) is 2.


operation on each bit of its integer arguments.

called bitwise or operator. it performs Boolean or operation on


| each bit of its integer arguments. (a | b) is 3.

called bitwise XOR operator. it performs Boolean exclusive


or operation on each bit of its integer arguments. exclusive or
means that either operand one is true or operand two is true
^ (a ^ b) is 1.
but not both.

called bitwise not operator. it is a is a unary operator and


~ operates by reversing all bits in the operand. (~b) is -4.

called bitwise shift left operator. it shift all the bits in its first
operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. shifting a value
left by one position is equivalent to multiplying by 2, shifting
two positions is equivalent to multiplying by 4 so on.
<< (a << 1) is 4.
called bitwise shift right with sign operator. it shift all the bits
in its first operand to the right by the number of places
specified in the second operand. The bits filled in
on the left depend on the sign bit of the original operand, in
order to preserve the sign of the result. If the first operand is
positive, the result has zeros placed in the high bits; if the first
operand is negative, the result has ones placed in the high bits.
>> shifting a value right one place is equivalent to dividing by 2 (a >> 1) is 1
(discarding the remainder), shifting right two places is
equivalent to integer division by 4, and soon.

called bitwise shift right with Zero operator. this operator is


just like the >> operator, except that the bits shifted in on the
>>> left are always zero, (a >>> 1) is 1.

6) Assignment Operators
There are following assignment operators supported by JavaScript
language:
operator description example

add and assignment operator, it adds the right operand


to the left operand and assign the result to the left c += a is equivalent to c =
+= operand c+a

subtract and assignment operator, it subtracts right


operand from the left operand and assign the result to c -= a is equivalent to c =
-= the left operand c-a

Multiply and assignment operator, it multiplies the


right operand with the left operand and assign
c *= a is equivalent to c =
*= the result to the left operand c*a
divide and assignment operator, it divides the left
operand with the right operand and assign the
c /= a is equivalent to c =
/= result to the left operand c/a

Modulus and assignment operator, it takes modulus c %= a is equivalent


using two operands and assign the result to the left to c = c %
%= operand a

7) Special Operator
Conditional operator (? :)
This operator first evaluates an expression for a true or false value and
then execute one of the two given statements depending upon the result
of the evaluation.
operator description example

if condition is true? then value X : otherwise value y


?: conditional expression

typeof operator
the typeof is a unary operator that is placed before a single operand,
which can be of any type. its value is a string indicating the data type of
the operand. the type of operator evaluates to “number”, “string”, or
“Boolean” if its operand is a number, string, or Boolean value and
returns true or false based on the evaluation.
here is the list of return values for the type of operator:

Type String returned by type of

number “number”

string “string”

boolean “boolean”

object “object”

Function “function”

Undefined “undefined”
null “object”

Operator Precedence and Associativity


When an expression contains numbers of operators and operand and the
order of evaluations is ambiguous then operator precedence and
associative rules comes in the picture.

• Operator Precedence: It refers to the way in which the operator


binds to its operand. It determines the what operation is done
first over the another. In precedence operator’s hierarchy is
formed and operator with highest precedence stood at the top.
Forexample, multiplication operator has the higher precedence
than addition so multiplication bind tightly than addition with
operand.

• Operator Associativity: It refers to the order in which an


operator evaluates its operand i.e. from left to right or right to
left. When an expression has operator with equal precedence
then association normally is left to right.

For example, the expression 6 + 3 * 10 / 2 will be written as ( 6 +( ( 3 *


10) / 2 ) ) and operator will be evaluated from left to right.
3.2 Numerical Calculation
JavaScript has mathematical capabilities like addition, subtraction,
multiplication and division. These operators perform the operation and
return the result. For example, in JavaScript calculate the total amount
in a code.
var total
amount;
total
=amount
=20+ 5 *7;
document.
write (total
amount);
1. First, you declare a variable, total amount, to hold the total cost.
2. In the second line, you have the code 20 + 5 * 7. This piece of
code is known as an expression. When you assign the variable
total amount the value of this expression, JavaScript
automatically. Calculates the value of the expression (55) and
stores it in the variable.
3. Notice that the equals sign tells JavaScript to store the results of
the calculation in the total amount variable. This is called
assigning the valueof the calculation to the variable, which is
why the single equals sign (=) is called the assignment operator.
4. Finally, you display the value of the variable in an document.
Write() method.

The increment and decrement operators, are represented by two plus


signs (++) and two minus signs (--), respectively.
• Using the increment and decrement operators shortens this to
myVal++; myVal -- ;
The result is the same — the value of myVal is increased or
decreased by one
• When the ++ and -- are used on their own, as they usually are, it
makes no difference where they are placed, but it is possible to
use the ++ and -- operators in an expression along with other
operators. For example:
myVar = myVal ++ - 30;
This code takes 30 away from myVal and then increments the
variable myVal by one before assigning the result to the variable
myVar.
• If instead you place the ++ before and prefix it like this:
myVar = ++ myVal - 30;
First, myVal is incremented by one, and then myVal has 30 subtracted from it.

3.3 Built-in Functions/Object for Numerical Calculation


1) isNaN(() This method checks whether passing argument
is a number or not. It returns true or false value as a
result.
For example
document.write( isNaN(4) ) // will return false.
document.write( isNaN(“4”) ) // will return false.
document.write( isNaN(“four”) ) // will return true.

2) valueOf(): This method return a number of a given


variable. For example var x =345;
x.valueOf() // will return 345;
JavaScript Math object helps developer to perform the
common mathematical operations. Here are some common
methods discussed with example.
3) Math.round(x): It returns the rounded value of passing
number to its nearest integer.
For example: Math.round(6.7) //returns 7
Math.round(6.4) //returns 6
Math.pow(x,y): It returns the power of x based on y.
4) For example:
Math.pow(3,4) //returns 81
Math.sqrt(x): It returns the square root of x.
For example:
Maths.sqrt(81) //returns 9

5) Math.ceil(x): It returns the greater or equal to integer


value of x.
Math.ceil(6.4) //returns 7
Math.ceil(4.1) //returns 5
6) Math.floor(x): It returns the less or equal to integer value
of x.
Math.floor(6.4) //returns 6

3.3 Basic String Operations


A major operation that can be performed is concatenation which can be
performed by placing + sign between two strings. This has been
discussed in previous sections.
Some Common Methods for String Operation
Length(): It returns the length of a string including white
space(s). For example var str = "Hello javaScript";
document.write(str.length; // it returns the 16.

Search(): It returns the starting location of passing string otherwise


returns -1.
var str = “This is my first script in JavaScript”
str.search(“script”); //returns 17
Substring(): It extract the substring by taking the starting and ending
position as argument. You can omit ending position then it will extract
the string from starting position to end of the string.
var str = “This is my first script in JavaScript”
str.substring(7,16) // returns “my first” as
substring

3.4 Mixing Numbers and Strings


• A expression which is mixing of number and strings is generally
requires when we have to describe the meaning of displayed
value to the user.
• If we have to display total marks and percentage of the student
then we have to specify which value is for the total marks and
which value is for the percentage.
• Mixing of number and string is easy. You have to join the string
and numeric value together by using + sign. It does not perform
the calculation rather concatenation the whole expression. For
example, following code document.write (“Total Marks = “ +
450); will display the “Total Marks = 450” message on the
document.

3.5 Data Type Conversion


JavaScript automatically convert the data when two different types are
used in the expression and evaluate the expression. This act is called
type conversion. There are two ways in JavaScript to convert the type:

Implicit Type Conversion


This conversion is done by JavaScript automatically when expression is
evaluated if there are two different types are given which are not
compatible to perform the operation. Following are the implicit
conversion examples:
• If one value is number and second is string with arithmetic
operator given in expression then it converts string to number
and perform the arithmetic operation. For example, 14 + “”
returns the 14 as result, 30 * “5” returns the 150 as result.
• If both operands are string with arithmetic operator then both are
converted to number and result is produced. For example, “14”
+ “15” returns 29 as result If one value is null in arithmetic
operations then it is converted to integer value 0. For example,
null + 5 returns the 5 as result.
• If one value Boolean in arithmetic operation then it is converted
to 0 or 1 according to the given value. For example, true + 5
returns 6 as result, false+5 returns 5 as result.
• If value cannot be converted to other type then NaN (Not a
Number) value is returned.

Explicit Type Conversion


This type of conversion is done by developer by using the inbuilt
method of type conversions. Following sections discuss the different
ways for explicit conversion.

3.6 ) Converting Number


Number(): This method is used to convert any type to number type.
For example,

• Number (“40”) convert string value “40” to 40.


• Number (null) convert null to 0
• Number (“”) convert empty string to 0
• Number(false) convert false to 0
• Number(“type”) it cannot be converted so return NaN

parseInt(): This method returns the integer value by


accepting two argument First argument is string having numeric
value.
• Second argument is radix which specify the returning value
presentation in a specific number system.
• If radix is omitted then either it checks the beginning of string
for radix. For example, if string begins with “ox” then radix is
16 (Hexadecimal), if string begins with “o” then radix is 8
(octal) otherwise radix is taken 10 (decimal).
For example:
parseInt
(“10”)
returns10

parseInt
(“40.33”)
returns 40

parseInt (“19
Covid”)
returns 19

parseInt
(“Covid 19”)
returns NaN

parseFloat(): This method returns the integer value by accepting


one string argument. It parses the string for conversion for number. If
number exists up to end then it converts the number and return
otherwise returns NaN.
For example:
parseFloat(“23”) returns
23
parseFloat(“23.55”)
returns 23.55
parseFloat( “23 yard”)
returns 23
parseFloat( “yard 55”)
returns NaN

eval():This method accept the JavaScript expression as an string


argument. It then evaluates the expression and return the result after
execution. If no result is obtained the it returns undefined as a result.
For example: eval (“ 8*4/2”) returns 16 as result

Converting String
String() method is used to convert any type to string value whereas
possible by accepting one argument.
• If argument is integer type then it converted to string. For
example, string (40) converted to “40”
• If argument is Boolean type then string(false) is converted to
“false”.
• If argument is null then string(null) is converted to “null”.

Converting Boolean
Boolean() method convert any type to Boolean type which is supported.

• If passing value is integer then Boolean(25) returns true.


• If passing value is null then Boolean(null) returns false.
• If passing value is string then Boolean(“Hello”)) returns true.

Answer the following questions:


Q.1: What is an operator?
Q.2: What is an associativity of operator?
Q.3: What is an precedence of operator
Q.4: What are the major types of operators supported by JavaScript?

Q5) What is the difference in the outputs that you get when you use the following
operators =; = = ;
Q.9: explain what you understand by modulo operator.

Q.10: specify four types of operators that can be used in JavaScript.

Q.11: What is conditional operator?

Fill in the Blanks

1) If x = 24 and y = 3 then the output of x*=x/y is ............................


2). if x = 25 and y =3 then the output of x+=y is ............................ .
3) ............................ and ............................ are all logical operators
used in
JavaScript
4) if x = 14 and y = 3 then the output of x mod y is ............................
.
5) if x = 15 and y =3 then the output of x%y is ............................ .
6) Plus sign is used to ............................ number and strings.

You might also like