JavaScript How To Call A Function
Learn how to call a function in JavaScript.
This is a two step process:
- Declare a function.
- Call it.
There are two ways to declare a function.
- Using Function Declaration
- Using Function Expression
Declare A Function Using Function Declaration
Add the function keyword in front of the function name when declaring a function using Function Declaration.
These type of functions are hoisted and become global.
That means the function will be pushed all the way up its scope regardless of where its declared in the scope.
And it will be available anywhere in that scope.
For that reason, you can call or initialize a function before declaring it.
// Call a function
sayHello(); // it will work even if its called before the function declaration
// Declare A Function
function sayHello() {
console.log("Hello");
}
Declare A Function Using Function Expression
In Function Expression, you define an anonymous function and assign it to a variable.
When you use Function Expression to create a function, you must declare it first before calling it.
Because these types of functions are not hoisted.
// Call A Function Before Declaration
sayHello(); // Error
// Declare A Function
const sayHello = function () {
console.log("Hello");
}
// Call A Function After Declaration
sayHello(); // "Hello"
Alternatively, you can use the arrow function.
// Call A Function Before Declaration
sayHello(); // Error
// Declare An Arrow Function
const sayHello = () => {
console.log("Hello");
}
// Call A Function After Declaration
sayHello(); // "Hello"