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

PIS Lect8

The document discusses JavaScript fundamentals including arrays, properties and methods, operators, control flow statements, and more. It covers topics like using arrays to store different data types, the length property, comparison operators and their uses, logical operators, and control flow statements like if/else.

Uploaded by

mynaa3643
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)
17 views

PIS Lect8

The document discusses JavaScript fundamentals including arrays, properties and methods, operators, control flow statements, and more. It covers topics like using arrays to store different data types, the length property, comparison operators and their uses, logical operators, and control flow statements like if/else.

Uploaded by

mynaa3643
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/ 14

Lecture 8: JavaScript Fundamentals 1

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you
can have variables of different types in the same Array. You can have objects in an Array. You
can have functions in an Array. You can have arrays in an Array:
myArray[0] = myFunction;
myArray[1] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:
cars.length // Returns the number of elements
cars.sort() // Sorts the array

The length Property


The length property of an array returns the length of an array (the number of array elements).
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

The length property is always one more than the highest array index.
Accessing the Last Array Element
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];

Operators
Operators in JavaScript are symbols that are used to perform operations on operands.
Operands are the values and variables. For Example:
console.log(10 + 20); // 30

Here (+) is an operator that performs addition, and 10 and 20 are operands. Here is the List
of Different Operators that we will learn in this course.
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 String Operators

 Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations on operands.
// Addition
let sum = 5 + 3;
console.log(sum); // 8
// Subtraction
Lecture 8: JavaScript Fundamentals 2

let difference = 10 - 4;
console.log(difference); // 6
// Multiplication
let product = 2 * 6;
console.log(product); // 12
// Division
let quotient = 15 / 3;
console.log(quotient); // 5
// Remainder (Modulus)
let remainder = 17 % 4;
console.log(remainder); // 1
// Exponentiation
let result = 2 ** 4;
console.log(result); // 16

 Assignment Operator:
Assignment operators are used to assign values to variables. We use (=) sign for assignment
operator.
Example:
let x = 5;
//We have multiple assignment operator like:
// Addition assignment
x += 3;
console.log("x:", x); // x: 8
// Subtraction assignment
x -= 2;
console.log("x:", x); // x: 6
// Multiplication assignment
x *= 4;
console.log("x:", x); // x: 24
// Division assignment
x /= 3;
console.log("x:", x); // x: 8
// Remainder (Modulus) assignment
x %= 5;
console.log("x:", x); // x: 3
// Exponentiation assignment
x **= 2;
console.log("x:", x); // x: 9

 Increment / Decrement:
The increment and decrement operators are used to increase or decrease the value of a
variable by 1. The increment operator is (++) and, the decrement operator is (--).
The increment and decrement operators can be used in two ways: Prefix and Postfix.
Let’s learn Prefix increment and decrement operators:
In the following two examples, the operator is placed before the variable, and the value of the
variable is incremented or decremented before it is used.
let a = 10;
Lecture 8: JavaScript Fundamentals 3

console.log(++a); // 11
console.log(a); // 11

let a = 10;
console.log(--a); // 9
console.log(a); // 9

Let’s learn Postfix increment and decrement operators:


In the following two examples, the operator is placed after the variable, and the value of the
variable is used before it is incremented or decremented.

let a = 10;
console.log(a++); // 10
console.log(a); // 11

let a = 10;
console.log(a--); // 10
console.log(a); // 9

 Comparison operators:
Comparison operators compare two values and give back a Boolean value: either true or
false. Comparison operators are useful in decision-making and loop programs in JavaScript.
Let’s see some examples:
 < (less than)
 >(greater than)
 <= (less than or equal to)
 >= (greater than or equal to)
 == (Equal checks )
 != (inequality) (not equal) (flipped value of equal checks)
 ===(strict equality checks ) (checks the Data type)
 !==(strict inequality (!==) (flipped value strict equality checks)

Example:
const a = 10;
const b = 20;
console.log(a < b); // true
console.log(a > b); // false
console.log(a <= b); // true
console.log(a >= b); // false
console.log(a == b); // false
console.log(a != b); // true
console.log(a === b); // false
console.log(a !== b); // true
const a = "10";
Lecture 8: JavaScript Fundamentals 4

const b = 10;
console.log(a == b); // true
console.log(a === b); // false

 Logical Operator:
Logical operators perform logical operations like: AND (&&), OR (||), NOT (!).
Logical AND (&&):
Evaluates operands and return true only if all are true.
 true && true; // true
 true && false; // false
 false && true; // false
 false && false; // false

let x = 5;
let y = 10;
console.log(x > 0 && y > 0); // true
console.log(x > 0 && y < 0); // false
console.log(x < 0 && y > 0); // false
console.log(x < 0 && y < 0); // false

Logical OR (||):
Returns true even if one of the multiple operands is true.
 true || true; // true
 true || false; // true
 false || true; // true
 false || false; // false

let a = 5;
let b = 10;
console.log(a > 0 || b > 0); // true
console.log(a > 0 || b < 0); // true
console.log(a < 0 || b > 0); // true
console.log(a < 0 || b < 0); // false

Logical NOT (!):


Converts operator to Boolean and returns flipped value.
let Yes = true;
let No = false;
console.log(!Yes); // false
console.log(!No); // true

JavaScript Ternary Operator:


JavaScript Ternary Operator (Conditional Operator) is a concise way to write a conditional (if-else)
statement. Ternary Operator takes three operands i.e. condition, true value and false value.
Lecture 8: JavaScript Fundamentals 5

let result = (10 > 0) ? 10 : 50;


console.log(result);

Operator Precedence:
Operator precedence in JavaScript determines the order in which, operators are parsed
concerning each other.
example:
let result = 2 + 3 * 4;
console.log(result); // Output: 14

Why the multiplication is performed before the addition, it is because of the operator’s
precedence value. In below table you can see the precedence of multiplication is 9 and
precedence of addition is 8. So the higher precedence is performed first. That’s why it is
multiplying 3 and 4 after that it is adding 2 and the result is 14.

Operator Precedence

Brackets: () 11
Exponentiation: ** 10
Multiplication & Division & Modulus: *, /, % 9
Addition & Subtraction: +, - 8
Relational: <, >, <=, >= 7
Equality Operators: ==, !=, ===, !== 6
Logical AND: && 5
Logical OR: || 3
Conditional (Ternary) Operator: ?: 2
Assignment Operator: =, +=, -=, *=, /=, %= 1

Operator Associativity:
Operator associativity in JavaScript defines the order in which operators of the same
precedence are evaluated.
There are two types of operator associativity:
- Left-to-right
- And Right-to-left

Left-to-right associativity:
In Left-to-right associativity Operators are evaluated from left to right.
Example:
Lecture 8: JavaScript Fundamentals 6

let result = 4 - 2 - 1;
console.log(result); // Output: 1

In this example only subtraction operator is used and it’s associativity is from left to right as
you can see in the table. The expression 4 - 2 - 1 is evaluated from left to right. First, 4 - 2 is
calculated, resulting in 2, then, 2 - 1 is evaluated, giving us the final result of 1.

Right-to-left associativity:
In Right-to-left associativity Operators are evaluated from right to left.
For example,

let result = 2 ** 3 ** 2;
console.log(result); // Output: 512

In this example only exponentiation operator is used and it’s associativity is from Right to
left as you can see in the below table. First, 3 ** 2 is calculated, resulting in 9. Then, 2 ** 9
is evaluated, giving us the final result of 512.

Control flow statements


JavaScript if, else, and else if
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript
error. Example: Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
Lecture 8: JavaScript Fundamentals 7

{
greeting = "Good day";
}

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.
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
}

If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

The else if Statement


Use the else if statement 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
Lecture 8: JavaScript Fundamentals 8

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

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00,
create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

JavaScript Switch Statement


The switch statement is used to perform different actions based on different conditions, or we
use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
Lecture 8: JavaScript Fundamentals 9

// code block
}

This is how it works:


 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0,
Monday=1, Tuesday=2 ..). This example uses the weekday number to calculate the weekday
name:
switch (new Date().getDay())
{
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

The break Keyword


Lecture 8: JavaScript Fundamentals 10

When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop
the execution inside the switch block. It is not necessary to break the last case in a switch
block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next
case will be executed even if the evaluation does not match the case.

The default Keyword


The default keyword specifies the code to run if there is no case match:
The getDay() method returns the weekday as a number between 0 and 6. If today is neither
Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay())
{
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}

The default case does not have to be the last case in a switch block:
switch (new Date().getDay())
{
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
}

If default is not the last case in the switch block, remember to end the default case with a
break.
Lecture 8: JavaScript Fundamentals 11

Common Code Blocks


Sometimes you will want different switch cases to use the same code. In this example case 4
and 5 share the same code block, and 0 and 6 share another code block:
Example
switch (new Date().getDay())
{
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}

Switching Details
If multiple cases matches a case value, the first case is selected. If no matching cases are
found, the program continues to the default label. If no default label is found, the program
continues to the statement(s) after the switch.

Strict Comparison
Switch cases use strict comparison (===). The values must be of the same type to match.
A strict comparison can only be true if the operands are of the same type.
In this example there will be no match for x:
Example
let x = "0";
switch (x)
{
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
Lecture 8: JavaScript Fundamentals 12

default:
text = "No value found";
}

Loops in JavaScript
In programming, loops are used to repeat a block of code. For example, if you want to display
a message 100 times, then you can use a loop. First we will learn about for loop:
Example 1: Display a Text 10 Times:

for (let i = 1; i <= 10; i++)


{
console.log("ITEC");
}

Example 2: Display Numbers from 1 to 10

for (let i = 1; i <= 10; i++)


{
console.log(i);
}

Example 3:

let coding = ["JavaScript", "Python", "CPP"];


for (let i = 0; i < coding.length; i++)
{
console.log(coding[i]);
}

We can create another Loop inside a loop also. example:

for (let i = 1; i <=5; i++)


{
console.log(i);
for (let j = 1; j <= 3; j++)
{
console.log("Inner Loop: " + j);
}
}

Now we will learn while Loop:


Syntax of while loop is:

while (condition)
{
// code to be executed repeatedly
}
Lecture 8: JavaScript Fundamentals 13

The process of while loop:


1. A while loop evaluates the condition inside the parenthesis ().
2. If the condition evaluates to true, the code inside the while loop is executed.
3. The condition is evaluated again.
4. This process continues until the condition is false.
5. When the condition evaluates to false, the loop stops.
Example:
JavaScript code snippet uses a while loop to print numbers from 0 to 10.
let i = 0;
while (i <= 10)
{
console.log(i);
i++;
}

JavaScript do...while Loop:


The syntax of do...while loop is:
do {
// code to be executed repeatedly
} while (condition);

The process of do...while Loop,


1. The body of the loop is executed at first. Then the condition is evaluated.
2. If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
5. This process continues until the condition evaluates to false. Then the loop stops.
Example: Display Numbers from 1 to 5

let i = 1;
do
{
console.log(i);
i++;
} while(i <= 5);

Now let’s understand when we will use for loop and when we will use while loop.
A for loop is usually used when the number of iterations is known. However, while and
do...while loops are usually used when the number of iterations are unknown. We have to
Lecture 8: JavaScript Fundamentals 14

repeat the code until the condition is false. So this was for loop, while loop, and do.. while
loop.
break and continue statement:
The break statement is used to terminate the loop immediately.
for (let i = 1; i <= 5; i++)
{
// condition to break
if (i == 3)
{
break;
}
console.log(i);
}

The continue statement is used to skip the current iteration of the loop and the control flow of
the program goes to the next iteration.
for (let i = 1; i <= 5; i++)
{
// condition to continue
if (i == 3)
{
continue;
}
console.log(i);
}

You might also like