Why should I assign a function to a variable in javascript?

Possible duplicate:
JavaScript: var functionName = function () {} vs function functionName () {}
What is the difference between a function expression and a declaration in Javascript?

I am trying to understand the "best practices" of javascript.

This code is from jqfundementals.com

// create a function that will greet a person, // and assign the function to the `greet` variable var greet = function( person, message ) { var greeting = 'Hello, ' + person + '!'; log( greeting + ' ' + message ); }; greet( 'Jory', 'Welcome to JavaScript' ); greet( 'Rebecca', 'Thanks for joining us' ); 

Why should I assign a function to a hello variable?

My first impulse would be to write it like this:

 function greet ( person, message ) { var greeting = 'Hello, ' + person + '!'; log( greeting + ' ' + message ); }; 

What are the differences between the two implementations?

+4
source share
2 answers

There is no difference between these fragments, except for the lift, which allows you to call the old function in the lines before the definition. But this is just a simplified example to get you warm. In fact, people do not assign these functions to variables, but pass them directly to other functions. Or they otherwise use them in expression contexts. Or they dynamically decide which function to store. Or something else really.

+1
source

There is no real difference, but the var form allows you to declare-up-use if you have recursive functions.

A simple example:

 var func1, func2; func1 = function (count) { count = count - 2; if (count > 0) { func2(count); } } func2 = function (count) { func1(count + 1); } func1(10); 

Although

 function func1 (count) { count = count - 2; if (count > 0) { func2(count); } } function func2 (count) { func1(count + 1); } func1(10); 

quite acceptable. The interpreter will replace him first because of the variable lift.

-2
source

Source: https://habr.com/ru/post/1433438/


All Articles