Mastering JavaScript Functions Learn Practice Excel Quiz and Coding Exercises for JavaScript FREE PDF Download

Learn JavaScript Basic Functions

Let’s delve into the world of basic functions in JavaScript. Functions are fundamental building blocks in JavaScript that allow you to group code into reusable units. Here’s an in-depth exploration with coding examples:

1. Function Declaration:

Description: Function declarations define a function and are hoisted to the top of the containing scope.

Example:

function greet(name) {

  console.log(`Hello, ${name}!`);

}

greet(‘John’); // Output: Hello, John!

2. Function Expression:

Description: Function expressions involve assigning a function to a variable. They are not hoisted.

Example:

const greet = function(name) {

  console.log(`Hello, ${name}!`);

};

greet(‘Jane’); // Output: Hello, Jane!

3. Arrow Functions:

Description: Arrow functions are a concise way to write functions, especially useful for short, single-expression functions.

Example:

const add = (a, b) => a + b;

console.log(add(3, 7)); // Output: 10

4. Default Parameters:

Description: You can set default values for function parameters.

Example:

function greet(name = ‘Guest’) {

  console.log(`Hello, ${name}!`);

}

greet(); // Output: Hello, Guest!

5. Rest Parameters:

Description: The rest parameter allows a function to accept an indefinite number of arguments as an array.

Example:

function sum(…numbers) {

  return numbers.reduce((acc, num) => acc + num, 0);

}

console.log(sum(1, 2, 3, 4)); // Output: 10

6. Callback Functions:

Description: Callback functions are functions passed as arguments to another function, often used in asynchronous operations.

Example:

function fetchData(url, callback) {

  // Fetch data from the URL

  // Once data is fetched, invoke the callback

  callback(data);

}

fetchData(‘https://api.example.com/data’, (data) => {

  console.log(‘Data received:’, data);

});

7. Higher-Order Functions:

Description: Higher-order functions either take a function as an argument or return a function.

Example:

function multiplier(factor) {

  return function (number) {

    return number * factor;

  };

}

const multiplyByTwo = multiplier(2);

console.log(multiplyByTwo(5)); // Output: 10

8. IIFE (Immediately Invoked Function Expression):

Description: IIFE is a function that is executed immediately after being created.

Example:

(function() {

  console.log(‘I am an IIFE!’);

})();

9. Recursion:

Description: A function can call itself, enabling the solution of problems through repeated self-similar smaller computations.

Example:

function factorial(n) {

  return n <= 1 ? 1 : n * factorial(n – 1);

}

console.log(factorial(5)); // Output: 120

10. Closures:

Description: Closures occur when a function is defined inside another function, allowing the inner function to access variables from the outer function even after the outer function has finished execution.

Example:

function outer() {

  let outerVar = ‘I am from outer scope’;

  function inner() {

    console.log(outerVar);

  }

  return inner;

}

const closureFunction = outer();

closureFunction(); // Output: I am from outer scope

These basic functions lay the foundation for more advanced JavaScript concepts. Practice, experiment, and gradually incorporate them into your coding repertoire. 

Coding exercises for Functions

10 coding exercises to reinforce your understanding of basic functions in JavaScript. Each exercise comes with detailed steps, descriptions, code examples, and solutions.

Exercise 1: Function Declaration

Task: Create a function that takes two numbers as parameters and returns their sum.

Steps:

  1. Declare a function named addNumbers with parameters num1 and num2.
  2. Inside the function, calculate the sum of num1 and num2.
  3. Return the result.

Code:

function addNumbers(num1, num2) {

  return num1 + num2;

}

console.log(addNumbers(5, 7)); // Output: 12

Exercise 2: Function Expression

Task: Write a function expression to find the square of a number.

Steps:

  1. Declare a variable square and assign it a function expression.
  2. The function should take a parameter number and return its square.

Code:

const square = function(number) {

  return number * number;

};

console.log(square(4)); // Output: 16

Exercise 3: Arrow Function

Task: Rewrite the addNumbers function from Exercise 1 using an arrow function.

Steps:

  1. Declare a variable addNumbers and assign it an arrow function.
  2. The arrow function should take two parameters and return their sum.

Code:

const addNumbers = (num1, num2) => num1 + num2;

console.log(addNumbers(3, 8)); // Output: 11

Exercise 4: Default Parameters

Task: Create a function that greets a user with their name and a default greeting if no name is provided.

Steps:

  1. Declare a function greetUser with a parameter name and set its default value to ‘Guest’.
  2. Inside the function, log a greeting using the provided or default name.

Code:

function greetUser(name = ‘Guest’) {

  console.log(`Hello, ${name}!`);

}

greetUser(‘Alice’); // Output: Hello, Alice!

greetUser(); // Output: Hello, Guest!

Exercise 5: Rest Parameters

Task: Write a function that accepts any number of arguments and returns their sum.

Steps:

  1. Declare a function sum with a rest parameter.
  2. Inside the function, use the reduce method to calculate the sum of all passed arguments.

Code:

function sum(…numbers) {

  return numbers.reduce((acc, num) => acc + num, 0);

}

console.log(sum(2, 4, 6)); // Output: 12

Exercise 6: Callback Function

Task: Create a function that receives a callback and invokes it with a message.

Steps:

  1. Declare a function useCallback that takes a callback as a parameter.
  2. Inside the function, invoke the callback with a message.

Code:

function useCallback(callback) {

  callback(‘Callback function invoked!’);

}

// Example callback function

const displayMessage = (message) => console.log(message);

useCallback(displayMessage); // Output: Callback function invoked!

Exercise 7: Higher-Order Function

Task: Implement a higher-order function that takes a function and a number, then applies the function to the number.

Steps:

  1. Declare a function applyFunction that takes a function (operation) and a number (value).
  2. Inside the function, apply the given operation to the provided value and return the result.

Code:

function applyFunction(operation, value) {

  return operation(value);

}

const squareFunction = (num) => num * num;

console.log(applyFunction(squareFunction, 4)); // Output: 16

Exercise 8: IIFE (Immediately Invoked Function Expression)

Task: Create an IIFE that logs a message immediately.

Steps:

  1. Write a function expression inside parentheses.
  2. Add an additional set of parentheses to immediately invoke the function.

Code:

(function() {

  console.log(‘IIFE executed!’);

})();

Exercise 9: Recursion

Task: Implement a recursive function to calculate the factorial of a number.

Steps:

  1. Declare a function factorial that takes a number as a parameter.
  2. Use recursion to calculate the factorial.

Code:

function factorial(n) {

  return n <= 1 ? 1 : n * factorial(n – 1);

}

console.log(factorial(5)); // Output: 120

Exercise 10: Closures

Task: Create a closure that counts the number of times it’s invoked.

Steps:

  1. Declare a function counter that initializes a count variable.
  2. Inside counter, return a function (inner function) that increments the count.
  3. Invoke the outer function and use the inner function to increment the count.

Code:

function counter() {

  let count = 0;

  return function() {

    count++;

    console.log(`Count: ${count}`);

  };

}

const incrementCount = counter();

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

These exercises cover a range of scenarios to help you practice and solidify your understanding of basic functions in JavaScript. Experiment with them to gain confidence in using these concepts effectively. 

Quiz questions about Functions

Quiz Questions:

Function Declaration and Expression:

Question: What is the key difference between function declaration and function expression?

A) Function declaration is hoisted, while function expression is not.

B) Function expression is hoisted, while function declaration is not.

C) Both are hoisted.

D) Neither is hoisted.

Answer: A) Function declaration is hoisted, while function expression is not.

Question: Which keyword is used to declare a function in a function declaration?

A) var

B) function

C) declare

D) func

Answer: B) function

Question: How do you define an anonymous function in a function expression?

A) function() { }

B) anonymous() { }

C) () => { }

D) function anonymous() { }

Answer: A) function() { }

Question: Which type of function allows you to write shorter syntax for one-line functions?

A) Callback functions

B) Arrow functions

C) Recursive functions

D) IIFE

Answer: B) Arrow functions

Question: What is the purpose of the return keyword in a function?

A) To terminate the function

B) To return a value from the function

C) Both A and B

D) Neither A nor B

Answer: B) To return a value from the function

Default and Rest Parameters:

6. Question: How do you set default values for function parameters?

A) Using the default keyword

B) By assigning a value in the function body

C) Using the def keyword

D) By using the set keyword

Answer: B) By assigning a value in the function body

Question: What is the purpose of rest parameters in a function?

A) To limit the number of parameters

B) To gather remaining arguments into an array

C) To enforce a specific order of parameters

D) To create optional parameters

Answer: B) To gather remaining arguments into an array

Callback Functions and Higher-Order Functions:

8. Question: What is a callback function?

A) A function that returns a value

B) A function passed as an argument to another function

C) A function that contains only callbacks

D) A function that calls itself

Answer: B) A function passed as an argument to another function

Question: What is a higher-order function?

A) A function that has a higher execution priority

B) A function that returns a higher value

C) A function that takes another function as an argument or returns a function

D) A function that is declared in a higher scope

Answer: C) A function that takes another function as an argument or returns a function

IIFE, Recursion, and Closures:

10. Question: What does IIFE stand for?

– A) Instant Invoked Function Expression

– B) Immediate Invoked Function Expression

– C) Inline Invoked Function Expression

– D) Immediately Invoking Function Expression

**Answer:** B) Immediately Invoked Function Expression

11. Question: In recursion, what is the base case?

– A) The starting point of the recursion

– B) The condition that stops the recursive calls

– C) The final result of the recursion

– D) The recursive function itself

**Answer:** B) The condition that stops the recursive calls

12. Question: What is a closure in JavaScript?

– A) A function that closes over a variable

– B) A function that has an inner function and accesses variables from its outer function

– C) A function that is immediately invoked

– D) A function that closes the browser window

**Answer:** B) A function that has an inner function and accesses variables from its outer function

13. Question: How can you create a closure in JavaScript?

– A) By using the closure keyword

– B) By using arrow functions

– C) By declaring a function inside another function

– D) By using the private keyword

**Answer:** C) By declaring a function inside another function

Coding Exercises:

14. Question: Write a function declaration to calculate the area of a rectangle (length * width).

– A) javascript function calculateArea(length, width) { return length * width; }

– B) javascript const calculateArea = (length, width) => length * width; 

– C) javascript const function calculateArea(length, width) { return length * width; } 

– D) javascript calculateArea function(length, width) { return length * width; }

**Answer:** A) 

function calculateArea(length, width) {

  return length * width;

}

15. Question: Write an IIFE that logs “I am executed immediately!” to the console.

– A) javascript (function() { console.log(‘I am executed immediately!’); })();

 – B) javascript const iife = function() { console.log(‘I am executed immediately!’); }(); 

– C) javascript const iife = () => { console.log(‘I am executed immediately!’); }(); 

– D) javascript (() => { console.log(‘I am executed immediately!’); })();

**Answer:** A) 

(function() {

  console.log(‘I am executed immediately!’);

})();

16. Question: What will the following code output?

const multiplyByTwo = function(number) {

return number * 2;

};

const result = multiplyByTwo(8);

console.log(result);

– A) 16

– B) 10

– C) 18

– D) 4

**Answer:** A) 16

17. Question: Write a higher-order function applyOperation that takes an operation function and two numbers, then applies the operation to the numbers.

– A) javascript function applyOperation(operation, num1, num2) { return operation(num1, num2); } 

– B) javascript const applyOperation = (operation, num1, num2) => operation(num1, num2); 

– C) javascript function applyOperation(operation, num1, num2) { operation(num1, num2); } 

– D) javascript const applyOperation = function(operation, num1, num2) { return operation(num1, num2); };

**Answer:** A) 

function applyOperation(operation, num1, num2) {

  return operation(num1, num2);

}

18. Question: What is the output of the following code?

const greet = (name = ‘Guest’) => {

console.log(Hello, ${name}!);

};

greet(‘Alice’);

– A) Hello, Alice!

– B) Hello, Guest!

– C) `undefined`

– D) Error

**Answer:** A) Hello, Alice!

19. Question: Rewrite the function below using the arrow function syntax:

javascript function multiplyByThree(number) { return number * 3; } 

– A) javascript const multiplyByThree = function(number) { return number * 3; }; 

– B) javascript const multiplyByThree = (number) => number * 3; 

– C) javascript const multiplyByThree(number) => number * 3; 

– D) javascript multiplyByThree = (number) => number * 3;

**Answer:** B) 

const multiplyByThree = (number) => number * 3;

20. Question: What is the purpose of the rest parameter in a function?

– A) To limit the number of parameters

– B) To gather remaining arguments into an array

– C) To enforce a specific order of parameters

– D) To create optional parameters

**Answer:** B) To gather remaining arguments into an array

21. Question: Write a recursive function factorial that calculates the factorial of a number.

– A) javascript function factorial(n) { return n <= 1 ? 1 : n * factorial(n – 1); } 

– B) javascript const factorial = n => n <= 1 ? 1 : n * factorial(n – 1); 

– C) javascript const factorial = function(n) { return n <= 1 ? 1 : n * factorial(n – 1); }; 

– D) javascript const factorial(n) => n <= 1 ? 1 : n * factorial(n – 1);

**Answer:** A) 

function factorial(n) {

  return n <= 1 ? 1 : n * factorial(n – 1);

}

22. Question: What does the acronym IIFE stand for?

– A) Immediately Invoked Function Expression

– B) Inline Instant Function Execution

– C) Immediate Inline Function Expression

– D) Instantaneous Invocation of Function Expression

**Answer:** A) Immediately Invoked Function Expression

23. Question: Which keyword is used to create a closure in JavaScript?

– A) close

– B) inner

– C) closure

– D) There is no specific keyword

**Answer:** D) There is no specific keyword

24. Question: What is the purpose of the apply method in JavaScript?

– A) To apply a function to an array

– B) To apply a function to an object

– C) To apply a function with a given this value and arguments provided as an array

– D) To apply a function to a string

**Answer:** C) To apply a function with a given this value and arguments provided as an array

25. Question: Write a closure that counts the number of times it’s invoked.

– A) 

function counter() {

let count = 0;

  return function() {

    count++;

    console.log(`Count: ${count}`);

  };

}

const incrementCount = counter();

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

– B) 

const counter = () => {

  let count = 0;

  return () => {

    count++;

    console.log(`Count: ${count}`);

  };

};

const incrementCount = counter();

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

– C) 

const incrementCount = function() {

  let count = 0;

  return function() {

    count++;

    console.log(`Count: ${count}`);

  };

};

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

– D) 

let count = 0;

const incrementCount = () => {

  count++;

  console.log(`Count: ${count}`);

};

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

**Answer:** A) 

“`javascript

function counter() {

  let count = 0;

  return function() {

    count++;

    console.log(`Count: ${count}`);

  };

}

const incrementCount = counter();

incrementCount(); // Output: Count: 1

incrementCount(); // Output: Count: 2

26. Question: Which of the following statements is true about arrow functions?

– A) Arrow functions can have their own this context.

– B) Arrow functions cannot be used as higher-order functions.

– C) Arrow functions cannot be immediately invoked.

– D) Arrow functions cannot have default parameters.

**Answer:** A) Arrow functions can have their own `this` context.