What are the advantages / disadvantages for creating a top-level function in ES6 with or without arrows?

What are the advantages / disadvantages for creating a top-level function in ES6 / ES2015 in different ways? Or is it just a matter of taste / style guidance, etc.

Option 1:

function square(n) {
   return n * n;
}

Option 2:

var square = function(n) {
  return n * n;
};

Option 3:

var square = (n) => {
   return n * n;
};

Option 4:

const square = (n) => {
   return n * n;
};
+4
source share
2 answers

Note: I posted this as a community wiki, we can all add to the list, clarify, etc. Please do not judge. Keep it objective.


Or is it just a matter of style and style guidance?

, , , , , .

1:

function square(n) {
   return n * n;
}
  • ( ).
  • ES2015 (ES6), ; ES2015 + , .
  • square = ... ( ).
  • square.prototype, .
  • (, , ), .
  • this, , , "" .

2:

var square = function(n) {
  return n * n;
};
  • ( ), .
  • ES2015, , . ES2015 + ( , , -, ES2015).
  • square = ...
  • square.prototype, .
  • (new square) , , , , .
  • (, , ), var.
  • this, , , "" .

2.5: ( )

var square = function square(n) {
  return n * n;
};

2, , ES5 (square). ( , , , .)

3:

var square = (n) => {
   return n * n;
};

:

var square = n => n * n;
  • ( ), .
  • ( , , -, ES2015).
  • square = ...
  • square.prototype.
  • (new square) (TypeError: square is not a constructor).
  • arguments ( arguments ).
  • Per spec , , this arguments. JavaScript- arguments, , this .
  • (, , ), var.
  • , this, this , , this ( , ).

4:

const square = (n) => {
   return n * n;
};

:

const square = n => n * n;
  • , .
  • ( , , -, ES2015).
  • square = ...
  • square.prototype.
  • (new square) (TypeError: square is not a constructor).
  • arguments (. 3).
  • Per spec, , "" (. 3).
  • ( ), ES2015 + const.
  • , this, this , , this ( , ).

5: ( )

let square = (n) => {
   return n * n;
};

:

let square = n => n * n;

4, , square = ...

+6

, T.J. , , . const square = n => n*n;. , , , " ES6/ES2015".

ES6- ( , , return) .

0

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


All Articles