How to write Nested Functions in JS & PHP
Tags: webdev, javascript, php, tutorial
Published: 2022-06-03 00:34:30

Today I will show you how you can write and access nested functions in both JavaScript and PHP.

> Nesting a Function means having multiple functions called **child functions** within a particular Function called the **parent function**.

In order to Nest a Function, you must have a parent function, then child function(s) within it.

## Let's Start off with JavaScript

Let's assume that we are building a simple calculator that will return the child functions  **( plus )** and ** ( minus )**.

The **Plus** will simply add up the numbers provided and the **minus** will simply subtract the numbers provided.

### Parent Function
We will start off by declaring the parent function as **calculate()** to accept 2 parameters which are (x, y).

```javascript
function calculate(x, y){
    /**
    * @calculate: Returns child functions 
    * @ x : Value 1 of type int
    * @ y : Value 2 of type int
    **/

}
```
Now let's declare a *local variable* to hold the parameters x and y, then multiply it by (1) to make sure that we are really working with *Numbers*.

```javascript
function calculate(x, y){
    /**
    * @calculate: Returns child functions 
    * @ x : Value 1 of type int
    * @ y : Value 2 of type int
    **/

   let a = x * 1;
   let b = y * 1;

}
```
### Child Function

Let's declare a child function that will return the sum of the values. We will call this function **add()** then we will pass in the parameters **(a, b)**.

```javascript
function calculate(x, y){
    /**
    * @calculate: Returns child functions 
    * @ x : Value 1 of type int
    * @ y : Value 2 of type int
    **/

    let a = x * 1;
    let b = y * 1;

    function add(a, b){
        return ( a + b );
    }
}
```
Now, let's test out this simple function by returning an object with a custom name and our child function as its value.

```javascript
function calculate(x, y){
    /**
    * @calculate: Returns child functions 
    * @ x : Value 1 of type int
    * @ y : Value 2 of type int
    **/

    let a = x * 1;
    let b = y * 1;

    function sum(a, b){
        return ( a + b );
    }

   return {
       plus : sum
   }
}
```
This practically means that anytime we access the returned value **plus**, our calculate function will execute its child function **sum()**.

Let's declare a variable that will hold our function and its properties.

```javascript
var calculate = calculate();
```

Now I will show you two ways to access our function properties. Think of it like you're accessing an object.

We will access **plus** property and pass in parameters ( 5, 5 ) to return the sum of the two values.

- The *dot notation*

```javascript
var calculate = calculate();
var sum = calculate.plus(5, 5);
console.log(sum);
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1638796442226/XxdKcM4MI.png)


- Using *square brackets*

This method is quite tricky. But in **PHP**, this is also one of the ways I could think of that can be used to access nested functions.

Using this method means that you have to pass in the property that you're trying to access as a string, then output the result by passing in your parameters.

Sounds confusing right? Take a look at the code below.

```javascript
var calculate = calculate();
var sum = calculate['plus'];
console.log(sum( 5, 5 ));
```
We have assigned the function property **plus** to the variable **sum**, passing no parameters.

Now we output the value from the sum variable by passing values (5, 5).

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1638797019838/Wt77FH4OI.png)

As you can see, it's the same Output.

### More Child Functions

Let's add 2 more child functions to subtract our values or multiply them.

```javascript
function calculate(x, y){
    /**
    * @calculate: Returns child functions 
    * @ x : Value 1 of type int
    * @ y : Value 2 of type int
    **/

    let a = x * 1;
    let b = y * 1;

    function sum(a, b){
        return ( a + b );
    }
    function subtract(a, b){
        return ( a - b );
    }
    function multiply(a, b){
        return ( a * b );
    }

   return {
       plus : sum,
       minus : subtract,
       times : multiply
   }
}
var calculate = calculate();
var sum = calculate.plus(5, 5);
var subtract = calculate.minus(5, 5);
var multiply = calculate.times(5, 5);

console.log('sum = '+sum);
console.log('minus = '+subtract);
console.log('times = '+ multiply);
```
Now, this is the exact output that we need.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1638797696310/y_L4cS03O.png)

That's it for JavaScript Nested Functions.

## PHP

Well, the process is still the same in PHP except that you can't access the property of a nested function using the **dot notation**.

This is because the dot notation known as the **concatenator**, is used to join two strings or variables together.

We still have 2 available ways of accessing our Nested Function.

- Using a global Variable

We will declare a global variable to hold our function and its properties, then pass in parameters at the same time, then we will use the **square brackets** to access our variable properties.

Note that we will also pass in the parameters to the child functions in our return value.

```php
function calc($x, $y){
    $a = $x;
    $b = $y;
    function sum($a, $b){
        return ($a + $b);
    };

    $retval = [
    "sum" => sum($x, $y) //pass in the param for child function sum()
    ];

    return $retval;
}
//Bind function to variable
$calcs = calc(1,2);

//Return all properties as an array
//var_dump($calcs); 

//access the sum property
echo ($calcs['sum']);
```
Now, this is the exact output that we expect.
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1638798606242/YxX68M5Jb.png)

- Using a Variable then calling its properties like they were all declared as functions.

Before I show you this method, Let us add some child functions.

```php
function calc($x, $y){
    $a = $x;
    $b = $y;
    function sum($a, $b){
        return ($a + $b);
    }

   function subtract($a, $b){
        return ($a - $b);
    }

   $retval = [
       "sum" => sum($x, $y),
       "minus" => subtract($x, $y)
    ];

    return $retval;
}
```
Now because we are returning our child functions with parameters passed directly to it, we can call the child functions directly anywhere on our page.

```php
function calc($x, $y){
    $a = $x;
    $b = $y;
    function sum($a, $b){
        return ($a + $b);
    }

   function subtract($a, $b){
        return ($a - $b);
    }

   $retval = [
       "sum" => sum($x, $y),
       "minus" => subtract($x, $y)
    ];

    return $retval;
}
//add a dummy value to prevent argument count error
$calcs = calc(1, 1);

//add child function
echo ("20 + 10 child function = ".sum(20, 10)) .'<br>';

//subtract child function
echo ("20 - 10 child function = ".subtract(20, 10));
```
This is once again the output that we need.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1638799904849/3y4sd3Gp5.png)

I hope you've understood what Nested functions are, and how to write them in both JavaScript and PHP.

You have reached the end of my article.

## EXTRA

I recently launched a JavaScript package that validates your HTML forms using validation rules, regular expressions and form input attributes.

I will appreciate if you spared a few seconds to check it out.

{% embed https://www.producthunt.com/posts/octavalidate %}

Thank You.