Functions

why do we do this,

var someVariable= function()
{}

// instead of,

function someFunction()
{}

Hello @saumyath1997, welcome to the forums! The first one is an example of an anonymous function (I believe). This means the function itself isn’t named, but the value returned from the function when it is executed is. The function in the var someVariable can be replaced:

var someVariable = function(){}
someVariable = 6;//this is fine

The second one is an example of a normal function, with a class function. That means that this is only a function, and can’t be re-written as anything else.

I hope this helps!

Nowadays we would write it,

const foo = function () {}

to protect the function from being overwritten or deleted.

The two functions are identical in behavior, but only the declared function (example 2) is hoisted. It too is vulnerable to being overwritten or deleted so the preferred form is the function expression above.

The variable becomes the name we can invoke the function by. It is a reference to an anonymous function.

Both of these forms may be used as constructor functions, something we cannot do with arrow functions.

1 Like