Declaration of functions

JavaScript has three ways of declaring functions.

(1) function command

The block of code declared by the function command is a function. The function command is followed by the function name, which is followed by a pair of parentheses containing the parameters of the function passed in. The body of the function is enclosed in braces.

function print(s) {
  console.log(s);
}
Copy the code

(2) Function expression

In addition to declaring functions with the function command, you can also write variable assignments.

var print = function(s) {
  console.log(s);
};
Copy the code

(3) Function constructor

The third way to declare a Function is the Function constructor.

var add = new Function(
  'x'.'y'.'return x + y'
);

/ / is equivalent to
function add(x, y) {
  return x + y;
}
Copy the code

You can pass as many arguments to the Function constructor as you want. Only the last argument is considered the Function body. If there is only one argument, that argument is the Function body.

var foo = new Function(
  'return "hello world"; '
);

/ / is equivalent to
function foo() {
  return 'hello world';
}
Copy the code

The Function constructor can omit the new command and return exactly the same result.