function
Function declaration
function showMessage() { alert( 'Hello everyone!' ); } //Call function showMessage(); showMessage();
local variable
function showMessage() { let message = "Hello, I'm JavaScript!"; // local variable alert( message ); } showMessage(); // Hello, I'm JavaScript! alert( message ); // < -- error! A variable is a local variable of a function
External variable
let userName = 'John'; function showMessage() { let message = 'Hello, ' + userName; alert(message); } showMessage(); // Hello, John
Function has full access to external variables. Functions can also modify external variables.
let userName = 'John'; function showMessage() { userName = "Bob"; // (1) Change external variables let message = 'Hello, ' + userName; alert(message); } alert( userName ); // John before the function call showMessage(); alert( userName ); // Bob, the value has been modified by the function
parameter
function showMessage(from, text) { // Parameters: from and text alert(from + ': ' + text); } showMessage('Ann', 'Hello!'); // Ann: Hello! (*) showMessage('Ann', "What's up?"); // Ann: What's up? (**)
We have a variable from and pass it to the function. Please note: the function will modify from, but the change cannot be seen outside the function, because the function modifies the copied copy of the variable value:
function showMessage(from, text) { from = '*' + from + '*'; // Make "from" look more elegant alert( from + ': ' + text ); } let from = "Ann"; showMessage(from, "Hello"); // *Ann*: Hello // The value of "from" is the same, and the function modifies a local copy. alert( from ); // Ann
Default value
If no parameter is provided, its default value is undefined.
function showMessage(from, text = "no text given") { alert( from + ": " + text ); } showMessage("Ann"); // Ann: no text given
Now, if the text parameter is not passed, it will get the value "no text given".
Here "no text given" is a string, but it can be a more complex expression and will only be evaluated and allocated in the absence of parameters. Therefore, it is also possible:
function showMessage(from, text = anotherFunction()) { // Otherfunction() is executed only when no text is given // Its running result will become the value of text }
Return value
Function can return a value to the calling code as a result.
function sum(a, b) { return a + b; } let result = sum(1, 2); alert( result ); // 3
Multiple return s may appear in a function
function checkAge(age) { if (age >= 18) { return true; } else { return confirm('Got a permission from the parents?'); } } let age = prompt('How old are you?', 18); if ( checkAge(age) ) { alert( 'Access granted' ); } else { alert( 'Access denied' ); }
It is also possible to use only return but no return value. However, it will cause the function to exit immediately.
function showMovie(age) { if ( !checkAge(age) ) { return; } alert( "Showing you the movie" ); // (*) // ... }
be careful:
The return value of a null return or a function without a return is undefined
//If the function has no return value, it will return as undefined function doNothing() { /* No code */ } alert( doNothing() === undefined ); // true //Return with null value is equivalent to return undefined function doNothing() { return; } alert( doNothing() === undefined ); // true
**Note: * * do not add a new line between return and return value
//For the long expression of return, you may want to put it on a separate line, as follows: return (some + long + expression + or + whatever * f(a) + f(b)) // JS will add a semicolon after return by default. return; (some + long + expression + or + whatever * f(a) + f(b)) //It actually returns a null value. //Therefore, it can be actually written return ( some + long + expression + or + whatever * f(a) + f(b) )
Function naming
A function is an action. So their names are usually verbs. It should describe the function briefly and as accurately as possible. In this way, people who read the code can clearly know the function of this function.
- "get..." - returns a value,
- "calc..." - calculate something,
- "Create..." - create something,
- "Check..." - check something and return a boolean value, etc.
- "show..." - display some contents, etc.
Example:
showMessage(..) // display information getAge(..) // Return age (gets it somehow) calcSum(..) // Calculates the sum and returns the result createForm(..) // Create a table (usually return it) checkPermission(..) // Check permissions and return true/false
Function = = comment
Compare the two functions, both of which are prime numbers output to n.
function showPrimes(n) { nextPrime: for (let i = 2; i < n; i++) { for (let j = 2; j < i; j++) { if (i % j == 0) continue nextPrime; } alert( i ); // A prime number } }
Use the additional function isPrime(n) to check the prime:
function showPrimes(n) { for (let i = 2; i < n; i++) { if (!isPrime(i)) continue; alert(i); // A prime number } } function isPrime(n) { for (let i = 2; i < n; i++) { if ( n % i == 0) return false; } return true; }
Reference link:
https://zh.javascript.info/function-basics
Function expression
let sayHi = function() { alert( "Hello" ); };
You can also copy functions to other variables
function sayHi() { // (1) Create alert( "Hello" ); } let func = sayHi; // (2) Copy func(); // Hello / / 3) run the copied value (normal operation)! sayHi(); // Hello / / it can also run here (why not)
Callback function
Let's write a function with three parameters ask(question, yes, no): question Text on the question yes When the answer is“ Yes" Script to run when no When the answer is“ No" Script to run when
Example:
function ask(question, yes, no) { if (confirm(question)) yes() else no(); } function showOk() { alert( "You agreed." ); } function showCancel() { alert( "You canceled the execution." ); } // Usage: show and cancel are passed to the function as parameters ask("Do you agree?", showOk, showCancel);
that
function ask(question, yes, no) { if (confirm(question)) yes() else no(); } ask( "Do you agree?", function() { alert("You agreed."); }, function() { alert("You canceled the execution."); } );
Arrow function
let sum = (a, b) => a + b; /* This arrow function is a shorter version of the following function: let sum = function(a, b) { return a + b; }; */ alert( sum(1, 2) ); // 3
Take another example:
If there is only one parameter, the parentheses outside the parameter can be omitted.
let double = n => n * 2; // Almost equivalent to: let double = function (n) {return n * 2} alert( double(3) ); // 6
If there are no parameters, the parentheses will be empty, but keep the parentheses.
let sayHi = () => alert("Hello!"); sayHi();
Create a function dynamically
let age = prompt("What is your age?", 18); let welcome = (age < 18) ? () => alert('Hello') : () => alert("Greetings!"); welcome();
Multiline arrow function
let sum = (a, b) => { // Curly braces indicate the beginning of a multiline function let result = a + b; return result; // If we use curly braces, we need an explicit "return" }; alert( sum(1, 2) ); // 3