Home > Article > Web Front-end > javascript return function?
Return function in JavaScript
In JavaScript, a function is a set of predefined codes that can be reused. When you need to perform a specific task, you call a function that performs the required operations based on your needs. Functions can receive parameters and return a value that can be used at the call site.
The return value (Return Value) refers to the value returned to the caller after the function execution is completed. In JavaScript, the return value is defined by the return statement, which ends the function and returns a value during its execution.
Grammar
The syntax of the return statement is very simple. It looks like:
return value;
where value is the value you want to return, which can be a number, a string, a Boolean value, Array or object.
Example 1:
function add(a, b) { return a + b; } var result = add(4, 6); //result的值是10
In this example, we define a function named add. The function receives two parameters a and b, adds them and returns. Then we call this function and save the return value in the variable result.
Example 2:
function compareNumbers(a, b) { if (a > b) { return true; } else { return false; } } var result = compareNumbers(10, 5); //result的值是true
In this example, we define a function named compareNumbers to compare the size of two numbers. The function receives two parameters a and b. If a is greater than b, it returns true, otherwise it returns false. Then we call this function and save the return value in the variable result.
In JavaScript, the return value type of a function can be any data type. Therefore, you can assign the return value of a function to a variable of any type. If the function does not return a value, it returns undefined.
Example 3:
function sayHello(name) { console.log('Hello ' + name); return; } var result = sayHello('John'); //result的值是undefined
In this example, we define a function named sayHello, which receives a parameter name, and then outputs "Hello" and name on the console. Then we call this function and save the return value in the variable result. Since the function has no return value, the return value is undefined.
Summary
Function in JavaScript is a tool that can perform a specific task and return a value. The return value is defined using the return statement, and the syntax is very simple. During function execution, when the JS interpreter encounters a return statement, it immediately stops execution and returns the specified value. You can assign the return value of a function to a variable of any type and do whatever you want with it.
The above is the detailed content of javascript return function?. For more information, please follow other related articles on the PHP Chinese website!