Introduction and Overview

Welcome back, Explorer! Today's adventure dives into JavaScript, exploring function invocation, calling independent functions within a function, and working with default argument values.

A function invocation refers to calling or triggering a function. Invoking independent functions within another combines their outputs. If no specific value is passed, default argument values are used. Are you ready to decode these concepts? Let's get started!

Understanding Function Invocation

Remember, a function acts only when we invoke or call it. Consider the function sayHello, invoked by sayHello(). Here's an illustration:

// Function defined (just a blueprint for now)
function sayHello() {
  console.log("Hello!");
}

// Function invoked (blueprint turned into reality)
sayHello();  // Output: "Hello!"

Function invocation in JavaScript is akin to using a recipe — you 'invoke' the recipe to make the cookies!

Invoking Independent Functions Inside a Function

Very often, we need to combine the outputs of different functions. That's when invoking independent functions within another becomes handy.

Imagine you have two distinct functions, sayHello and sayGoodbye. Now, crafting a greet function to invoke sayHello and sayGoodbye would look like this:

// Defining independent functions
function sayHello() {
    console.log("Hello!");
}

function sayGoodbye() {
    console.log("Goodbye!");
}

// Invoking them inside another function
function greet() {
    sayHello();
    sayGoodbye();
}

// Calling the greet function
greet();
/*
Prints:
Hello!
Goodbye!
*/

Voila! Both "Hello" and "Goodbye" are presented together by invoking sayHello and sayGoodbye within greet.

Using Other Functions Results

Often, while writing functions, you would want to utilize the result of one function inside another. In such cases, you would call a function inside another function.

Take an example of a function findSum that adds two numbers and another function getAverage that finds the average of two numbers. To get the average, we must first find the sum. Hence, we need to call findSum inside getAverage. Here's how it is done:

// Define `findSum` function that returns the sum of two numbers
function findSum(num1, num2) {
  let sum = num1 + num2;
  return sum;
}

// Define `getAverage` function
function getAverage(num1, num2) {
  // Call findSum inside getAverage
  let sum = findSum(num1, num2);
  let avg = sum / 2;
  return avg;
}

// Test the function
let average = getAverage(10, 20); // Output: 15

In our getAverage function, we first call the findSum function, which returns the sum of num1 and num2. This sum is then used to calculate the average. This is how you can call functions inside functions!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal