Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

JavaScript Loops – Repeating Tasks Efficiently

In the previous article, we learned how conditional statements help programs make decisions. However, many situations require performing the same task repeatedly.

For example:

  • Display numbers from 1 to 100

  • Print multiplication tables

  • Process thousands of records

  • Generate reports

  • Display product lists

Writing the same statement repeatedly is inefficient. To solve this problem, JavaScript provides loops.

Loops allow a block of code to execute multiple times automatically.

In this article, we will learn:

  • What loops are

  • Why loops are needed

  • Types of loops

  • for loop

  • while loop

  • do-while loop

  • Nested loops

  • break statement

  • continue statement

  • Practical examples

  • Dry runs


What is a Loop?

A loop is a control structure that repeatedly executes a block of code until a specified condition becomes false.

Basic concept:

Condition True
      ↓
Execute Code
      ↓
Check Condition Again
      ↓
Repeat

Why Loops are Needed

Without loops:

document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");

This approach becomes impractical for large repetitions.

Using loops:

for(let i=1; i<=5; i++)
{
    document.write("Hello<br>");
}

Output remains the same with much less code.


Types of Loops in JavaScript

JavaScript provides:

Loop TypePurpose
forKnown number of repetitions
whileUnknown repetitions
do-whileExecute at least once
Nested LoopLoop inside loop

The for Loop

The for loop is the most commonly used loop.

It is preferred when the number of repetitions is known.


Syntax

for(initialization;
    condition;
    update)
{
    statements;
}

Components of a for Loop

for(let i=1;
    i<=5;
    i++)
PartPurpose
InitializationStart value
ConditionCheck repetition
UpdateIncrease or decrease value

Example 1 – Print Numbers 1 to 5

for(let i=1; i<=5; i++)
{
    document.write(i + "<br>");
}

Output:

1
2
3
4
5

Dry Run

i = 1

1 <= 5 → true

Print 1

i++

i = 2

2 <= 5 → true

Print 2

...

i = 6

6 <= 5 → false

Loop stops

Example 2 – Print Numbers 1 to 10

for(let i=1; i<=10; i++)
{
    document.write(i + "<br>");
}

Example 3 – Reverse Counting

for(let i=10; i>=1; i--)
{
    document.write(i + "<br>");
}

Output:

10
9
8
7
6
5
4
3
2
1

Example 4 – Print Even Numbers

for(let i=2; i<=20; i+=2)
{
    document.write(i + "<br>");
}

Output:

2
4
6
8
10
12
14
16
18
20

Example 5 – Print Odd Numbers

for(let i=1; i<=19; i+=2)
{
    document.write(i + "<br>");
}

Output:

1
3
5
7
9
11
13
15
17
19

Multiplication Table Program

let num = 5;

for(let i=1; i<=10; i++)
{
    document.write(
    num + " × " +
    i + " = " +
    (num*i)
    );

    document.write("<br>");
}

Output:

5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
...
5 × 10 = 50

Sum of Numbers 1 to 10

let sum = 0;

for(let i=1; i<=10; i++)
{
    sum += i;
}

document.write(sum);

Output:

55

Dry Run

sum = 0

sum = 0 + 1 = 1

sum = 1 + 2 = 3

sum = 3 + 3 = 6

...

sum = 55

The while Loop

The while loop executes as long as the condition remains true.


Syntax

while(condition)
{
    statements;
}

Example

let i = 1;

while(i <= 5)
{
    document.write(i + "<br>");

    i++;
}

Output:

1
2
3
4
5

Dry Run

i = 1

1 <= 5

Print 1

i++

i = 2

Repeat

Reverse Counting Using while

let i = 10;

while(i >= 1)
{
    document.write(i + "<br>");

    i--;
}

Infinite Loop Example

Wrong:

let i = 1;

while(i <= 5)
{
    document.write(i);
}

Problem:

i never changes

Result:

Infinite Loop

Browser may freeze.


The do-while Loop

The do-while loop executes at least once.


Syntax

do
{
    statements;
}
while(condition);

Example

let i = 1;

do
{
    document.write(i + "<br>");

    i++;
}
while(i <= 5);

Output:

1
2
3
4
5

Difference Between while and do-while

while

Condition checked first.

while(condition)
{
}

do-while

Code executes first.

do
{
}
while(condition);

Example

let i = 10;

do
{
    document.write(i);
}
while(i < 5);

Output:

10

Even though condition is false.


Comparison of Loops

Featureforwhiledo-while
InitializationIncludedSeparateSeparate
Condition CheckBeforeBeforeAfter
Executes At Least OnceNoNoYes

Nested Loops

A loop inside another loop.


Syntax

for(...)
{
    for(...)
    {
    }
}

Example

for(let i=1; i<=3; i++)
{
    for(let j=1; j<=3; j++)
    {
        document.write(j);
    }

    document.write("<br>");
}

Output:

123
123
123

Star Pattern Program

for(let i=1; i<=5; i++)
{
    for(let j=1; j<=i; j++)
    {
        document.write("*");
    }

    document.write("<br>");
}

Output:

*
**
***
****
*****

Dry Run

i=1 → *

i=2 → **

i=3 → ***

i=4 → ****

i=5 → *****

break Statement

Used to terminate a loop immediately.


Example

for(let i=1; i<=10; i++)
{
    if(i==5)
    {
        break;
    }

    document.write(i);
}

Output:

1234

Loop stops when i becomes 5.


continue Statement

Skips current iteration.


Example

for(let i=1; i<=5; i++)
{
    if(i==3)
    {
        continue;
    }

    document.write(i);
}

Output:

1245

3 is skipped.


Real-Life Example – Password Attempts

for(let attempt=1;
    attempt<=3;
    attempt++)
{
    document.write(
    "Attempt " + attempt
    );

    document.write("<br>");
}

Output:

Attempt 1

Attempt 2

Attempt 3

Complete Practical Program

<!DOCTYPE html>

<html>

<body>

<script>

document.write(
"Numbers 1 to 10"
);

document.write("<br>");

for(let i=1; i<=10; i++)
{
    document.write(i);

    document.write("<br>");
}

</script>

</body>

</html>

Flowchart of a Loop

      Start
         │
         ▼
 Initialize
         │
         ▼
 Check Condition
         │
   ┌─────┴─────┐
   │           │
 True       False
   │           │
 Execute      End
   │
 Update
   │
   └───────────►

Real-Life Applications

Loops are used in:

  • ATM systems

  • Banking software

  • Online shopping

  • Data processing

  • Games

  • Social media feeds

  • Student result systems

Companies like Google, Amazon, and Microsoft use loops extensively for handling massive amounts of data.


Common Mistakes Beginners Make

Missing Update Statement

Wrong:

while(i<=10)
{
}

Can create infinite loops.


Wrong Condition

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

Loop never executes.


Confusing break and continue

  • break → Ends loop

  • continue → Skips iteration


Advantages of Loops

  • Reduce code repetition

  • Improve efficiency

  • Handle large datasets

  • Simplify complex tasks

  • Essential for programming


Conclusion

Loops are one of the most powerful features of JavaScript. They allow programs to repeat tasks efficiently and are essential for solving real-world problems.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? ๐Ÿ“Œ Readability – Comments make code easier to understand for you and others. ๐Ÿ“Œ Maintenance – When you revisit your code after months, comments remind you what you were doing. ๐Ÿ“Œ Collaboration – In team projects, comments explain code to fellow developers. ๐Ÿ“Œ Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . ๐Ÿ’ป Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } ๐Ÿง  Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

๐Ÿ’ก Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. ๐Ÿง‘‍๐Ÿ’ป Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...