Defining Functions
In JavaScript, we have already encountered a few functions. For example: console.log()
for logging, push()
for adding an element to the end of an array, pop()
for removing an element from the end of an array. These functions were created for us. We just used them. Now we will look at how to create such a function.
We create (define) a function in JavaScript using the function
keyword, followed by the function name, parentheses, and a block of code.
The function block already contains the commands we want the function to perform. For example:
function myFunction() {
console.log("This is my function");
}
This creates a function that prints This is my function
. If we ran this code, nothing would be printed. That's because we just defined the function but did not call (execute) it. How to call functions will be covered in the next exercise.
Instructions
Create a function named firstFunction
that in its code block will print: "This is my first function!"
.
Start programming for free
2/7