DEV Community

Cover image for Function, loops js (Lesson 3 with Hassan)
Hanna
Hanna

Posted on • Updated on

Function, loops js (Lesson 3 with Hassan)

FUNCTION

A JS function is a block of code designed to perform a particular task and is executed when "something" invokes it (calls it).
We can submit 0, 1, or more parameters to a function.

ex.
function functionName(parameter1, parameter2, parameter3) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

FUNCTION & RETURN STATEMENT

The return value is "returned" back to the "caller".

ex.
function myFunction(a, b) {
  return a + b;
}
console.log(myFunction(5, 6))// Function returns 11
Enter fullscreen mode Exit fullscreen mode

LOOPS

Loops are used in JS to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false.

FOR LOOP

for ([begin]; [condition]; [step]) {
   // statement
}
Enter fullscreen mode Exit fullscreen mode
ex.
for (let i = 0; i < 10; i++) {
    console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

WHILE LOOP

The while loop starts by evaluating the condition. If the condition is true, the statement(s) is/are executed. If the condition is false, the statement(s) is/are not executed. After that, while loop ends.

while (condition)
{
  statement(s);
}
Enter fullscreen mode Exit fullscreen mode
ex.
let i = 0;
while (i < 10) 
{
  console.log(i);
   i++;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)