Functions In Javascript

The literal meaning of function is an activity intended for a person or a thing. In programming, function is work or operation that is performed to get the desired output.

In javascript, a function is created using the ‘function’ keyword followed by the name of the function. The name of the function should be meaningful so that the person reading your code can easily understand the purpose of the function.

There are 3 steps of creating and executing a function :

  1. Declaring a function
  2. Defining a function
  3. Calling a function

For Example: Let’s create a sum function that carries out the sum of two numbers.

Step 1: Declaring a function: Giving a name to the function and memory is allocated for the function

Figure 1

Step 2: Defining a Function: Writing the code inside the function that will produce the desired output.

Step 3: Final step is to invoke/call the function so that the statements written inside the function are executed. You have to call the function to get the desired output. If you have defined the function and not called it, no output will be produced.

Figure 2

Output :

Figure 3

It is not necessary to call the function just after you have defined it. You can call it anywhere inside your javascript code. We will talk more about how functions are stored in memory and their scope in the Hoisting concept.

Leave a Reply

Your email address will not be published.