In this tutorial, we are going to learn about functions in JavaScript. Functions are one of the fundamental building blocks in JavaScript, allowing us to write reusable code.
By the end of this tutorial, you will be able to:
- Understand what functions are and why they are useful.
- Declare and call functions.
- Understand the concept of function parameters and arguments.
- Write your own custom functions in JavaScript.
Basic knowledge of JavaScript syntax and HTML would be beneficial.
Functions are reusable blocks of code that perform a specific task. They are only executed when 'called' or 'invoked'.
You can declare a function using the function
keyword, followed by a name you give the function, and then a pair of parentheses ()
. The code to be executed is placed within curly brackets {}
.
function myFunction(){
// code to be executed
}
To execute the function, you 'call' it by using its name followed by parentheses.
myFunction(); // This will execute the code in myFunction
Functions can also take inputs, known as parameters. When you call the function, you provide the values (known as arguments) for these parameters.
function myFunction(a, b){ // 'a' and 'b' are parameters
// code to be executed
}
myFunction(5, 3); // 5 and 3 are the arguments
var
, let
, or const
.Let's look at some examples:
Here, we declare a function named greet
that logs 'Hello, world!' when called.
// Declaring the function
function greet(){
console.log('Hello, world!');
}
// Calling the function
greet(); // Outputs: 'Hello, world!'
This function takes two parameters and logs their sum.
// Declaring the function
function addNumbers(a, b){
console.log(a + b);
}
// Calling the function
addNumbers(5, 3); // Outputs: 8
In this tutorial, we learned about functions in JavaScript. We now understand how to declare and call functions, use function parameters and arguments, and best practices when using functions.
Consider learning about different types of functions in JavaScript such as arrow functions and self-invoking functions.
Try these exercises to practice what you've learned:
1.
function multiplyNumbers(a, b){
console.log(a * b);
}
multiplyNumbers(4, 5); // Outputs: 20
2.
function greetPerson(name){
console.log('Hello, ' + name + '!');
}
greetPerson('John'); // Outputs: 'Hello, John!'
Keep practicing and exploring more about JavaScript functions. Happy coding!