0

What is the difference between these two way of defining a method?

 var Todo = {};
    Todo.abc = function(){
    }

and

function abc(){
}
Raaz
  • 1,669
  • 2
  • 24
  • 48
  • 3
    One is a function and one is a variable assignment – scrappedcola Jun 08 '17 at 13:29
  • 2
    Try some [rubber duck problem solving](https://blog.codinghorror.com/rubber-duck-problem-solving/). To answer your question, they're actually both similar in that they have a letter **`n`** in the word `function`, unlike your title. Actually, your question is malformed--you cannot ask "what is the difference between these two way [sic] of defining a method", because they are not both methods. I'd start off with learning correct terminology (for example, `abc` is not a "keyword") and take it from there. –  Jun 08 '17 at 13:31
  • @scrappedcola, variable assignment? I thought i added a function value to the abc keyword of Todo object – Raaz Jun 08 '17 at 13:33
  • 1
    `abc` is just a variable in an object. You are thinking in more java terms and that often does not directly apply to JS. The variable assignment is just assigning an anonymous function to the variable `abc`. Functions are just objects that are assignable like any other. – scrappedcola Jun 08 '17 at 13:35

2 Answers2

3

The first is an anonymous function expression, stored in the abc property. These are not hoisted.

The second is a function declaration. It has a name property and it is hoisted.

From MDN:

The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions.

Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you define them:

Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

First is a Todo property, second is a global function. In fact, in order to call the first one you have to write

Todo.abc();

Note that Todo.abc = 'Hello' will overwrite instance property.

  • if I create the global function would not it clutter the global namespace? Should i avoid defining global methods? – Raaz Jun 08 '17 at 13:31
  • 1
    @Raaz it isn't a completly true statement that `abc()` is a global function. It is a global function in the context of the current scope which might not be the global scope. – kidwon Jun 08 '17 at 13:35
  • 1
    You can create a your own namespace upon global namespace. See https://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript – Nicolò Boschi Jun 08 '17 at 13:35