Creating Functions in JavaScript
Learn how to declare a function in JavaScript.
We'll cover the following...
There are many ways to create functions in JavaScript. Let’s see what they are.
The function
keyword
The whole function consists of the following parts.
The basic syntax to create a function in JavaScript is using the function
keyword. Let’s look at an example below.
Press + to interact
function example() {console.log('Print a message');}example();
We’ve created a simple function using the function
keyword in the code snippet above. It logs Print a message
to the console.
Creating function within a function
Since functions are first-class citizens in JavaScript, we can also do things like creating a function that itself creates functions. Let’s look at an example below.
Press + to interact
function withInnerFunction(outer) {return function ourInnerFunction(inner) {console.log(`Outer function received ${outer}, inner got ${inner}`);};}const returnedFunction = withInnerFunction('a');// some time later in our program, we actually need to call returnedFunctionreturnedFunction('b');
In the code ...