JavaScript is language of Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
In JavaScript, functions are the 1st class citizens of language. These are the bread and butter of JavaScript. Go in deep now:
Functions in-depth
Function keyword, followed by a name, followed by parentheses (). You can get function definition or invoke the function, ex:
- function myFunction(a, b) {
- return a * b;
- }
The () invokes the function,
Properties of function
Let us dive into some properties of function, ex-
- Call v/s Apply:
If you want to assign value of a function we use straight forward way, i.e.,
- var val = myFunction (2,3);
There are two other way to achieve it using call or apply property,
- var val = 0;
- myFunction.apply(val,[2,3]);
- myFunction.call(val,2,3);
Call requires the parameters be listed explicitly | Apply lets you invoke the function with arguments as an array. |
- The "constructor" property
Every object has a built-in property named constructor. It refers to the function which created it. Let us understand in detail:
- function myFunction(a, b) {
- return a * b;
- }
- var m = new myFunction();
- console.log( m.constructor == myFunction);
- console.log(m.__proto__.constructor == myFunction);
- Defining Your Own Function Properties
Many times we need a unique number say GUID or identifies which increments with each call made to function. In such scenario, it is recommended to attach a property with a function. It is acting like a static property to keep track of last value returned.
- function myFunction(a, b) {
- ++myFunction.p1;
- return a * b;
- }
- myFunction.p1 = 1;
- myFunction();
- myFunction.p1 ;
- Length property
In a function, we pass arguments to process input and sometime we don’t pass correct number of arguments. Therefore, it is good practice to check required number of arguments needed for a particular function.
- function myFunction(a, b) {
- return a * b;
- }
- myFunction(2);
- Its time to fix above function by using property length
- function myFunction(a, b) {
- var argsRequired = arguments.length;
- var argsActual = arguments.callee.length;
- if (argsRequired!=argsActual) {
- throw new Error("Wrong # of args passed");
- }
- return a * b;
- }
Summary
There are other useful properties also which you can look into detail. I hope you like this series. Please share your comments / feedback.
Read more articles on JavaScript: