Loop for and Do-while & Funtion

javascript dev.to

For Loop:

  • A for loop is used when you know how many times you want to repeat a block of code

No Output:

  • This use for condition false but Ans: No output

Loop Check:

  • Entire query is about loop entry check and exit check examples in real-life situations.

Entry Check Example (Real-Life):

Example: Taking a Bus

Real-life situation:

  • Before entering the bus, you check: "Do I have enough money?" (condition checked first)

  • If the money you have is less than the bus ticket price, you never enter the bus (loop doesn't run)

  • You check the condition before taking the ride

Code example:

let count = 0;
while (count < 3) {
  console.log("Count: " + count);
  count++;
}

// Output: 0, 1, 2 (checks before each time)
Enter fullscreen mode Exit fullscreen mode

Exit Check Example (Real-Life) Do-While Loop:

Example: ATM Machine

Real-life situation:

  • You first use the ATM (withdraw money)

  • Then you ask: "Do I want to withdraw more?" (condition checked after)

  • You always use the ATM at least once, even if you don't want more

Code example:

do {
  console.log("Enter amount");
  console.log("Withdraw money");
} while (wantMoreWithdrawal);
Enter fullscreen mode Exit fullscreen mode

Function:

  • A Function is a block of code written to perform a specific task.(ஒரு குறிப்பிட்ட வேலை (task) செய்ய எழுதப்படும் code block-ஐ Function என்பார்கள்.)

  • Instead of writing the same code multiple times, we can place it inside a Function and call it whenever needed.(ஒரே code-ஐ பல முறை எழுதாமல், Function-ல் வைத்து தேவையான போது அழைக்கலாம் (call).

Syntax:

function functionName() 
{
    // code
}
Enter fullscreen mode Exit fullscreen mode

Why do we use Functions?

  • Code Reuse – The same code can be used multiple times

  • Easy Maintenance – It is easier to modify and manage the code

  • Reduce Duplicate Code – No need to write the same code repeatedly

  • Better Readability – Makes the code easier to read and understand

Types of Functions in JavaScript:TBD

  1. Normal Function:
function test() 
{
    console.log("Normal Function");
}

Enter fullscreen mode Exit fullscreen mode

2.Function Expression:

const test = function() 
{
    console.log("Function Expression");
};
Enter fullscreen mode Exit fullscreen mode

3.Arrow Function:

const test = () => 
{
    console.log("Arrow Function");
};
Enter fullscreen mode Exit fullscreen mode
Reference:

Source: dev.to

arrow_back Back to Tutorials