2426021684 2426021684 - 2 years ago 61
Javascript Question

There are several different ways that a Javascript function can be declared. Which way is appropriate under which circumstances?

In javascript functions can be created in the following ways:

function f(x){ return x * x }
const f = function (x){ return x * x }
const f = x =>{ return x * x }
const f = x => x * x

I understand the differences between them (arrow function do not have their own this and functions defined as variables cannot be used before they are defined). Under what circumstances should each way be used?
I am looking for answers like if you are doing x use this format, but if you are doing y use that format. Some situations would include callbacks, recursive functions, and which one should use be used when in doubt. What is the convention?

Answer Source

Distinct function constructions have been built up for achieving the same goal with ease in various situations. For example, suppose you've to switch between different functions with same id "_fn" but different body/behavior. Then, applying the "const" statement to the ternary operator, throws a syntax error. Try:

( 1 ) ? const _fn = function (x){ return x * x ; } : const _fn = function (x){ return 2*x ; } ;

Actually the "const" construction does not fit here, infact right the "const" token is detected as "unexpected". The following statement works anyway:

var _fn = ( 1 ) ? function f(x){ return x * x ; } : function f(x){ return 2*x; } ;
console.log( _fn(3) );

Try changing '1' to '0'. This is the first example came up into my mind.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download