Overview of ECMAScript Functions

What is a function?

Functions are a set of statements that can be executed anywhere at any time.

Functions are the core of ECMAScript.

Functions are declared in this way: the keyword function, function name, a group of parameters, and the code to be executed inside the parentheses.

The basic syntax of a function is like this:

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

For example:

function sayHi(sName, sMessage) {
  alert("Hello " + sName + sMessage);
}

How to call a function?

Functions can be called by their name followed by parentheses containing the parameters, if there are multiple parameters.

If you want to call the function in the above example, you can use the following code:

sayHi("David", "Nice to meet you!")

Calling the function sayHi() above will generate a warning window. You canTry this example yourself.

How does a function return a value?

The function sayHi() does not return a value, and it is not necessary to declare it specifically (like using void in Java).

Even if a function indeed has a value, it is not necessary to explicitly declare it. The function only needs to use the return operator followed by the value to be returned.

function sum(iNum1, iNum2) {
  return iNum1 + iNum2;
}

The following code assigns the value returned by the sum function to a variable:

var iResult = sum(1,1);
alert(iResult);	//Output "2"

Another important concept is that, like in Java, a function stops executing code immediately after executing a return statement. Therefore, the code after the return statement will not be executed.

For example, in the following code, the alert window will not be displayed:

function sum(iNum1, iNum2) {
  return iNum1 + iNum2;
  alert(iNum1 + iNum2);
}

A function can have multiple return statements, as shown below:

function diff(iNum1, iNum2) {
  if (iNum1 > iNum2) {
    return iNum1 - iNum2;
  }
    return iNum2 - iNum1;
  }
}

The function above is used to return the difference of two numbers. To do this, it is necessary to subtract the smaller number from the larger one, so an if statement is used to determine which return statement to execute.

If a function does not have a return value, you can call the return operator without any parameters to exit the function at any time.

For example:

function sayHi(sMessage) {
  if (sMessage == "bye") {
    return;
  }
  alert(sMessage);
}

In this code, if sMessage is equal to "bye", the warning box will never be displayed.

Note:If a function does not have an explicit return value, or calls a return statement without any parameters, then the value it actually returns is undefined.