Summary
To create a function in JavaScript, use the function
keyword.
Function without parameters:
function myFunction() {
// Insert code here
}
// Call function
myFunction();
Details
A function allows you to group one or more lines of code together and give the group of code a name. You can then reuse this group of code whenever you need to by writing the function name (with parentheses).
Writing a function
To write a function, first write the function keyword:
function
Then give the function a name. Function names in JavaScript use camelCase. This means that if the function name is made up of several words, the first word is lowercase and all subsequent words start with an uppercase letter. All function names end with parentheses as well.
function myFunction()
Next, add curly braces after the parentheses.
function myFunction() {
}
Lastly, add the code you want included in your function in between the curly braces.
function myFunction() {
console.log('Hello world');
}
To call your function, type the function name, including the parentheses.
function myFunction() {
console.log('Hello world');
}
myFunction();
As stated before, functions are useful because you can call the same function multiple times. If you need to update what the function does, you only need to update it in one place. This is better than copying and pasting your code, where you’d have to update the code everywhere you pasted it.
function myFunction() {
console.log('Hello world');
}
// Calling function multiple times
myFunction();
myFunction();
You can add more than one line of code inside of the curly braces.
function myFunction() {
console.log('Hello world');
console.log('Goodbye world');
}
myFunction();
Hoisting
This method of writing functions is called a function declaration. One interesting feature of function declarations is that you can call the function before it is defined, like this:
myFunction();
function myFunction() {
console.log('Hello world');
}
Demo
Exercises
Try the following statements in the console:
function myFunction() {
console.log('hello world');
}
myFunction()
The output should be ‘hello world’.
References
function declaration on MDN