Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Lecture 2 - Operators & Conditional Statements

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 2 - Operators & Conditional Statements

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

CHAPTER – 2

Operators and Conditional Statements in JS?

In web development, we use conditional statements (like if) to make decisions based on
true or false conditions. Operators (like ==, >, <, +, % ) are used inside these statements
to perform some operations on the operands like comparison, calculation, or logic checking
etc.
 Conditional statements: Decide actions based on conditions (e.g., "If it is raining,
take an umbrella").
 Operators: Perform operations like arithmetic (+, -), comparisons (==, >, <), or
logical checks (&&, ||).
Together, they help implement real-life conditions in websites.

How to comment in JS
A comment is a part of the code that is not executed by JavaScript. It is typically used to
explain the code, make notes, or clarify the functionality of the code for anyone reading the code.
To comment out a line or block of code in JavaScript, you can use Ctrl + / in many code editors."
Additional Notes:
 Single-line comments in JavaScript start with //.
 Multi-line comments are enclosed in /* */.
 The shortcut Ctrl + / is a feature of most code editors (e.g., VS Code, Sublime Text) and not
part of JavaScript itself.

Operators in JavaScript.
Operators in JavaScript are symbols or keywords used to perform operations on values
or variables. They help us manipulate data.

Here are some common types of operators with examples:

1. Arithmetic Operators: Used for basic math operations.


o + (Addition): 5 + 3 gives 8
o - (Subtraction): 10 - 4 gives 6
o * (Multiplication): 6 * 2 gives 12
o / (Division): 12 / 4 gives 3
o % (Modulus): 10 % 3 gives 1 (remainder)
o **(Exponentiation): 5**2 gives 25
o ++(Increment): 5++ gives 5+1 = 6
o -- (Decrement): 5-- gives 5-1 = 4

Examples:
let a = 5;
let b = 2;
console.log(“a + b”) = 5 + 2 = 7 // Addition
console.log(“a - b”) = 5 - 2 = 3 // Subtraction
console.log(“a * b”) = 5 * 2 = 10 // Multiplication
console.log(“a / b”) = 5 / 2 = 2.5 // Division
console.log(“a % b”) =5%2=1 // Modulus
console.log(“a ** b”) = 5 ** 2 = 25 // Exponentiation means 5 to the power
(5^2)

Unary Operators
In JavaScript, increment and decrement operators are used to increase or decrease
a value by 1.
1. Increment Operator (++):
o Increases a value by 1.
o Example:
let x = 5;
x++; // Now x is 6
2. Decrement Operator (--):
o Decreases a value by 1.
o Example:
let y = 5;
y--; // Now y is 4
Types of Increment and Decrements:
 Post-increment/decrement:
The operator comes after the variable (x++ or x--). The value is used first,
then changed.
 Pre-increment/decrement:
The operator comes before the variable (++x or --x). The value is changed
first, then used.
o Example:
let a = 5;
console.log(a++); // Prints 5, then a becomes 6
console.log(++a); // Increases a to 6, then prints 6
How Pre- and Post-Increment/Decrement Work:
 Pre-decrement (--x): The value of the variable is decreased first, and then the
new value is used in the calculation or condition.
o Think of it as "decrease now, then use."
 Post-decrement (x--): The current value is used first, and then the variable is
decreased afterward.
o It's like "use the value, then decrease."
 Pre-increment (++x): The value of the variable is increased first, and then the
new value is used in the calculation or condition.
o "Increase now, then use."
 Post-increment (x++): The current value is used first, and then the variable is
increased afterward.
o "Use the value, then increase."
Summary:
 Pre changes the value first, then uses it.
 Post uses the value first, then changes it.

Here are simple coding examples for each type of increment and decrement, with
comments to explain what’s happening:
Post-Decrement (x--)
let x = 5;
let result = x--; // result is assigned 5, then x is decreased to 4
console.log(result); // Outputs 5
Pre-Increment (++x)
let x = 5;
let result = ++x; // x is increased to 6, then result is assigned 6
console.log(result); // Outputs 6
Post-Increment (x++)
let x = 5;
let result = x++; // result is assigned 5, then x is increased to 6
console.log(result); // Outputs 5
_______________________________________________________________________________
______

What is the difference between Unary and assignment operators?.


Unary operators ( a++ or a -- ) Assignment Operators ( a += 4 or a -= 4 )

The unary operators (a++ and a--) increase or decrease the value of a by 1.
o a++ is the same as a = a + 1.
o a-- is the same as a = a - 1.
The assignment operators (a += 4 and a -= 4) change the value of a by a
specific number.
o a += 4 is the same as a = a + 4.
o a -= 4 is the same as a = a - 4.
In short, ++ or -- changes a by 1, while += or -= changes a by any number you
specify.
_______________________________________________________________________________
______

2. Assignment Operators in JavaScript


Assignment operators are used to assign values to variables. We can use all
arithmetic operators in the form of assignment operators. Here are some
common ones:
o = (Assign):
Assigns a value to a variable.
Example: x = 10 (sets x to 10)
o += (Add and Assign):
Adds a value to a variable and assigns the result.
Example: x += 5 (same as x = x + 5)
o -= (Subtract and Assign):
Subtracts a value from a variable and assigns the result.
Example: x -= 3 (same as x = x - 3)
o *= (Multiply and Assign):
Multiplies a variable by a value and assigns the result.
Example: x *= 2 (same as x = x * 2)
o %= (Modulus and Assign):
Divides a variable by a value and assigns the remainder.
Example: x %= 3 (same as x = x % 3)
o **= (Exponent and Assign):
Raises a variable to the power of a value and assigns the result.
Example: x **= 2 (same as x = x ** 2)
These operators make it easy to update a variable's value without rewriting the
entire expression.

3. Comparison Operators: Used to compare values.


o == (Equal to):
5 == '5' is true (compares values, ignoring data type)
o === (Strict equal to):
5 === '5' is false (compares both value and data type)
o != (Not equal):
5 != 3 is true (compares values, ignoring data type)
o !== (Strict not equal):
5 !== 3 is true (compares both value and data type)
o > (Greater than):
8 > 5 is true
o >= (Greater than or equal to):
8 >= 5 is true (checks if the left side is greater than or equal to the right side)
o < (Less than):
3 < 7 is true
o <= (Less than or equal to):
3 <= 7 is true (checks if the left side is less than or equal to the right side)
Make sure to note the correction for the >= and <= operators in terms of their
meanings.
4. Logical Operators: Used for combining conditions.
o && (And):
true && false gives false (both conditions must be true for the result to be true)
o || (Or):
true || false gives true (at least one condition must be true for the result to be
true)
o ! (Not):
!true gives false (reverses the value; true becomes false, and vice versa)
This formatting keeps it clear and easy to understand.
____________________________________________________________________________________________
________

Expression in JS ( “a + b” )
The whole part "a + b" is called an expression, where "a" and "b" are called operands, and
the "+" sign between them is called the operator.
An operator performs a specific action on values or variables, such as addition,
comparison, or assignment, to produce a result or change a value.

Conditional Statements in JavaScript


We learn operators to do simple tasks like adding numbers, comparing values, and making
decisions in our code. They help the program work properly.

Operators are used in conditional statements to check if something is true or false,


helping the program decide what to do next.

Conditional statements let your program take different actions based on certain
conditions. Examples include if, else if, else, and switch.

if Statement
 Purpose: Execute a block of code if a condition is true.
 Example: Check if the temperature is high.

if (temperature > 30) {


console.log("It's hot.");
}

 Example: Check if a person can vote based on age.

if (age > 18) {


console.log("You can vote.");
}

 Example: Set background color based on mode (dark or light).


let mode = "dark";
let color;

if (mode === "dark") {


color = "black"; // Dark mode color
} else if (mode === "white") {
color = "white"; // Light mode color
}
console.log(color); // Outputs the selected color

2. if...else Statement
 Purpose: Execute one block of code if the condition is true and another if it's false.
 Example: Check if a score is passing.

if (score >= 50) {


console.log("Pass");
} else {
console.log("Fail");
}

 Example: Check voting eligibility based on age.

let age = 20;

if (age > 18) {


console.log("You can vote.");
} else {
console.log("You cannot vote.");
}

 Example: Set background color based on mode.

let mode = "dark";


let color;

if (mode === "dark") {


color = "black";
} else if (mode === "white") {
color = "white";
} else {
color = "gray"; // Default color
}
console.log(color);
3. else if Statement
 Purpose: Check multiple conditions in sequence.
 Example: Evaluate score for performance.
if (score >= 80) {
console.log("Excellent");
} else if (score >= 50) {
console.log("Good");
} else {
console.log("Needs Improvement");
}

Age Eligibility
 Example: Check multiple age conditions and respond accordingly.
let age = 16;

if (age >= 18) {


console.log("You can vote.");
} else if (age >= 16) {
console.log("You are eligible for a provisional license.");
} else {
console.log("You are too young for voting or a license.");
}

Changing Color Based on Mode


 Example: Set the background color based on different modes.
let mode = "dark";
let color;

if (mode === "dark") {


color = "black"; // Dark mode color
} else if (mode === "white") {
color = "white"; // Light mode color
} else if (mode === "blue") {
color = "blue"; // Blue mode color
} else {
color = "gray"; // Default color
}

console.log(color); // Outputs the selected color


These examples show how to use the else if statement effectively to handle multiple
conditions in sequence, whether for age eligibility or setting background colors based on
mode.
4. Switch Statement
The switch statement checks a value and matches it to different options. It runs the code
for the option that matches. If there’s no match, it can run a default option instead. This
helps organize choices better than using many if-else statements.

Days of the Week


 Example: Evaluate a variable and print the corresponding day.

let day = 2;

switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}

Voting Eligibility
 Example: Check if a person is eligible to vote.

let age = 20;

switch (true) {
case (age >= 18):
console.log("You can vote.");
break;
default:
console.log("You cannot vote.");
}

Changing Color Based on Mode


 Example: Set background color based on mode.

let mode = "dark";


let color;
switch (mode) {
case "dark":
color = "black";
break;
case "white":
color = "white";
break;
default:
color = "gray"; // Default color
}
console.log(color); // Outputs the selected color

These examples illustrate how to use conditional statements effectively in JavaScript for
various scenarios.

Ternary Operator
The ternary operator is a short way to write an if-else statement in one line. It uses a
question mark (?) and is often used to choose between two values.

How It Works

The syntax is: condition ? value If True : value If False;

 condition: A statement that is checked (true or false).


 Value If True: What to return if the condition is true.
 Value If False: What to return if the condition is false.

Example
let age = 16;
let canVote = (age >= 18) ? "Yes, you can vote." : "No, you cannot vote.";

console.log(canVote); // Outputs: No, you cannot vote.

In this example, it checks if age is 18 or older. If true, it says "Yes, you can vote." If false, it
says "No, you cannot vote."
____________________________________________________________________________________________
_______

You might also like