English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Basic Tutorial

JavaScript Objects

JavaScript Functions

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

JavaScript Function Definition

Functions allow you to define a block of code, name it, and then execute it repeatedly as needed.

Functions can be defined using the function keyword or executed using the () operator.

Function Declaration

In the previous part of this tutorial, you learned to use the following syntaxDeclarationFunction:

function nameOfFunction(parameters) {
  // The statement to be executed
}

Declared functions do not execute immediately. Declared functions are just naming the function and specifying the operations to be performed when the function is called.

function greet() {}}
   document.write("Hello, World!");
}
Test and see‹/›

In the above example, we have declared (defined) a function named greet that outputs the message 'Hello, World!'. This function can be called using the () operator, for example greet().

Function Expression

JavaScript allows us to assign functions to variables and then use the variable as a function. It is calledFunction Expression.

//Function expressions can be stored in variables
var sum = function(a, b) {
return a + b;
);
// This variable can be used as a function
var x = sum(100, 8);
Test and see‹/›

The function above is actually aAnonymous Function(Function without a name).

Functions stored in variables do not need a function name. Always use the variable name to call them.

The above function ends with a semicolon because it is part of an executable statement.

Function Hoisting

In the previous part of this tutorial, you learnedJavaScript Hoisting.

Hoisting is the default behavior of JavaScript that moves declarations to the top of the current scope.

Therefore, you can call the JavaScript function before declaring it:

// Call the function before declaration
greet();
function greet() {}}
  document.getElementById("output").innerHTML = "Hello World";
}
Test and see‹/›

Functions defined by expressions are not hoisted.

Self-executing anonymous function

It can make the function expression "self-executing".

Self-execution is a JavaScript function that runs immediately after definition.

Automatically invoke (start) the self-invoking expression without calling it. Also known as IIFE (Immediately Invoked Function Expression).

If a function expression is followed by (), the function expression will execute automatically.

(function () {
  // The statement to be executed
})();
Test and see‹/›

Assigning an IIFE to a variable will store the return value of the function, not the function definition itself:

let result = (function () {
let name = "Seagull"; 
return name; 
})(); 
//Create output immediately
result;   // "Seagull"
Test and see‹/›

The following example demonstrates how to pass parameters to an IIFE (Immediately Invoked Function Expression):

(function (x, y) {
  document.getElementById("output").innerHTML = x + y;
})();5, 10);
Test and see‹/›

Callback function

A callback function is a function passed as an argument to another function and then called in the outer function to complete some routine or operation.

function greet(name) {
  alert("Hello " + name);
}
function processInput(callback) {
  let name = prompt("Please enter your name:");
  callback(name);
}
// Passing the greet function into the processInput function as an argument
processInput(greet);
Test and see‹/›

The above example is a synchronous callback because it will execute immediately.

However, callbacks are usually used to continue executing code after asynchronous operations are completed.

Recursion

Recursion is a technique of iterative operation, which is to make the function call itself repeatedly until the result is obtained.

The following example demonstrates how to obtain the factorial of a number using recursion:

var factorial = function(number) {
  if (number <= 0) {
 return 1;
  } else {
 return (number * factorial(number - 1));
  }
);
document.getElementById("output").innerHTML = factorial(5);
Test and see‹/›

Arrow Functions

So far, we have introduced how to define a function using the function keyword.

However, from ECMAScript 6Starting from now, there is a new, more concise way to define a function calledArrow FunctionsExpressionsFunction.

As is well known,Arrow FunctionsIt is represented by an equal sign followed by a greater than sign: =>.

//Function Expression
var sum = function(x, y) {
   return x + y;
}
// Arrow Functions
const sum = (x, y) => x + y;
Test and see‹/›

Arrow functions do not have their own this. They are not suitable for definingObject Methods.

Arrow functions are not hoisted. They must be defined first,And then useThey.

Using const is safer than using var because the function expression is always a constant.

The return keyword and curly braces can be omitted only when the function is a single statement. Therefore, it may be a good habit to always keep them.

The return keyword and curly braces can be omitted only when the function is a single statement. Therefore, it is a good habit to always use them.

const sum = (x, y) => { return x + y };
Test and see‹/›