Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, what is the difference between window.function(){} and var variable = function?

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?

like image 853
Tahir Raza Avatar asked Aug 28 '17 11:08

Tahir Raza


People also ask

What is the difference between VAR and function in JavaScript?

A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call. But a function can be a variable, too, as it stores data and values, too. See the following syntax: var functionname = function(){} .

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

What is window function in JavaScript?

The window object is supported by all browsers. It represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object.

What are the two types of functions in JavaScript?

Functions in JavaScript are very similar to those of some other scripting high-level languages such as TypeScript and there are two types of functions: predefined and user-defined.


1 Answers

// 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

like image 144
Artem Avatar answered Jan 17 '23 09:01

Artem