Functions
Introduction
Functions are reusable blocks of code that perform a specific task. Instead of writing the same code multiple times, we can group it into a function and call it whenever needed.
In JavaScript, functions are first-class citizens. This means:
- They can be stored in variables.
- They can be passed as arguments to other functions.
- They can be returned from other functions.
There are several ways to define functions in JavaScript. Understanding these helps you write more flexible and maintainable code. Functions are also crucial for scope management and organizing large programs.
Concepts
Function Declaration
- Declared with the function keyword.
- Hoisted: can be called before its definition.
Examples
// Declaration
function add(a, b) { return a + b; }
// Expression
const subtract = function(a, b) { return a - b; };
// Arrow function
const multiply = (a, b) => a * b;
// Default parameter
function greet(name = "Guest") {
return `Welcome, ${name}!`;
}
Challenges
1. max(a,b)
- Write a function
max(a, b)that returns the larger of two numbers.
💡 Show Answer
function max(a, b){
return a > b ? a : b;
}
console.log(max(5,12));
2. isEven arrow
- Create an arrow function
isEven(n)that returnstrueif the number is even.
💡 Show Answer
const isEven = n => n % 2 === 0;
3. reverseString
- Write a function
reverseString(str)that reverses a string and returns it.
💡 Show Answer
function reverseString(str){
return str.split("").reverse().join("");
}
console.log(reverseString("The Wind in the Willows"));
4. greetUser default
- Create a function greetUser(name) that uses a default parameter "Guest" if no name is given.
💡 Show Answer
function greetUser(name="Guest"){
console.log("Hello " + name);
}
console.log(greetUser());
5. sumArray
- Write a function sumArray(numbers) that takes an array and returns the sum of all its elements.
💡 Show Answer
function sumArray(arr){
return arr.reduce((a,b)=>a+b,0);
}
console.log(sumArray([1, 2, 3, 4, 5]));
6. Declaration vs Expression
- Demonstrate the difference between a function declaration and a function expression by logging them before and after their definitions.
💡 Show Answer
function declared(){ return "I am declared"; }
const expressed = function(){
return "I am expressed";
};
console.log(declared());
console.log(expressed());
7. Anonymous in setTimeout
- Use an anonymous function inside setTimeout to print "Hello World" after 3 seconds.
💡 Show Answer
setTimeout(function(){
console.log("Hello World");
},3000);
8. applyTwice
- Write a function applyTwice(fn, value) that takes a function and a value, then applies the function to the value twice.
💡 Show Answer
function applyTwice(fn,val){
return fn(fn(val));
}
function doubleValue(val){
return val * 2;
}
console.log(applyTwice(doubleValue, 5));
9. Recursive factorial
- Create a recursive function factorial(n) that returns the factorial of n.
💡 Show Answer
function factorial(n){
return n===0?1:n*factorial(n-1);
}
console.log(factorial(10));
10. makeMultiplier
- Write a function makeMultiplier(x) that returns a new function.
- The returned function should multiply its input by x.
💡 Show Answer
function makeMultiplier(x){
return function(n){
return n * x;
}
}
console.log(makeMultiplier(5));