Functions in JavaScript

Posted on by By Nikhilesh, in Front End, Javascript | 0

Consider the given code below:

1:    function doSomething(a) {
2:        function doSomethingElse(a) {
3:            return a - 1;
4:        }
5:        var b;
6:        b = a + doSomethingElse( a * 2 );
7:        console.log( b * 3 );
8:    }

doSomething( 2 );

 

By considering above code, if you are learning JavaScript, you might get 9 as your answer. But think twice. Or let me explain you in a better way.

First you have to understand that JavaScript treats functions as its first class citizens. Meaning, JavaScript compiler will first compile functions.

Hence in the above code, let me breakdown into smaller segments and see what is happening where. So firstly we start at line 6 which says:

b = a + doSomethingElse( a * 2 );

 

Again narrow down line 6 and consider:

doSomethingElse( a * 2 );
// returns 4

 

Now the JavaScript compiler goes to line 2:

function doSomethingElse(a) {
    return a - 1;
}

// returns 3 because now a is 4 but not 2

 

And again compiler comes back to line 6 and re-compiles the code:

b = a + doSomethingElse( a * 2 );

Now b returns 5 because doSomethingElse( a * 2 ); is 3 now (which is returned from above function doSomethingElse)

 

Hence the result is 5 * 3 = 15.

As a beginner, it is recommended to understand what is happening at the background and visualize it before start coding actual code. Cheers..!! Happy Coding.

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

-By
Uma Maheswar
Helical IT Solution

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments