JavaScript Functions

Function is an important part of any programming language, like any other programming language JavaScript also allows developer to write a function. Function is simply a small part of the program itself. Whenever we have a very lenthy code then we can divide that code into smaller parts so it will be easy to read and easy to understand the code. We can also write the function to repeat the code so it will reduce the line of code and easy to maintain.

Function accepts argument(s) and return value as well if we want to. Function can also access the variables of parent code block and function has it's own scope.

There are two types of functions in JavaScript, named function and anonymous function.

Named function

In named function, function start with function keyword and then name of the function, we can pass the parameters in parantheces. For example

Example
function Addition(value1, value2)
{
	var sum = value1 + value2;
	return sum;
}
console.log("The sum of value1 and value2 is :" + Addition(3, 4));

// It will output "The sum of value1 and value2 is :7"

In above function we have passed two parameters and returns sum of those two parameters.

Anonymous function

In anonymous function, first we will write the name of the function and then write the function keyword followed by = sign and then in parantheces we will pass the parameters. For example

Example
var Addition = function(value1, value2)
{
	var sum = value1 + value2;
	return sum;
}
console.log("The sume of value1 and value2 is :" + Addition(3, 4)); 

 

← Previous

Next →