Learning JavaScript – function explained

By | March 26, 2016

In my previous  post I have discussed about the data types in Javascript in which I have discussed about the Javascript function in brief. In this article I want to extend the discussion about the functions with code examples.

Become an Expert in Programming and Web Development.View all courses!

Passing Parameter to functions in Javascript

Suppose if I define a function with certain number of parameters and if I don’t provide value for all the parameter in that case the the last parameters for which the value has not been passed will remain as ‘undefined’ as shown in the below code.

Javascript is well aware of the fact that while passing the parameters to the functions it is not necessary that it will receive all of them and while coding we should be aware of this fact.

Overriding a javascript function

Does javascript really supports overriding. Not really !!. Suppose if I have two functions with same name, the function which is defined later in the code will be called as shown in the below code snippet

In the above code snippet the function with single parameter will be always called. The first function just vanishes.

arguments object

As discussed in the first part of this article, when calling a javascript function we can pass any number of parameters. But we have an argument object present only in the scope of the functions by the help of which we can get the count of arguments passed as well as the arguments itself as shown in the code below

While using argument object the declared parameter really does not matter as we can simple access the arguments using argument object as shown below.

argument object is just the array, means that all the functions of array object are applicable to argument object.

Returning a value from function

Javascript functions explicitly does not have a return type unlike C#. They just return values. If the function is not returning anything, still the function can be assigned to variable but the type of this variable will be undefined.

Even if we specify only return as statement in that case also it will be undefined. But if we return some value in that case the type will be returned value’s type

Function as Objects

Functions just behave as any other object in javascript which will be clear in the below code snippet. Using the function names length property we get the number of parameters of the function, name of the function and the body of the function.

In this article I have discussed about the functions in javascript.