JavaScript basic learning series twenty-nine: functions

Functions are a core component of any language because they can encapsulate statements and be executed anywhere and at any time.
Functions in ECMAScript are declared using the function keyword, followed by a set of parameters, and then the function body.

The following is the basic syntax of the function:

function functionName(arg0, arg1,...,argN) {
    
    
  statements
}

Below is an example:

function sayHi(name, message) {
    
    
  console.log("Hello " + name + ", " + message);
}

A function can be called by its name, and the parameters to be passed to the function are placed in parentheses (if there are multiple parameters, separate them with commas). The following is an example of calling the function sayHi():

sayHi("Nicholas", "how are you today?");

The output of calling this function is "Hello Nicholas, how are you today?". The parameters name and message are concatenated together as strings inside the function, and are finally output to the console through console.log.
Functions in ECMAScript do not need to specify whether they return a value. Any function can use the return statement at any time to return the value of the function, followed by the value to be returned. for example:

   function sum(num1, num2) {
    
    
      return num1 + num2;
}

The function sum() adds two values ​​and returns the result. Note that there is no special declaration other than the return statement that the function returns a value. Then you can call it like this:

   const result = sum(5, 10);

The diff() function is used to calculate the difference between two values. If the first value is less than the second, subtract the first from the second; otherwise, subtract the second from the first. Each branch in the code has its own return statement that returns the correct difference.
The return statement can also have no return value. At this time, the function will immediately stop execution and return undefined. This usage is most commonly used to terminate function execution early, not to return a value. For example, in the following example, console.log will not be executed:

function sayHi(name, message) {
    
    
return;
console.log("Hello " + name + ", " + message); // 不会执行 }

Strict mode also has some restrictions on functions:

  • Functions cannot have eval or arguments as names;
  • Function parameters cannot be called eval or arguments;
  • Two named parameters cannot have the same name. If the above rules are violated, a syntax error will result and the code will not execute.

Guess you like

Origin blog.csdn.net/wanmeijuhao/article/details/135465042