0

I'm sorry if my question seems silly but I'm still not clear about the difference of various modes of calling a function. EXAMPLE:

function a(name) {
  console.log("hello " + name);
}


// Case 1:
a("John");

// Case 2:
console.log(a("John"));

// Case 3:
var b = a;
console.log(b("John"));

ps: Also I haven't grasp the need of a return statement(except that stops the function after being executed). Is it not the same if i use an alert(), console.log() or another function that can fulfil the same purpose?

VLAZ
  • 18,437
  • 8
  • 35
  • 54
  • "*Also I haven't grasp the need of a return statement(except that stops the function after being executed)*" Compare what case 1 prints (`"hello John"`) and what the other two print (`"hello John"`, `undefined`) – VLAZ Nov 05 '20 at 16:57

2 Answers2

1

Nothing.

Functions are first class objects. You can assign them to other variables (or properties or pass them as arguments or return them etc) freely.


That said, how you call a function can impact the value of this inside it, see How does the “this” keyword work?).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
-1

Adding a function to a variable will store a reference to the outcome of the function in the variable. This way the variable can be reused. When you call a function by it self the outcome is instantly produced.

The return statement return the outcome of the function. Console.log only return the outcome to the console what great for checking your code but not helpful when you want the outcome to be part of your code.

Alert() outdated. I would avoid using it.

329seven
  • 9
  • 3
  • 2
    "*Adding a function to a variable will store the outcome of the function in the variable.*" not true `var b = a` will not execute `a` it just stores a reference to it. – VLAZ Nov 05 '20 at 17:01