0% found this document useful (0 votes)
19 views18 pages

Loops and Codistion Statments

The document explains the strict equality operator (===) in JavaScript, highlighting its difference from the loose equality operator (==) and emphasizing best practices for usage. It covers various types of loops (for, while, do...while) and their appropriate use cases, along with advanced looping techniques and performance optimization. Additionally, it discusses conditional statements, event handling, and DOM manipulation, providing examples and best practices for each concept.

Uploaded by

RAHUL J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views18 pages

Loops and Codistion Statments

The document explains the strict equality operator (===) in JavaScript, highlighting its difference from the loose equality operator (==) and emphasizing best practices for usage. It covers various types of loops (for, while, do...while) and their appropriate use cases, along with advanced looping techniques and performance optimization. Additionally, it discusses conditional statements, event handling, and DOM manipulation, providing examples and best practices for each concept.

Uploaded by

RAHUL J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

What Does === Mean in JavaScript?

The === operator in JavaScript is the strict equality operator. It compares both
value and data type without type conversion.

1. Difference Between === and ==


Operator Checks Type Conversion Example

== Equality Yes (type coercion) "5" == 5 → true

=== Strict Equality No "5" === 5 → false

2. Example of === (Strict Equality)


console.log(5 === 5); // true (same value, same type)
console.log("5" === 5); // false (different types)
console.log(true === 1); // false (Boolean vs. Number)
console.log(null === undefined); // false (different types)
✅ Best Practice: Always use === unless you explicitly want type conversion.

3. Example of == (Loose Equality)


console.log(5 == "5"); // true (string "5" is converted to number 5)
console.log(true == 1); // true (Boolean `true` is converted to 1)
console.log(null == undefined); // true (special case)
🔹 Why Avoid ==?
 Implicit type conversion can lead to unexpected results.
 Example:
console.log(" " == 0); // true (empty string is converted to 0)
console.log(false == "0"); // true ("0" is converted to 0)

4. When to Use ===?


 When comparing numbers and strings:
let age = "25";
if (age === 25) { // ❌ Wrong: string "25" !== number 25
console.log("Match found");
}
 When comparing Booleans and numbers:
console.log(true === 1); // false (Boolean and Number are different types)

5. Summary
Operator Behavior Use Case
Converts data types before Use with caution, may cause
==
comparing unexpected results
Recommended for accurate
=== Checks both value & type
comparisons

Loops
1. Types of Loops
Loop Type Syntax Structure When to Use
for(initialization; condition; When the number of iterations is
For Loop
increment/decrement) { code } known.
When the number of iterations is
While Loop while(condition) { code } unknown but depends on a
condition.
When the loop must execute at least
Do...While Loop do { code } while(condition);
once before checking the condition.

2. for Loop (Best for Fixed Iterations)


The for loop is used when the number of iterations is predetermined.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example: Counting from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
🔹 How it works?
1. Initialization (let i = 1;) → Sets the starting value.
2. Condition (i <= 5;) → Checks if loop should continue.
3. Increment (i++) → Increases i after each iteration.
✅ Best for:
 Looping over arrays (for with .length).
 Performing a set number of iterations.

3. while Loop (Best for Unknown Iterations)


The while loop executes as long as a condition is true.
Syntax:
while (condition) {
// Code to execute
}
Example: Print numbers from 1 to 5
let count = 1;
while (count <= 5) {
console.log("Count:", count);
count++;
}
🔹 How it works?
1. Condition is checked first (count <= 5).
2. Code runs only if condition is true.
3. count++ updates the value each loop cycle.

✅ Best for:
 Waiting for user input (while(userInput !== "exit")).
 Running loops until a certain condition is met dynamically.

4. do...while Loop (Best for One-Time Execution)


The do...while loop executes at least once, regardless of condition.

Syntax:
do {
// Code to execute
} while (condition);
Example: Run at least once
let num = 10;
do {
console.log("Executed once, even if condition is false");
} while (num < 5);
🔹 Key Difference from while loop:
 do...while executes first, then checks the condition.
 Good for prompts, user inputs, and menus where execution must happen
at least once.
✅ Best for:
 Ensuring at least one execution of a block.
 Prompting users for input (do { prompt() } while(inputInvalid)).

5. Advanced Looping Techniques


5.1 Iterating Over Arrays (forEach)
Executes a function once for each array element.
Example:
let numbers = [10, 20, 30, 40];
numbers.forEach(num => console.log(num));
✅ Best for:
 Looping over arrays without modifying them.

5.2 Iterating Over Objects (for...in)


Loops through the keys of an object.
Example:
let student = { name: "Rahul", age: 25, grade: "A" };
for (let key in student) {
console.log(key + ":", student[key]);
}
✅ Best for:
 Accessing object properties dynamically.

5.3 Iterating Over Arrays (for...of)


Loops through values of an array.
Example:
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
✅ Best for:
 Looping over iterable objects like arrays and strings.

6. Loop Performance & Optimization


💡 Avoiding Infinite Loops
Make sure conditions eventually become false.
let x = 1;
while (x > 0) {
console.log("This never stops!");
}
Fix:
while (x > 0) {
console.log("Running...");
x--;
}
💡 Using break and continue
 break; → Stops the loop immediately.
 continue; → Skips current iteration, moves to the next one.
Example: Stop at 3
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
// Output: 1, 2 (loop stops at 3)
Example: Skip 3
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
// Output: 1, 2, 4, 5 (skips 3)

7. Summary of Loop Differences


Loop Type Best For Condition Check Execution Guarantee
for Known iterations Before loop runs No
while Unknown iterations Before loop runs No
do...while Must run at least once After first execution Yes

53,38,20,61,57,31,54,34,23,24,12,18,56,14,33
Conditional Statements in JavaScript
Conditional statements allow us to control the flow of a program by executing
different code blocks based on conditions.

1. if, else if, and else (Basic Conditional Statements)


These are the most commonly used conditional statements.
Syntax:
if (condition) {
// Code executes if condition is true
} else if (anotherCondition) {
// Code executes if anotherCondition is true
} else {
// Code executes if none of the above conditions are true
}
Example:
let score = 85;

if (score >= 90) {


console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
🔹 Explanation:
 If score >= 90, it prints "Grade: A".
 If score is between 80 and 89, it prints "Grade: B".
 Otherwise, it prints "Grade: C".
✅ Best for:
 Simple decision-making processes.
 Handling multiple conditions sequentially.

2. switch Statement (Alternative to if...else for Multiple Cases)


The switch statement is used when multiple conditions depend on the same
variable value. It is more efficient and readable than multiple if...else if
statements.
Syntax:
switch (expression) {
case value1:
// Code executes if expression === value1
break;
case value2:
// Code executes if expression === value2
break;
default:
// Code executes if no case matches
}
Example: Days of the Week
let day = "Monday";

switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is near!");
break;
case "Sunday":
console.log("It's a holiday!");
break;
default:
console.log("It's a regular day.");
}
🔹 How it works?
1. The switch statement compares day with each case.
2. If day === "Monday", it prints "Start of the week!".
3. The break; statement prevents execution of the next cases.
4. If no match is found, the default case executes.
✅ Best for:
 Handling multiple values of a single variable (e.g., menu options, enums).
 When comparisons are based on exact values (not conditions like >, <).
🚨 Important:
 If break; is omitted, execution "falls through" to the next case!

Example: Fall-through Behavior (When break is Missing)


let fruit = "Apple";

switch (fruit) {
case "Apple":
console.log("It's an apple!");
case "Mango":
console.log("It's a mango!");
default:
console.log("Unknown fruit.");
}
Output:
It's an apple!
It's a mango!
Unknown fruit.
🔹 Fix: Add break; after each case.

3. Nested Conditional Statements (Conditions inside Conditions)


Sometimes, we need to check multiple conditions inside another condition.
Example: Nested if...else
let age = 20;
let hasLicense = true;

if (age >= 18) {


if (hasLicense) {
console.log("You can drive.");
} else {
console.log("You need a driving license.");
}
} else {
console.log("You are too young to drive.");
}
🔹 Explanation:
 If age >= 18, it checks for hasLicense.
 If hasLicense === true, "You can drive." is printed.
 Otherwise, "You need a driving license." is printed.
✅ Best for:
 Handling complex logic.
 Checking multiple related conditions.
4. Combining switch with Nested if
You can combine switch and if...else for advanced logic.
Example: Bank Account System
let accountType = "Savings";
let balance = 5000;

switch (accountType) {
case "Savings":
if (balance > 1000) {
console.log("You have a good balance in your savings account.");
} else {
console.log("Your savings balance is low.");
}
break;

case "Current":
console.log("This is a business account.");
break;

default:
console.log("Invalid account type.");
}
✅ Best for:
 Handling hierarchical decision-making.
 When switch handles primary conditions and if...else handles sub-
conditions.
5. Ternary Operator (? :) – Shorter Conditional Statements
A compact way to write simple if...else conditions.
Syntax:
condition ? "if true" : "if false";
Example:
let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Output: "Adult"
✅ Best for:
 Quick conditional assignments.
 Making code concise and readable.

6. Summary of Conditional Statements


Conditional
Best For Works With Example Use Case
Type
Comparisons (>, <, Checking age
if...else Simple conditions
==) eligibility
Multiple discrete Exact matches Handling menu
switch
cases (===) options
Checking bank
Nested if Complex logic Multiple conditions
account type
Single-line Assigning status based
Ternary (? :) Short conditions
decisions on age
Events and DOM Manipulation in JavaScript
JavaScript interacts with web pages using Events and DOM (Document
Object Model) Manipulation. Events let it respond to user actions, while
DOM manipulation helps modify HTML and CSS dynamically.

1. What is an Event?
An event is any user action, such as clicking a button, pressing a key, or moving
the mouse. JavaScript allows to listen for these events and execute code
accordingly.
Common Events in JavaScript
Event Type Description
click Triggered when an element is clicked
mouseover Triggered when the mouse hovers over an element
mouseout Triggered when the mouse leaves an element
keydown Triggered when a key is pressed
keyup Triggered when a key is released
change Triggered when the value of an input element changes
submit Triggered when a form is submitted
load Triggered when the webpage finishes loading

2. Adding Event Listeners


Event listeners detect events and execute a function when the event occurs.
2.1 Using onclick (Inline Event Handler)
html
<button onclick="alert('Button Clicked!')">Click Me</button>
🔹 Problem: Not recommended for complex applications because it mixes
JavaScript with HTML.

2.2 Using addEventListener() (Best Practice)


document.getElementById("myButton").addEventListener("click", function() {
alert("Button Clicked!");
});
✅ Advantages:
 Allows multiple event listeners on the same element.
 Keeps JavaScript separate from HTML (better for maintainability).

3. Modifying HTML Elements Dynamically


JavaScript can change the text, styles, and attributes of elements.
3.1 Changing Text Content (innerHTML and textContent)
document.getElementById("demo").innerHTML = "Hello, JavaScript!";
document.getElementById("demo").textContent = "New Text Content!";
🔹 Difference:
 innerHTML can insert HTML (<b>Hello</b> will be bold).
 textContent treats it as plain text.

3.2 Changing Styles (style Property)


document.getElementById("demo").style.color = "blue";
document.getElementById("demo").style.fontSize = "20px";
✅ Best for:
 Changing element appearance dynamically.

3.3 Adding and Removing Classes (classList)


document.getElementById("demo").classList.add("highlight");
document.getElementById("demo").classList.remove("highlight");
🔹 Why use classList instead of style?
 Allows better styling control using CSS.
 Keeps JavaScript and CSS separate.

4. Handling User Interactions


4.1 Form Input Handling (change, input, submit Events)
document.getElementById("nameInput").addEventListener("input", function()
{
console.log("User typed: " + this.value);
});
✅ Best for:
 Live search filters.
 Validating input fields.

4.2 Preventing Default Actions (preventDefault())


By default, form submissions reload the page. We can prevent this.
document.getElementById("myForm").addEventListener("submit",
function(event) {
event.preventDefault(); // Stops page reload
alert("Form submitted successfully!");
});

5. Event Delegation (Handling Multiple Elements Efficiently)


Instead of adding event listeners to each child element, attach one listener to the
parent.
Example: Handle clicks for multiple buttons
document.getElementById("parentDiv").addEventListener("click",
function(event) {
if (event.target.tagName === "BUTTON") {
alert("Button Clicked: " + event.target.innerText);
}
});
✅ Why use Event Delegation?
 Improves performance when handling many child elements.
 Useful for dynamically added elements.

6. Removing Event Listeners (removeEventListener)


function greet() {
alert("Hello!");
}
//document.getElementById("btn").addEventListener("click", greet);
document.getElementById("btn").removeEventListener("click", greet);
🔹 Note: The function must be named; anonymous functions won't work.

7. Summary of Key Concepts


Concept Example Use Case
addEventListener("click",
Event Listeners Handling user clicks
callback)
Changing content
Modifying Text innerHTML = "New text"
dynamically
Modifying Styles style.color = "red" Highlighting elements
Class
classList.add("active") Toggling CSS styles
Manipulation
Preventing form
Prevent Default event.preventDefault()
submission
Handling multiple child
Event Delegation event.target.tagName
elements

You might also like