0% found this document useful (0 votes)
13 views64 pages

Js Sem2 Lec3

The document is a lecture on JavaScript covering conditionals, loops, and data structures like arrays and objects. It explains various conditional statements such as if-else, switch, and the ternary operator, as well as different types of loops including for, while, and do-while. Practical examples illustrate how to use these concepts effectively in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views64 pages

Js Sem2 Lec3

The document is a lecture on JavaScript covering conditionals, loops, and data structures like arrays and objects. It explains various conditional statements such as if-else, switch, and the ternary operator, as well as different types of loops including for, while, and do-while. Practical examples illustrate how to use these concepts effectively in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

The Complete Lecture 3:

Javascript Course
conditionals and
loops
-Vishal Sharma

@newtonschool
Table of Contents

• Conditional Statements

• Ternary Operator

• Assignment Operator

• Loops

• Loops control statements

• Arrays and Objects

• Practical examples: basic examples with conditionals and loops

02
Conditional Statements
in Javascript

3
What are conditional statements?

Conditional statements help


determine the flow of execution in a
program based on specific
conditions.

PRIMITIVES
Types of conditional statements

Here are the main types of Conditional


Statements
conditional statements:-

if-else-if
if if-else switch
else
if statement

if statement is the most basic form of


conditional statement. Body of if
statement runs if test condition is
true.
if statement: Syntax

Let’s have a look at if statement syntax.


if statement: Example
Let’s understand with an example:-

I am an adult.

condition
if-else: Building on if statement

If you understand the if statement, adding the else part is straightforward. It simply
provides an alternative action when the condition is false.

if(condition) {

// body of if
if statement + else = }
else {

// body of else
}
if-else: Building on if statement

In the previous example, we checked


if a person is under 18 using only an
if statement." Modify the code to false true
include an else condition that prints
"You are not eligible." when the
person age is less than 18 years.
if-else: Example
Here age is less than 18 so else statement is executed:-

I am a minor.
Going beyond: if-else-if-else ladder
The if-else-if-else ladder helps the program check multiple conditions one by one
and take an action based on the first condition that’s true.
Going beyond: if-else-if-else ladder

Think of it like making plans: Plan A,


then Plan B if A fails, then Plan C, and
only facing the worst if all fail. The
if-else-if-else ladder works the same
way.
If-else-if-else: example
Let’s write code for delivering salutations at different parts of day:-
switch statement
switch statement is one among many tools for condition based execution of
statements.
switch statement

It selects one among many cases


whichever matches with value
passed inside switch.
switch statement: syntax
Let’s have a look at its syntax:-

We pass a variable inside switch


and whichever case matches that
variable value gets executed.
switch statement: example
Here switch checks fruit against each case. If no match is found, the default block
runs as a fallback.

Since case ‘apple’ matches the


fruit variable, “This is an
apple.” gets printed.

But what is the break


statement just after every test
case end??
switch statement: break
In this example we have added break after every test case. Do you know why?

Whenever a case matches


statements under it run and to
avoid other cases to run we
break its execution by just
adding break at the end of it.
Ternary Operator: A Shortcut for If-Else

The ternary operator is a concise way to write an if-else statement in a single line. It
evaluates a condition and returns one value if true, and another if false.
Ternary Operator: example

The ternary operator simplifies if-else code when only one condition is involved.
Ternary Operator: Comparison with if..else

Compared to if-else, the ternary operator offers smoother flow, improving


readability and understanding.

Now, after comparison you will


appreciate ternary operator.
Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment
operator is =, but there are also shorthand operators like +=, -=, *= etc.

Usually we use shorthand


notations in writing javascript, it
saves time and energy

/
Assignment Operators: Example
Let’s have a look at an example:-

First one is the basic


assignment and rest of it are
shorthands.

We need not to write


shorthands necessarily, but it
saves time
Loops in real life

Every day we follow certain routine


which we repeat all over the week,
like brushing your teeth, taking
shower etc.
Loops in real life

We wake up, go for a walk, take a


shower, then take lunch and so on.
And next day we repeat the same
process.
Loops in Programming

Just like we repeat several tasks in


daily like, we need some tasks to be
repeated in programming and we
Types of loops
repeat those tasks with the help of
loops.

for while do-while


for loop
A for loop in JavaScript repeats a block of code a set number of times, typically
when the number of iterations is known in advance.
for loop: syntax
for loop has three parts, initial state, increment/decrement and end condition.

let
for loop: example
Let’s see an example:-

Here console.log
statement is printed
5 times as loop runs
for exact 5 times.
while loop
A while loop in JavaScript repeatedly executes a block of code as long as the
condition remains true, making it ideal when the number of iterations depends
on dynamic conditions.
while loop: syntax
for loop has just end condition, increment/decrement is done in body and
initialization is done before the loop starts.
while loop: example
Let’s see an example:-

Here console.log statement


is printed 5 times as loop
runs for exact 5 times. But
we did increment/decrement
inside body and initialization
before the loop
do-while loop
A do-while loop is a control flow statement that ensures a block of code runs at
least once, regardless of the condition.

It runs at least once because at start


body is run before actually checking
the test condition but only for the
first time.
do-while loop: syntax
Let’s have a look at it’s syntax:-

It is same as while loop


with only difference that
condition is checked at
the end.
do-while loop: example
Let’s see an example:-

Here condition got


checked at the end of
the loop.
Difference: while and do-while loop
The while loop checks the condition before execution, potentially skipping the
loop entirely if false. The do-while loop runs at least once before checking the
condition.
Difference: while loop
Here while loop will not run at all since test condition fails before first iteration.
Difference: do-while loop
Here do-while loop will run since body gets executed before it can run test
condition for the first time.
Control Statements:
break and continue

40
Control statement: break

The break statement stops a loop or


switch case from running further,
allowing you to exit early when a
condition is met.
Control statement: break

When the specified condition is met, the break statement immediately terminates
the loop and transfers control to the next statement after the loop.
Control statement: break (with)

Let’s understand with example:-

Here we broke out of loop


when condition i === 3 was
true

Output:
1
2
Control statement: break (without)

Outcome without break would be different

Since there is no break


statement all the values got
printed

Output:
1
2
3
4
5
Control statement: continue

The continue statement skips the


current iteration of a loop and moves
to the next one.
Control statement: continue example

In this example, the continue


statement skips the iteration when i
is 3, so 3 is not printed, but the loop
continues with the next values.

Go back in the previous


slides and compare it
with break statement.
Difference: break vs continue

The break statement exits the loop


entirely, while the continue
statement skips the current iteration
and moves to the next one.
Difference: break vs continue

Let’s compare the break and


continue examples: In the break
example, the loop stops entirely
before reaching 3, while in the
continue example, only 3 is skipped,
and the loop continues until 5.

break
Arrays and Objects

49
What are arrays?

Arrays are one of the best data structures for storing multiple values in a single
variable. Loops, such as for, while, or do-while are commonly used with arrays to
process or manipulate their elements efficiently.
Using array with for loop
Let’s use arrays along with loop. Here we will iterate array elements using for loop:-
Objects: Real world dictionary
Think of an object as a real-world dictionary, where the key is the word you're
looking up (e.g., "name" or "age"), and the value is the definition or meaning of that
word (e.g., "Alice" or 20).

Key Value

name Alice

age 20

In Javascript
Objects: Practical Example
When you have data that involves key-value pairs, objects are the most appropriate
choice. Here is an example:-

Here, title, author, year,


and genre are the keys
(or properties) of the
book object.
Storing Objects in array
You can store several objects inside an array too:-

We often store
multiple objects in
an array is to keep
things organized.
Object Array: Iterating using for loop
And then iterate over them using for loop:-
Object Array: Iterating using for…in loop
It would be lot simpler if we use for…in loop instead:-

In for…in loop we get keys


and in this case ‘i’ is the
key. And then we use use
that key to access the
object in the array.
Object Array: Iterating using for…of loop
If we want to access objects directly then we can use for…of loop

for…of loop directly


provides values stored in
the array.

Which iteration method


would you prefer?
Object: for…in vs for…of
The main difference between them with respect to objects is that for…in is iterable
over the keys of an object, whereas for…of can only iterate over an array.
Some Real World Examples
Calculating Discounts
When shopping, it's crucial to calculate the best price after discounts. For example,
if an item costs $100 and has a 20% discount, arithmetic operators can help us
determine the discount amount and the final price.
Job Offers: Making Right Choice
To choose the better job offer, you can use comparison operators to evaluate
salaries. For example, using a greater-than operator helps you quickly see
which offer provides a higher salary.
Shopping Cart: Calculating Bill
You are creating a shopping cart where each item has a price. You want to
calculate the total cost of all items in the cart.

Arrays, objects, and for loops


(and their variations) are
commonly used together to
solve many programming
problems.
In Class Questions

63
Thanks
for
watching!

64

You might also like