🌞Function declaration
-
Create a function using a function declaration.
-
The function keyword appears first, followed by the function name, followed by a list of parameters between parentheses (comma-separated, empty in the above example), and finally the code between curly brackets (i.e.'function body').
function showMessage() { alert( 'Hello everyone!' ); }
- Code that calls showMessage() to execute the function.
🌞local variable
- Variables declared in a function are visible only inside the function.
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
-
Functions have full access to external variables.Functions can also modify external variables.
-
External variables are used only when there are no local variables.
If a variable with the same name is declared inside a function, the function will obscure the external variable.
-
Variables declared outside any function are called global variables.
🌞parameter
We can use parameters (also known as "function parameters") to pass any data to the function.
👀[We have a variable from and pass it to a function.Note that the function modifies from, but no change is visible outside the function because it modifies a copy of the copied 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 "from" value is the same, and the function modifies a local copy. alert( from ); // Ann
🌞Default value
If no parameters are provided, the default value is undefined.
For example, the example showMessage(from,text) above can be called with only one parameter: showMessage("Ann"), output *Ann*:undefined
💧Backup default parameters
Sometimes it makes sense to set the default value of a parameter when the function is executed (later than expected) rather than when the function is declared.
-
To see if the parameter is omitted, we can compare it to undefined:
function showMessage(text) { if (text === undefined) { text = 'empty message'; } alert(text); } showMessage(); // empty message
-
Or we can use the || operator:
// Assign'empty'if the'text' parameter is omitted or passed in an empty string function showMessage(text) { text = text || 'empty'; ... }
-
Does the modern JavaScript engine support null merge operators??It is more advantageous when other false values may be encountered, such as 0 being considered normal and not merged:
// "unknown" is displayed if no "count" parameter is passed in function showCount(count) { alert(count ?? "unknown"); } showCount(0); // 0 showCount(null); // unknown showCount(); // unknown
🌞Return value
A function can return a value to the calling code as a result.
Instruction return can be anywhere in the function.When execution arrives, the function stops and the value is returned to the calling code.
It is also possible to use only return but no return value.This will cause the function to exit immediately.
⚠Null returns or functions without returns return undefined
If the function has no return value, it will return undefined as if:
function doNothing() { /* No code */ } alert( doNothing() === undefined ); // true
Null values return and return undefined are equivalent:
function doNothing() { return; } alert( doNothing() === undefined ); // true
🌞Function Naming
A function is an action.So their names are usually verbs.It should be brief and describe the function as accurately as possible.
- "get..." - returns a value,
- "calc..." - Calculate something,
- "Create..." - create something,
- "check..." - check something and return a boolean value, etc.
📖Practice
📘Use'?'Or'|'overrides the function
If the parameter age is greater than 18, the following function returns true.
Otherwise it will ask for confirmation and return the confirmation result:
function checkAge(age) { if (age > 18) { return true; } else { return confirm('Do you have your parents permission to access this page?'); } }
Rewrite this function to ensure the same effect, without using if, and with only one line of code.
Write two variants of checkAge:
-
Use question mark operator?
function checkAge(age) { return (age > 18) ? true : confirm('Did parents allow you?'); }
-
Use or Operator||
function checkAge(age){ return (age>18) || confirm('Did parents allow you?'); }
📘Function min(a,b)
Write a function min(a,b) that returns the smaller number in numbers a and B.
function min(a,b){ if(a>b){ return b }else{ return a } }
In the case of a == b, it doesn't matter what you return.
📘Function pow(x,n)
Write a function pow(x,n) that returns the n-th power of X.In other words, multiply X by itself n times to return the final result.
function pow(x, n) { let result = x; for (let i = 1; i < n; i++) { result *= x; } return result; } let x = prompt("x?", ''); let n = prompt("n?", ''); if (n < 1) { alert(`Power ${n} is not supported, use a positive integer`); } else { alert( pow(x, n) ); }