0

Can you please explain why would the return function in doctor1 function bellow could be better that the one in the doctor 2?

//-----------------Doctor 1--------------------------

function doctor1() {
  return function() { alert("How are you, today?"); };
}

var x = doctor1();
x();


//-----------------Doctor 2--------------------------

function doctor2() {
  return alert("How are you, today?");
}

doctor2();

//-------------------------------------------
Aseel
  • 57
  • 11
  • Possible duplicate of [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Ken White Jun 16 '17 at 18:22
  • What do you mean by _be better_? – pishpish Jun 16 '17 at 18:23
  • @destoryer, I mean which one is correct or if there is some case where you want to use one than the other! – Aseel Jun 16 '17 at 18:34

1 Answers1

1

In your particular case there's not really a difference. But if you wanted to create functions that retain some state (i.e. create closures), returning a function could be useful:

By the way, your doctor2 function doesn't need a return statement, because alert doesn't return anything.

Edit: I'd like to clarify that the function you return doesn't have to be anonymous:

function doctor1(num) {
  return function() {
    alert("How are you, today? " + num);
  };
}

var functions = [];

for (var i = 0; i < 3; i++) {
  functions.push(doctor1(i));
}

// The functions "remember" the values 0, 1, and 2 
for (var i = 0; i < functions.length; i++) {
  functions[i]();
}
function doctor1(num) {
  return function myFunc() { alert("How are you, today? " + num); };
}

Naming the function like this can help when debugging. If the function throws an error, you'll see the function name in the console.

Rifky Niyas
  • 1,737
  • 10
  • 25
Frank Modica
  • 10,238
  • 3
  • 23
  • 39
  • Thank you for the your help. If you don't mind why then when I alert the functions array the num was not replaced with the number assigned? – Aseel Jun 16 '17 at 18:59
  • If you do `alert(functions)` you are just going to see the text of the function. But if you do `console.log(functions)` and open your dev tools, you can dig down into each function and some browsers will show you the closures (works for me on Chrome). So you can actually see the number that the function encloses (like 0, 1, or 2). – Frank Modica Jun 16 '17 at 19:05
  • @Aseel I edited my answer to further clarify that the function returned doesn't have to be anonymous. – Frank Modica Jun 17 '17 at 15:31