0

Is there ANY difference in the following two ways of defining a functions?

METHOD 1)

var printName = function(name){
    return("Hi! My name is ",name)
}

VS

METHOD 2)

function printName(name){
    return("Hi! My name is ",name)
}

and I mean ANY, I'm new at JS and want to lay down my understanding of functions and Objects before I advance as I feel these 2 features are the 2 I'll use the most.

  • AFAIK there is no difference (in performance) if both defined in the same scope. – MaxZoom Jun 16 '15 at 19:32
  • 1
    Notice that `return` is not a function you can call, it is a keyword. Don't use parenthesis. And I'm pretty sure you wanted to do string concatenation, not the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator), so use `return "Hi! My name is "+name;` – Bergi Jun 16 '15 at 19:35
  • +Bergi hate to be a pain. but whats the diffrence in using "commar operators" and a "string concatenation"? –  Jun 16 '15 at 20:03

2 Answers2

3

Yes there is a difference, but none that would affect the performance of the function code when it's called.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

The difference has to do with when the function is created, but the performance is identical. Using your examples:

printName_1("Drew"); // This will fail, as printName_1 is not defined (yet)
printName_2("Yuannan Lin"); // This will work

var printName_1 = function(name){
    return "Hi! My name is "+name;
}

function printName_2(name){
    return "Hi! My name is "+name;
}

Functions that are declared using the latter syntax are initialized at the beginning of the block where they appear, so it looks like they can be called before they are defined.

Drew
  • 761
  • 5
  • 9