Functions in JavaScript

Introduction

A function is a sequence of reusable code that can be called anywhere in a program. This eliminates the need to repeat the same code.

Functions in JavaScript

Functions are a central working unit of JavaScript. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax

<script type="text/javascript">
	<!--
	function functionname(parameter-list)
	{
		Statements
	}
//-->
</script>

Function with no parameter

<script type="text/javascript">
      function abhijeet() {
        alert("hello guyzz");
      }   
</script>

Calling a Function

<script type="text/javascript">
      function abhijeet() {
        alert("hello guyzz");
      }
      abhijeet();
</script>

Output

Function with Parameters

<script type="text/javascript">
	<!--
	function abhijeet(name, age)
	{
		alert(name + " is " + age + " years old.");
}
//-->
</script>

Calling a Function

<script type="text/javascript">
      function abhijeet(name, age) {
        alert(name + " is " + age + " years old.");
      }
      abhijeet("abhi", 22);
</script>

Output

No syntax-level polymorphism

In some languages, a programmer may write two functions with the same name but a different parameter list, and the interpreter/compiler would choose the right one as in the following.

function abhi(a) {
	…
}
function abhi(a, b) {
	…
}

abhi(a) // first function is called
abhi(a, b) // second function is called

That is called function polymorphism. In JavaScript, there’s no such thing.

There can be only one function named abhi, that is called for any given argument.

So we can say that in JavaScript, a function may be called with any number of arguments, no matter how many of them are listed.

Example

function abhi(a, b) {
	alert(“a =”+a +”, b =”+b)
}

abhi(a) // a=1 b=undefined
abhi(1, 2) // a=1 b=2
abhi(1, 2, 3) // a=1 b=2 , extra argument is not listed

Arguments that are not provided become undefined.

Next article: Event Handlers in JavaScript


Similar Articles