[Solved] How does a return statement differ from an equal sign?


const pet = function() {
  return {cat: 10};
}

Here an anonymous function is being assigned to pet. pet now has properties like length and name, properties that apply to functions. But cat isn’t a property of pet, it’s a property of the object created when you run pet. You have to include those parentheses for the Javascript engine to understand that you want to run the function, not refer to the function itself. Only then can you make the mental substitution of the cat-containing object. So, if you want to see the cat property of the returned object, you would use console.log(pet().cat);.

Being able to refer to functions directly instead of running them all the time comes in handy! It lets us pass entire functions around, not just their results:

const func = function() {
  let r = Math.random();
  console.log(r);
}
window.setInterval(func, 1000);

This sends a random number to the console every second, because we passed the function we want to run to window.setInterval. If func was equivalent to its (undefined) return value, window.setInterval wouldn’t get anything and wouldn’t know what to do with it.

4

solved How does a return statement differ from an equal sign?