dukegod dukegod - 1 month ago 16
Javascript Question

difference between “function with return” and “function without return”

how to access to inner function by js. in other word, what's difference between “function with return” and “function without return”

"with return"

function makeAdder(x) {

function add(y) {
console.log(x,y)
return x+y;
};

return add;

}

makeAdder(3)(4) // 7


without

function makeAdder(x) {

function add(y) {
console.log(x,y)
return x+y;
};
}

makeAdder(3)(4) // error


if i want to access "add()" like "makeAdder(3).add(4)",how to code ?

Answer

When a function has no return statement, it implicitly returns undefined. If you want to call .add like you described, your function should return an object with an add property:

function makeAdder(x) {
    return {
      add(y) {
        return x+y;
      }
    };
}

console.log(makeAdder(3).add(4))   // 7

Alternatively, you could also use ES6 classes for a more traditional OO approach:

class Adder {
  constructor(x) {
    this.x = x  
  }
  
  add(y) {
    return this.x + y
  }
}

console.log(new Adder(3).add(5))