JavaScript Functions Notes Tasks
JavaScript Functions Notes Tasks
JavaScript Functions
1. Introduction to Functions
📌 What is a Function?
A function is a reusable block of code that performs a specific task.
💡 Example:
function greet() {
console.log("Hello, world!");
}
greet(); // Output: Hello, world!
💡 Example:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
💡 Example:
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 2)); // Output: 8
No this binding.
💡 Example:
const square = (num) => num * num;
console.log(square(5)); // Output: 25
💡 Example:
function greet(name) { // name is a parameter
console.log("Hello, " + name);
}
greet("Alice"); // "Alice" is an argument
JavaScript Functions 2
Allows setting a default value for parameters.
💡 Example:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("Bob"); // Output: Hello, Bob
💡 Example:
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
💡 Example:
function showArgs() {
console.log(arguments);
}
showArgs(10, 20, 30); // Output: [10, 20, 30]
JavaScript Functions 3
A function that runs immediately after defining it.
💡 Example:
(function() {
console.log("IIFE executed!");
})(); // Output: IIFE executed!
Tasks On Functions
📝 Beginner Level (Tasks 1-10)
1️⃣ Write a function that takes a name as an argument and returns a greeting
message.
Example:
greet("Alice");
Output:
Hello, Alice!
2️⃣ Write a function that takes two numbers and returns their sum.
Example:
add(4, 7);
Output:
11
isEven(5);
JavaScript Functions 4
Output:
Odd
square(6);
Output:
36
5️⃣ Write a function that takes an array of 5 numbers and returns their sum.
(Don't use built-in methods)
Example:
sumArray([2, 4, 6, 8, 10]);
Output:
30
6️⃣ Write a function that takes a number n and returns "Positive" , "Negative" , or
"Zero" .
Example:
checkNumber(-3);
Output:
Negative
7️⃣ Write a function that returns the factorial of a number using a loop.
Example:
JavaScript Functions 5
factorial(5);
Output:
120
reverseString("hello");
Output:
olleh
9️⃣ Write a function that finds the largest number in an array of 5 numbers
(without using built-in methods).
Example:
Output:
89
countVowels("hello");
Output:
sum(1, 2, 3, 4, 5);
Output:
15
Output:
IIFE executed
Output:
JavaScript
1️⃣8️⃣ Write a function that takes an array and removes duplicates without using
built-in methods.
Example:
removeDuplicates([1, 2, 2, 3, 4, 4, 5]);
Output:
[1, 2, 3, 4, 5]
1️⃣9️⃣ Write a function using currying that adds numbers step by step.
JavaScript Functions 7
Example:
add(2)(3)(4);
Output:
isPalindrome("racecar");
Output:
true
JavaScript Functions 8