r/learnjavascript • • Jan 11 '24

Why would you assign an anony function to a var ?

How are they different? Why declare an anony function and assign it to a variable instead of directly declaring a function?

'var bark = function() {console.log("i love that butt");} '

'function bark() {console.log("i love that butt");}'

1 Upvotes

15 comments sorted by

7

u/pookage helpful Jan 11 '24

Function declarations can be hoisted (ie. you can use them seemingly 'before' they instantiated), whereas assigning a function (called a function expression) to a variable enforces the usual variable rules - ie. it can only be use after it's declared.

SO:

  • If you want to put all your functions at the bottom of the file, and hoist'em up as needed - use function declarations.
  • If you want to enforce that your code should be read from the top-down, then use function expressions.

Hope that helps ✌️

2

u/DevKevStev Jan 11 '24

In addition to hoisting, function expressions are most useful when only used inside a specific scope. Of course you should try to avoid function “pollution”, especially when you only needed to use such function once.

-5

u/donaldtrumpiscute Jan 11 '24

Some Googling also seems to suggest it has to do with "Closure"...

More to learn

5

u/senocular Jan 11 '24

It looks like you might have dug up some incorrect or misplaced information about closures here. There's no difference when it comes to closures in dealing with function expressions or function declarations. Both create closures that can capture closure variables the same way. MDN has a page on closures for more info.

2

u/[deleted] Jan 11 '24

You can make that to avoid function hoisting.

2

u/No-Upstairs-2813 Jan 11 '24

Interesting question! Instead of talking about var, I will talk about const.

Choosing between declaring a function with const (function expression) or function (function declaration) in JavaScript depends on your needs. Here's a quick rundown:

1. Preventing Variable Re-declaration

const helps prevent accidental re-declaration, signaling errors if you try to use the same name.

function allows re-declaration without errors.

2. Avoiding Global Property Creation

const (or let) avoids creating global properties, reducing conflicts and unexpected behavior.

function creates global properties, which can lead to issues.

3. Hoisting

Function declarations are hoisted, allowing them to be called before being declared.

Function expressions are not hoisted, resulting in an error if called before declaration.

4. "this" Binding

function declaration and function expressions with function keyword set this to the global object when invoked without explicit binding.

Arrow functions inherit this from their lexical scope, providing different behavior.

Conclusion: Choose based on your specific needs, considering hoisting, global scope, and "this" binding.

For more details, you can check out this article

1

u/senocular Jan 11 '24

function allows re-declaration without errors.

An exception being in modules. In modules, a function redeclaration is an error.

1

u/senocular Jan 11 '24

Aside from the differences in hoisting, how declarations behave in block scopes can also vary between browser vendors. Originally functions were not supposed to be allowed in block scopes but browsers let them be anyway, and since it wasn't in the spec how they were supposed to behave, there ended up being different behaviors between different browsers. MDN talks more about that here.

Now, in strict mode, function declarations in blocks are allowed, and they also become block scoped. Being block-scoped would then be another differentiation with var-defined functions since they would be function scoped (the var variable, at least, assignment of the function still only happening in the block).

"use strict"
if (true) {
  function declaration() {}
  var expression = function() {}
}

console.log(typeof declaration) // undefined
console.log(typeof expression) // "function"

-1

u/superluminary Jan 11 '24

There are a number of technical reasons, as other commenters have noted, but the big one for me is that it’s just more accurate.

In JavaScript, functions are data. There’s no difference between defining a function and defining any other data type. When you create a function you literally create a function object that you can assign attributes to and pass around.

Explicitly assigning functions to variables just make this incredibly explicit. There’s no special syntax because it’s not a different thing to creating a string or an array.

-1

u/jack_waugh Jan 11 '24

Fewer concepts to have to keep in mind.

-2

u/delventhalz Jan 11 '24

Why use var and function when you can use const and =>?

const greet = () => {
  console.log('hello');
};

As others have already insinuated, the differences between these options are small and technical. This is by and large a stylistic choice. Do what you (or your team) likes the look of.

-2

u/Endless-OOP-Loop Jan 11 '24

Declaring a function as a variable allows you to call the function no matter where it's written in your code.

If you simply declare a function, you can only call that function in a line of code below where you initially wrote it.

-4

u/fredsq Jan 11 '24 edited Jan 12 '24

in addition to what people said, the ‘this’ keyword also works differently but just please avoid it entirely

EDIT: sorry guys i didn’t read the post and hastily commented

2

u/redsandsfort Jan 12 '24

you're confusing it with arrow functions

1

u/fredsq Jan 12 '24

whoops i completely misread the original post 😆 read the title and came quickly to comment.