Create Function in JavaScript using Function Declaration

There are many ways to create functions in JavaScript. In this video, we will look at the most common form, which is using the function declaration.


function add(a, b) {
let c = a + b
return c
console.log(add(10, 20))

Full Transcript

0:00 Hello there. Today you will learn to create functions in JavaScript using function declaration. A function declaration starts with the function keyword. This is a reserved keyword in JavaScript, which means as developer, we cannot create a variable whose name is function. A function declaration is followed by the name of the function. It is then, followed by the list of parameters passed to the function. These are also known as input to the function. Then, a function body is enclosed within the curly braces. Inside the function body, there could be one or more statements and finally a function returns a value back to the caller. This is the most common form of creating a function in JavaScript. Now let's look at an example to understand this better. First we use the function keyword. Then we give a name of add to our function. Next we create two parameters, a and b as the inputs to our function.

0:57 Then we have curly braces and then function body. Inside that, we create a new variable c, which adds two numbers. And finally, the function returns the value of c. Now, once we have created a function, how do we call it? It is as simple as writing the function name and putting the arguments inside the parenthesis. So in the case of our add function, that translates to add followed by 10 and 20 as arguments. One thing to note here is that when declaring a function, the inputs are known as parameters. While when providing the input during the function called they're known as arguments. Let's create a function and run it. We create a function with function keyword and give it a name of add. It takes two parameters, a and b. Within that we create a new variable c that adds two numbers. Then we return c back to the caller. Then we are going to call the add function with 10 and 20 as argument and print it on console. As we run, we can see the value of 30 and that's it. If you like the video, consider subscribing us to receive more engaging content about JavaScript every week. See you next time.