JavaScript Functions

Functions are a piece of code that are created to perform a particular functionality. They are written once and can be used anywhere and multiple times. Hence, there is no need to write the same code again and again. Through functions, we can divide the code into smaller functions.

Functions are defined by the keyword function, followed by a unique name, list of parameters (optional) followed by block of code in curly braces. Below is the syntax of JavaScript functions:

function function_name(parameter1, parameter2, parameter3,…) {
statement1;
statement2;
.
.
.
}

Below is an example of how to write a basic JavaScript function. This function has no parameters.

       
function hello() {
alert("Hellooozzzz");
}

But writing this function is of no use until we call it which is known as Invoking of a Function. Below is the complete code to create and invoke a function.

In the above example, we have created a function with the name hello which has zero parameters. In our HTML page, we have a button Click Me!. When we click this button, our hello function is invoked and you will see an alert box with the message Hellooozzzz written on it.

When a function is invoked, the statements within it are executed. We can declare various types of variables in it, use conditional and loop statements as well in that.

Passing Parameters

There are two terms used in functions: Arguments and Parameters. Parameters are the names that are listed in function definition. Arguments are the real values that are passed to the function when they are called.

Let’s see an example where we pass parameters to a function. You can pass one or more parameters to the function separated by comma(,). But the number of parameters should match in function definition and when function is invoked.

Below is an example:

In the above example, we have created a function calculateEvenOrOdd which takes one parameter. We have placed a textbox and a button on our HTML page which has a label “Even OR Odd”. We enter a number in the textbox and click the button to know whether the the number is even or odd. On click of the button, the number is passed to the function as an argument, the result is calculated and displayed in an alert box through function.

 

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started