Lesson 8 - Function
Functions in JavaScript
A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you can put it inside a function and call it whenever needed.
console.log("Hello!");
}
// Call (use) the function
sayHello();
❓Why use functions?
- They make code organized and readable.
- You can reuse the same code multiple times.
- They allow you to break problems into smaller parts.
Functions with parameters
console.log("Hello,", name, "!");
}
greet("Alice");
greet("Bob");
You can give a function inputs (called parameters) to make it more flexible
Functions that return values
return a + b;
}
let result = add(5, 3);
console.log("Result:", result);
Functions can also return results using the
return keyword
Arrow functions (a shorter way)
return a + b;
};
console.log(add(5, 3));
It works the same way as function, just written
with an arrow =>.
📋 Key Points
- Use
functionto define a function. - Use parentheses
()to call a function. - Use curly braces
{ }to wrap the code inside the function. - Functions can take parameters (inputs).
- Functions can return a value.
Say Hello
console.log("Hello, everyone!");
}
sayHello();
💡 Try changing the message inside console.log().
Say Your Name
console.log("Hello, " + name);
}
greet("Anna");
💡 Try greeting yourself by changing the name.
Add Two Numbers
return a + b;
}
console.log(addNumbers(2, 3));
💡 Try adding bigger numbers.
Double a Number
return x * 2;
}
console.log(double(6));
💡 Try doubling your age!
Make a Sentence
return name + " likes " + food;
}
console.log(makeSentence("Sam", "pizza"));
💡 Try your own name and favorite food.
Find the Bigger Number
if (a > b) {
return a;
} else {
return b;
}
}
console.log(bigger(8, 3));
💡 Try two different numbers.
Repeat a Word
return word.repeat(times);
}
console.log(repeatWord("Hi ", 3));
💡 Try repeating your name 5 times.
Multiply Three Numbers
return a * b * c;
}
console.log(multiply(2, 3, 4));
💡 Try three different numbers.
Check Even or Odd
if (n % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
}
checkNumber(7);
💡 Try with your favorite number.
Make a Birthday Song
console.log("Happy Birthday to you!");
console.log("Happy Birthday dear " + name);
}
birthdaySong("Liam");
💡 Try singing the song for your friend!