You are on page 1of 12

Javascript

Function
❖ What is Function/Definition
❖ Function Syntax
❖ Function Declaration
❖ Function Expression
❖ Anonymous function
❖ Variables
❖ Return statement
What is Function

A javascript function is a block of code designed to perform a particular task. A function is a


block of code that will be executed only by an occurrence of an event at the time of function is
called.A function can called from anywhere within the HTML page.

A function is group of reusable code which can be called anywhere in your program. These
eliminate the need of writing same code again and again.
Function Syntax

function functionName (parameter1,parameter2,parameter3)

……………………..

Function statements;

…………………...

}
Function Declaration
Example:-

function addNumbers(firstNumber, secondNumber)

var sum =firstNumber+secondNumber;

Return sum;

var result =addNumbers(10,20);

document.write(result);
Function Expression

var Area=function(width,height)

return width*height;

document.write(Area(3,4));
Anonymous function definition

var anon=function()

alert(“I am anonymous”);

anon();

Use of anonymous function is as argument to another function.

Another use is as a closure.


Argument to the other function

<script>

var anon =function()

alert("I am anonymous");

anon();

setTimeout(function()

alert("hello");

},10000);
Return statement

The return statement is used to specify the value that is returned from the function.

So the function that are going to return value must use the return statement.

A javascript function can have optional return statement.


Example of return statement:-

<head>

<script>

function MyReturn()

Return (“Hello i am a Return keyword”);

</script>

</head>

<body>

<script>

document .write(MyReturn());
variables

● GLOBAL variable
● LOCAL variable

● LOCAL JavaScript Variables

A variable declared within a JavaScript function becomes LOCAL and can only accessed within
that function. You can have local variable with same name with different functions.Local
variable are deleted as soon as the function is completed.
GLOBAL variable:-

Variable declared outside a function become GLOBAL, all scripts and function on web page can
access it.Global variables are deleted when you close the page.

You might also like