Just JavaScript - The Function Object
Just JavaScript - The Function Object
Written by Ian Elliot   
Monday, 21 May 2018
Article Index
Just JavaScript - The Function Object
Other Ways Of Creating Function Objects
Constructor v Expression v Statement

Return and Parameters

You might well be thinking if the invocation operator evaluates the function it should return a result and this is the case. You can use the statement:

return result;

to specify what the function evaluates to. 

If you don't specify a return result the function body returns undefined. 

For example:

var myFunction= new Function(
                    "var ans=1+2;return ans;");

has the function body:

var ans=1+2;
return ans;

Now if you try:

alert(myFunction());

you will see 3 displayed as this is the result of the function. 

The value of the function can be any object not just a Number object (actually a primitive value) as in the example.

The final part of the Function object we need to examine is the use of parameters. 

In other languages you have to specify what parameters are to be passed to a function but in JavaScript you don’t. When you call a Function you can simply supply as many arguments as you like as a list of comma separated objects. The list is used to create an array like object called arguments that is available to the code of the Function.

For example:

var myFunction= 
  new Function("var ans=arguments[0]+arguments[1];
     return ans");

and now you can call the function using:

alert(myFunction(1,2));

and you will see 3 displayed. The arguments 1 and 2 are automatically converted into the properties of the arguments object as arguments[0] and arguments[1].

Notice that this means that when you define a function you can call it with as many arguments of any type you care to use.

This mechanism is the basic way that JavaScript deals with function parameters but, of course, it is nothing like the way other languages allow you to specify parameters. To make coding easier and more familiar JavaScript allows you to specify a parameter list of variables when you define a function.

For example:

var myFunction=
 new Function("a","b","var ans=a+b;return ans");

The values that you specify when you call the function are still used to create the arguments object but they are also used to create the local variables a and b with a=arguments[0] and b=arguments[1] and hence the function will return the sum of a and b no matter what they are set to when the function is evaluated. 

For example:

alert(myFunction(1,2));

sets a to reference 1 and b to reference 2 and then evaluates the body. 

Notice that function parameters can be any object and not just the Number objects used in the example. You can also think of what is passed as being a reference to an object, even it it happens to be a primitive value, in all cases. 

You can also use as many parameters in a function definition as you care to define and use as many as you care to when you execute the function. For each parameter you give a value to there is a variable of the same name with that value as part of the function's code. Any missing parameters are undefined and it is up to your code to deal with this. 

Also notice that this implies that there is no JavaScript form of function overloading because  functions don't have fixed signatures

In fact parameters in JavaScript are a little more subtle than this and we will have to come back to them later after we have found some more convenient ways of creating Function objects – see Chapter 7.

Other Ways Of Creating Function Objects

You could just use the Function object approach to creating JavaScript code but it isn't exactly convenient to have to enclose all code in quotes or form a String object.

This said, there are times when converting a String object containing code into an executable Function object is useful, but these tend to be considered advanced techniques.

JavaScript before ES2015 provides two other ways to define a Function object and they both look more like function definitions in other languages – the Function expression and the Function statement.

The purpose of the Function expression is to give you a way to define a function without using a String to store the code. This is more secure and it allows for optimizations. A Function expression also looks a lot like a lambda expression in other languages.

ES2015 also introduced “arrow” functions as a forth way of defining a Function object. Arrow functions look even more like lambda expressions in other languages but this isn’t their real purpose as JavaScript has long had adequate support for lambdas in the form of the Function expression. Arrow functions are mostly about writing functions using a more condensed syntax and they solve a long standing problem with the way methods are implemented using this.

The purpose of a Function statement is to make JavaScript Functions look more like functions in other objects. A Function statement obscures the fact that you are creating an object and it appears to give the function a fixed name. It also allows a style of programming based on a “top-down” approach to work because of the application of hoisting – see later.

Notice that even though these look different they also create a Function object just like the constructor although with some differences.

Lets’ start with the Function expression.

The Function Expression

This is just a shortcut to creating a Function object and doesn't really introduce anything new but you can now write:

function(parameters){statements};

Notice that the function body is now specified as statements enclosed in curly brackets and it is specified as part of the program text not as a String.

This means that it cannot change at runtime and so the JavaScript engine is able to make optimizations that cannot be made when the code is specified as a possibly dynamic String. That is, with a function expression the function’s code is known and fixed at “compile time” and hence more easily optimized.

Enclosing the code in curly brackets {} is also the notation used to create compound statements in JavaScript – that is, any list of statements enclosed in curly brackets is regarded as a single statement. 

For example the previous Function object can be written:

var myFunction=function(a,b){var ans=a+b; return ans;};

or by including line-breaks to produce a more usual formatting:

var myFunction= function(a,b){
                 var ans=a+b;
                 return ans;
                };

This has the advantage that this looks more like a function definition in a non-object-oriented language. In particular it also looks a lot more like a lambda expression which you will find in most modern languages.

It is important to keep in mind that while this looks like a simple function declaration as you would find in other languages it isn't.

A function expression creates a Function object exactly like the Function constructor does.

Also notice that the variable assigned to becomes a reference to the function object as with the constructor.

Also notice that again just as when you use the constructor the Function object is anonymous. All you can do is to set a variable to reference it but those variables can be set to reference something else at any time.

The Arrow Function ES2015

The arrow function is mostly a condensed syntax for the function expression. You can use it to define a function as simply as:

(param1,parm2…, parmN)=> {statements};

For example:

(a,b)=>{
        var ans=a+b;
        return ans;
       };

This returns a Function object which can be used in the normal way.

For example you can store a reference to the arrow function in a variable:

var myFunction=(a,b)=>{
                       var ans=a+b;
                       return ans;
                      };

and you can call the function in the usual way:

myFunction(1,2);

There are some syntactic shortcuts you can use, but this is more or less all there is to an arrow function – with one exception. Arrow functions do not have a this of their own, they inherit whatever value for this is in use at the time of their declaration.

This makes them unsuitable for use as method definitions but much better for passing to other Functions as parameters.

Apart from this everything that is true of a function expression is also true of an arrow function.

Now we need to look at the Function statement.

JustJavaScripticon

 



Last Updated ( Monday, 21 May 2018 )
 
 

   
Banner
RSS feed of all content
I Programmer - full contents
Copyright © 2018 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.