- Functions that are part of objects are called methods.
- A function declaration looks like this:
function name(parameters, delimited, by, comma) {
/* code */
}
- Custom functions are functions defined in your code, not inside the browser. A custom name with parentheses straight after it is a custom function. For example:
function myFunction() {
alert('hello');
}
myFunction();
// calls the function once
- A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time term).
- An argument is the value that is passed to the function when it is called (it’s a call time term).
- Some functions require parameters to be specified when you are invoking them. For example:
const myText = 'I am a string';
const newString = myText.replace('string', 'sausage');
- Sometimes parameters are optional — you don't have to specify them.
const madeAString = myArray.join(' ');
const madeAString = myArray.join();
- Default Parameters:
function hello(name = 'Chris') {
console.log(`Hello ${name}!`);
}
hello('Ari'); // Hello Ari!
hello(); // Hello Chris!
-
Anonymous Functions
- The function parameter is often passed as an anonymous function. For example:
function logKey(event) {
console.log(`You pressed "${event.key}".`);
}
textBox.addEventListener('keydown', logKey);
// is the same as
textBox.addEventListener('keydown', function(event) {
console.log(`You pressed "${event.key}".`);
});
// notice the syntax carefully
-
Function scope and conflicts
- When you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions.
- JavaScript has the following kinds of scopes:
- Global scope: The default scope for all code running in script mode.
- Module scope: The scope for code running in module mode.
- Function scope: The scope created with a function.
- In addition, variables declared with
let
or const
can belong to an additional scope:
- Block scope: The scope created with a pair of curly braces (a block).
-
Function return values
-
Naming a function