Nested functions in JavaScript

Suppose we have a function that takes two numbers as a parameter and returns the sum of the squares of these numbers:

function func(num1, num2) { return num1 * num1 + num2 * num2; } console.log(func(2, 3)); // shows 13 (the result of 2 * 2 + 3 * 3)

Let's take the squaring operation into the auxiliary function square:

function square(num) { return num * num; } function func(num1, num2) { return square(num1) + square(num2); } console.log(func(2, 3)); // shows 13

Let us be sure that the function square will be used only in the function func and not in any other.

In this case, it would be convenient to make sure that no one accidentally uses it (you yourself or another programmer working with you).

JavaScript has a neat solution: we can put our helper function square inside func. In this case, our helper function will only be available inside func and not outside.

Let's do it:

function func(num1, num2) { function square(num) { return num * num; } return square(num1) + square(num2); } console.log(func(2, 3)); // shows 13

Attempting to call square outside func will result in an error:

function func(num1, num2) { function square(num) { return num * num; } return square(num1) + square(num2); } console.log(square(2)); //!! throws an error

Make the function func that will take two numbers as parameters and return the sum of the square of the first number with the cube of the second number. To do this, make the helper function square, squaring the number, and the helper function cube, raising the number to the cube.

enru