rahul2001
rahul2001

Reputation: 1657

Nested functions in closure not being called properly in Javascript

I am new to Javascript and learning about closures and nested scope.

The prompt asks for this: Write a function that has three nested functions, each taking one number as an argument. The inner-most function should return the sum of all three numbers.

This is what I have come up:

var outMost = function (num1) {
var x = num1;
var innerMost = function (num2) {
    var y = num2;
    var innerInnerMost = function (num3) {
        console.log(x + y + num3);
    }
    return innerInnerMost;
}
return innerMost;
}

var firstNum = outMost(1);
firstNum(2);
firstNum((3));

Please help me understand what I am doing wrong -- I have gone on numerous website to learn about closures and scope but nothing seems to explain it well. Thank you for the help.

Upvotes: 2

Views: 277

Answers (3)

MEAbid
MEAbid

Reputation: 550

very easy look at this example

if you have this type in ES6

  let f = () => {
  return () => {
    console.log('First function called');
    return () => {
      console.log('Second function called');
    }
  }
}

you have two way to call every function, first of all, I want to call the First function in this way f()() and then I want to call the Second function f()()(). First of all, you will be seeing in console

First function called

and then

Second function called

and another way you can use this technic

let f1 = f();
let f2 = f1();

you will be seeing

First function called

if you want to the second function call

let f1 = f();
let f2 = f1();
let f3 = f2();

and then you will be seeing

Second function called

if you want to change this code to ES5

var f = function() {
  return function() {
    console.log('First function');
    return function(){
      console.log('Second function');
    }
  }
}

two way of call

var f1 = f();
var f2 = f1();
var f3 = f2();

f()()();

Upvotes: 0

Dhiraj Gophane
Dhiraj Gophane

Reputation: 1

function firstFunc(x){
    return function secondFunc(y){
            return function thirdFunc(z){
                    console.log(x+y+z);
                }
        }
}

Calling:

var ff = firstFunc(1);

var sf = ff(2);

sf(3);

Upvotes: 0

Harry Pehkonen
Harry Pehkonen

Reputation: 3038

When you call firstNum(2), you are not catching the return-value (which is a function). If I run your code in Node.js REPL, here is what it looks like:

> var firstNum = outMost(1);
undefined
> firstNum(2);
[Function]
> firstNum((3));
[Function]

Try this in the end instead:

var firstNum = outMost(1);
var secondNum = firstNum(2);
secondNum(3);

Here is what it looks like in Node.js REPL:

> var firstNum = outMost(1);
undefined
> var secondNum = firstNum(2);
undefined
> secondNum(3);
6
undefined

Please note that assignment evaluates to undefined. Also, since innerInnerMost doesn't return anything, there is an implicit return undefined in the end.

Upvotes: 1

Related Questions