- A function with an empty
return
or without it returns undefined
.
- JavaScript assumes a semicolon after return so never add a newline between return and the value.
- There is another syntax for creating a function that is called a
// This approach of defining a function is called "**Function Expression".**
let sayHi = function() {
console.log("Hello");
};
console.log(sayHi); // Shows the function code.
sayHi(); // Hello
- Function Expression have a semicolon at the end, but Function Declaration does not.
- Function Expression is used inside a statement and it’s not a code block.
- So the semicolon is not related to the Function Expression itself in any way, it just terminates the statement.
- A Function Expression is created when the execution reaches it and is usable from then on.
- Once the execution flow passes to the right side of the assignment, the function is created and can be used.
- A Function Declaration is usable in the whole script/code block.
- When JavaScript prepares to run the script or a code block, it first looks for Function Declarations in it and creates the functions.
- After all of the Function Declarations are processed, the execution goes on.
- As a result, a function declared as a Function Declaration can be called earlier than it is defined.
- When a Function Declaration is made within a code block, it is visible everywhere inside that block but not outside of it.
Local & Global Variables
- A variable declared inside a function is only visible inside that function.
- A function can access an outer variables.
- The outer variable is only used if there’s no local one.
Parameters
- If a parameter is not provided, then its value becomes
undefined
.
- If we want to use a “default” text in this case, then we can specify it after for each argument.
function showMessage1(from, text) {
// If text is falsy then text gets the "default" value.
text = text || 'no text given';
}
function showMessage2(from, text = "no text given") {
alert(from + ": " + text);
}
function showMessage3(from, text = anotherFunction()) {
// anotherFunction() only executed if no text given its result becomes the value of text.
}
- Arrow functions do not have
this
.
- If
this
is accessed, it is taken from the outside.
- Not having
this
naturally means another limitation: arrow functions can’t be used as constructors.
- They can’t be called with
new
.
let sayHi = () => alert("Hello!");
let sum = (a, b) => a + b;
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, use return to get results
};
let double = n => n * 2;
- There’s a subtle difference between an arrow function
=>
and a regular function called with .bind(this)
:
- While
.bind(this)
creates a “bound version” of the function, the arrow =>
doesn’t create any binding.
- Arrow functions also have no
arguments
variable.
Rest Parameters