Now a days I am talking more about JavaScript to C# developers. Surprisingly I find that they have always if not no then little knowledge about JavaScript functions. In this post I am trying to explain it in simplest words possible.

Like C# you have two kinds of JavaScript functions.

  1. Named Function
  2. Anonymous Function

You can create Anonymous function as following,


var display_message = function (age) {
 alert("you are " + age + "year old ");

}
 display_message(19);

Named function can be created as following


function display_message(age) {
 alert("you are " + age + "year old ");
 }
 display_message(19);

JavaScript function can be parameterized or without parameter. A function with parameter can be created as following. In below function we are passing two primitive type values as parameter.

function findgreater(number1, number2) {

if (number1 > number2)
 return number1;
 else
 return number2;
 }
 });

 

image

On execution of following code you will get undefined in alert.


function findgreater(number1, number2) {

var r = number1 + number2;
 }

alert(findgreater(9, 14));

You can use function in different ways,

  • You can store it in a variable
  • You can pass it as parameter of other function
  • You can use it in an expression

In JavaScript function both Pass by Value and Pass by Reference is allowed.

image

An example of Pass by Value is given below. You see that even though we are modifying value of greetingmessage variable in function it is not updating the original value. So in alert we will get “Hey DJ”.


var greetingmessage = "Hey DJ";

function showmessage(greetingmessage) {

greetingmessage = "I am changing value";
 }

showmessage(greetingmessage);
 alert(greetingmessage);

In below example we are passing an array as input parameter to function. You can see that in function on modifying the array element value original value is being modified. In alert you will get dhananjay as message. Here array is being passed as reference since in JavaScript array is an object.


var arrayofname = ["dj"];

function showmessage(arrayofname) {

arrayofname[0] = "dhananjay";
 }

showmessage(arrayofname);
 alert(arrayofname[0]);

This is the way JavaScript function works. I hope you find this post useful. Thanks for reading.

Advertisements

2 thoughts on “Functions in JavaScript : Beginner’s note

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s