• Home
  • Tutorials
  • Python Tutorial 1
  • Python Tutorial 2
  • Python Tutorial 3
  • Python Tutorial 4
  • Python Tutorial 5
  • JavaScript Tutorial 1
  • JavaScript Tutorial 2
  • JavaScript Tutorial 3
  • JavaScript Tutorial 4
  • JavaScript Tutorial 5

Functions and Control Flow (If Statements, Loops)

Understanding Functions in JavaScript

What are Functions?
Functions are reusable blocks of code designed to perform a specific task. Functions help make code more organized, readable, and efficient by allowing you to reuse the same logic in different parts of your program.

How to Define a Function:
Functions are defined using the function keyword, followed by a name and parentheses ( ). Code inside the curly braces { } is the body of the function.

Syntax:

function functionName() {

 // Code to be executed 

}

Example:

function sayHello() {
   console.log("Hello, World!");
}
sayHello();  // Output: Hello, World!
 

Example:

function addNumbers(num1, num2) {
   return num1 + num2;
}
console.log(addNumbers(5, 10));  // Output: 15
 

Questions & Answers:

  • Q: What is a function in JavaScript?
    • A: A function is a reusable block of code that performs a specific task.
  • Q: How do you call a function named greet?
    • A: Use great( );

Control Flow with If Statements

What is Control Flow?
Control flow determines the order in which your code executes. With if statements, you can execute different blocks of code depending on whether a condition is true or false.

Syntax for If Statements:

if (condition) {
   // Code to execute if the condition is true
}
 

Example:

let age = 18;
if (age >= 18) {
   console.log("You are eligible to vote.");
} else {
   console.log("You are not eligible to vote.");
}
Else If Statements:
To check multiple conditions, use else if.

Example:

let grade = 85;
if (grade >= 90) {
   console.log("You got an A!");
} else if (grade >= 80) {
   console.log("You got a B!");
} else {
   console.log("You need to study more.");
}


Questions & Answers:

  • Q: What is an if statement used for?
    • A: It is used to execute code based on whether a condition is true or false.
  • Q: How do you check multiple conditions?
    • A: Use else if statements for additional conditions.

Loops in JavaScript

What are Loops?
Loops allow you to repeat a block of code multiple times. There are several types of loops in JavaScript, but the most common are for loops and while loops.

For Loops

Syntax:

for (initialization; condition; increment) {
   // Code to execute
}

Example:

for (let i = 0; i < 5; i++) {
   console.log("Counting: " + i);
}
// Output: Counting: 0, Counting: 1, ..., Counting: 4
 

While Loops

Syntax:
while (condition) {
   // Code to execute
}
 

Example:

let i = 0;
while (i < 3) {
   console.log("Hello, World!");
   i++;
}
// Output: Hello, World! (3 times)
 

Break and Continue

  • break: Exits the loop immediately.
  • continue: Skips the rest of the current loop iteration and moves to the next iteration.

Example:

for (let i = 0; i < 5; i++) {
   if (i === 3) {
       break;  // Exit the loop when i is 3
   }
   console.log(i);  // Output: 0, 1, 2
}
 

Questions & Answers:

  • Q: What is the difference between for and while loops?
    • A: A for loop runs for a specified number of iterations, while a while loop runs as long as its condition is true.
  • Q: What does break do in a loop?
    • A: It exits the loop immediately, skipping any remaining iterations.

Combining Functions with Control Flow

Example:
Let’s create a function to check if a number is even or odd using an if statement.

function checkEvenOdd(number) {
   if (number % 2 === 0) {
       return "Even";
   } else {
       return "Odd";
   }
}
console.log(checkEvenOdd(10));  // Output: Even
console.log(checkEvenOdd(7));   // Output: Odd
 

Mini-Project: Number Guesser Game

Objective:
Create a number guessing game where the user tries to guess a random number between 1 and 10.

Code Example:

function numberGuesser() {
   let randomNumber = Math.floor(Math.random() * 10) + 1;
   let guess;
   let attempts = 0;

   while (guess !== randomNumber) {
       guess = parseInt(prompt("Guess a number between 1 and 10: "));
       attempts++;
       if (guess < randomNumber) {
           console.log("Too low, try again.");
       } else if (guess > randomNumber) {
           console.log("Too high, try again.");
       } else {
           console.log(`Correct! You guessed it in ${attempts} attempts.`);
       }
   }
}
numberGuesser();
 

Questions for the Mini-Project:

  • Q: What JavaScript method generates random numbers?
    • A: Math.random( ) generates a random decimal number between 0 and 1.
  • Q: How do you convert a decimal number to an integer?
    • A: Use Math.floor( ) or Math.ceil( ).

Conclusion

Recap:

  • Functions help organize and reuse code. You can pass inputs to functions and get outputs using parameters and return values.
  • Control flow with if, else if, and else lets your code make decisions.
  • Loops, such as for and while, allow you to execute repetitive tasks efficiently.

Next Steps:

  • Practice writing your own functions and loops.
  • In the next tutorial, we’ll explore arrays and objects, two essential data structures in JavaScript.

GoInnovateSoftware

Copyright © 2024 GoInnovateSoftware - All Rights Reserved.

Powered by GoDaddy

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept