8

I am working on a javascript code where functions are defined in three different ways.

funtion f1(){}

and second

var vaiable = f1(){}

and third

window.f1 = function(){}

I have read about the first two here but don't know about the last one.

Will there be a problem if I change the third one to the second one?

What are the pros and cons of third type?

Why it is used particularly?

Tahir Raza
  • 726
  • 1
  • 7
  • 20
  • 2
    It depends on what exactly you want this to do. In general, you should avoid #3 unless really necessary. – deceze Aug 28 '17 at 11:58
  • 2
    Possible duplicate of [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Roman Aug 28 '17 at 12:00

4 Answers4

5
// this is function declaration in JavaScript
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
function myFunction (/* args */) { /* body */ }

// this is function expression
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
const/var/let myFunction = function myFunction(/* args */) { /* body */ }

// this is basically (unnamed) function expression, defining property `f1` on global object `window`
window.f1 = function (/* args */) { /* body */ }

If you change the third approach to the second one, it will become bound to some scope (the block, where it's going to be put). While the third one is always global (it is available from anywhere).

Note that you can also declare function in the global scope, using 1st and 2nd approaches. For example:

<head>
    <script>function myFunction() {/* body */}</script>
</head>

Please, look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope

Artem
  • 1,937
  • 1
  • 14
  • 19
  • This is also helpful https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Function_constructor_vs._function_declaration_vs._function_expression – Artem Aug 28 '17 at 12:19
2

The third one is assigned to the global scope (window in browser, global in Node environment) thus it's accessible everywhere like e.g. console object.

lukaleli
  • 3,427
  • 3
  • 22
  • 32
0

window.f1 = function(){} ==> since you are attaching it to window, it will explicitly make your function global and accessible from everywhere

funtion f1(){} and var vaiable = f1(){} ==> this way your function can be global or local based on whether they are encapsulated in another function.

Nemani
  • 778
  • 5
  • 12
0

All of the three stated function declaration/expressions will produce global function as well. But be aware of the third function expression:

window.f1 = function(){};

which works well in browser but will throw an error in other environments like Node due to the difference of global object.

Andy Tan
  • 51
  • 1
  • 2