which is the better way of defining a function? [duplicate]
Asked Answered
Y

2

6

Is there any difference between them ? I've been using both the ways but do not know which one does what and which is better?

function abc(){

    // Code comes here.
}

abc = function (){

    // Code comes here.
}

Is there any difference between defining these functions ? Something like i++ and ++i ?

Yoon answered 13/6, 2013 at 11:13 Comment(6)
repeated Question: #337359Amoroso
Why did you add the html tag again? This question has nothing to do with HTML!Innocence
that's becuase people may consider this question to that of java - which uses object oriented approach...Yoon
The question is already tagged javascript. It's clear that it has nothing to do with Java. If someone does not know that there is a difference between JavaScript and Java, they shouldn't be programming.Innocence
All right!! Should i remove that now ??Yoon
Okie.. will do it...thanx....Yoon
C
7
function abc(){

    // Code comes here.
}

Will be hoisted.

abc = function (){

    // Code comes here.
}

Will not be hoisted.

For instance if you did:

 abc(); 
 function abc() { }

The code will run as abc is hoisted to the top of the enclosing scope.

If you however did:

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

abc is declared but has no value and therefore cannot be used.

As to which is better is more of a debate of programming style.

http://www.sitepoint.com/back-to-basics-javascript-hoisting/

Cryptography answered 13/6, 2013 at 11:15 Comment(2)
Nitpick: "Then abc is not yet declared and cannot be used." Variable declarations are hoisted too, so the variable is declared, but it has no value yet.Innocence
@FelixKling - updated. Cheers.Cryptography
B
1

Short answer: none.

You are putting the function in the global namespace. Anyone can access this, anyone can overwrite this.

The standard more safe way to do it is wrap everything in a self calling function:

(function(){
    // put some variables, flags, constants, whatever here.
    var myVar = "one";

    // make your functions somewhere here
    var a = function(){
        // Do some stuff here

        // You can access your variables here, and they are somehow "private"
        myVar = "two";
    };


    var b = function() {

        alert('hi');
    };

    // You can make b public by doing this
    return {
        publicB: b
    };
})();
Bristling answered 13/6, 2013 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.