Ringkasan Fungsi ECMAScript

Apa itu fungsi?

Fungsi adalah suatu kumpulan pernyataan yang dapat dijalankan kapan saja dan dimana saja.

Fungsi adalah inti ECMAScript.

Fungsi diumumkan dengan cara seperti ini: kata kunci function, nama fungsi, grup parameter, dan kode yang akan dieksekusi dalam kurung siku.

Basis sintaks fungsi seperti ini:

fungsi functionName(arg0, arg1, ... argN) {
  pernyataan
}

For example:

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

Bagaimana cara memanggil fungsi?

Fungsi dapat dipanggil melalui nama fungsi ditambahkan kurung siku parameter, jika ada beberapa parameter.

Jika Anda ingin memanggil fungsi di contoh di atas, Anda dapat menggunakan kode berikut:

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

Pemanggilan fungsi sayHi() di atas akan menghasilkan jendela peringatan. Anda dapatTry this example yourself.

How does a function return a value?

The function sayHi() does not return a value, but it does not need to be declared specifically (like using void in Java).

Even if a function does indeed have a value, it does not need to be explicitly declared. 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, you must subtract the smaller number from the larger number, so you use an if statement to decide which return statement to execute.

If a function does not have a return value, you can call a 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 equals "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 actual value it returns is undefined.