Functions are the heart of ECMAScript: a collection of statements that can be run anywhere at anytime. Functions are declared with the keyword function, followed by a set of arguments, and finally by the code to execute enclosed in braces. The basic syntax is:
This function can then be called by using the function name, followed by the function arguments enclosed in parentheses (and separated by commas,if there are multiple arguments). The code to call the sayHi() function looks like this:sayHi(“Nicholas”, “how are you today?”);
This code results in the alert displayed in Figure
The sayHi() function doesn’t specify a return value, but it requires no special declaration (such as void is used in Java) to do so. Likewise, a function doesn’t need to explicitly declare a return value type if the function does indeed return a value. The function need only use the return operator followed by the value to return:
The value of the sum function is returned and assigned to a variable like this:
Another important concept is that,just as in Java, the function stops executing code after a return statement is executed. Therefore, any code that comes after a return statement is not executed. For example,the alert in the following function is never displayed:
It is possible to have more than one return statement in a function, as in this function:
The previous function is designed to return the difference between two numbers. To do so, it must always subtract the smaller number from the larger, which results in an if statement to determine which return statement to execute.
If a function doesn’t return a value,it can use the return operator without any parameters to exit a function at any time. Example:
In this code, the alert will never be displayed if the message is equal to the string “bye”.
ECMAScript functions cannot be overloaded. This may come as a surprise, considering ECMAScript closely resembles other higher-level programming languages that support overloading. You can define two functions with the same name in the same scope without an error; however, the last function becomes the one that is used. Consider the following example:
What do you think will be displayed from this code snippet? The alert will show “20”, because the second doAdd() definition overwrites the first. Although this can be annoying to a developer, you have a way to work around this limitation by using the arguments object.
The arguments object
Within a function’s code, a special object called arguments gives the developer access to the function’s arguments without specifically naming them. For example,in the sayHi() function,the first argument is given the name message.The same value can also be accessed by referencing arguments,which asks for the value of the first argument (the first argument is in position 0, the second is in position 1,and so on.). Therefore, the function can be rewritten without naming the argument explicitly:
The arguments object can also be used to check the number of arguments passed into the function by referencing the arguments.length property. The following example outputs the number of arguments each time the function is called:
This snippet shows alerts displaying “2”, “0”, and “1” (in that order). In this way, the arguments object puts the responsibility on the developer to check the arguments that are passed into a function.
By using the arguments object to determine the number of arguments passed into the function, it is possible to simulate the overloading of functions:
The function doAdd() adds 10 to a number only if there is one argument; if there are two arguments, they are simply added together and returned. So doAdd(10) outputs “20” whereas doAdd(30,20) outputs “50”. It’s not quite as good as overloading, but it is a sufficient workaround for this ECMAScript limitation.
The Function class
Perhaps the most interesting aspect of ECMAScript is that functions are actually full-fledged objects. A Function class represents each and every function a developer defines. The syntax for creating a function using the Function class directly is as follows:
var function_name = new Function(argument1, argument2,..,argumentN, function_body);
In this form, each of the function arguments is one parameter, with the final parameter being the function body (the code to execute). Each of these parameters must be a string. Remember this function?
Admittedly, this form is a little bit harder to write because of the nature of strings, but understand that functions are just reference types and they always behave as if using the Function class explicitly created
for them. Remember this example?
As you remember, the second function overrides the first, making doAdd(10) output “20” instead of “110”. This concept becomes a whole lot clearer if this block is rewritten as follows:
Looking at this code, it is clear that the value of doAdd has changed to point to a different object. Yes, function names are just reference values pointing to a function object and behave just as other pointers do. It is even possible to have two variables point to the same function:
Here, the variable doAdd is defined as a function, and then alsoDoAdd is declared to point to the same function. Both can then be used to execute the function’s code and output the same result, “20”. So if a function name is just a variable pointing to a function, is it possible to pass a function as an argument to another function? Yes!
In this example, callAnotherFunction() accepts two arguments: a function to call and an argument to pass to the function. This code passes the doAdd() function into callAnotherFunction() with an argument of 10, outputting “20”.
Because functions are reference types, they can also have properties and methods. The one property defined in ECMAScript is length, which indicates the number of arguments that a function expects. Example:
The function doAdd() defines one argument to pass in, so its length is 1; sayHi() defines no arguments, so its length is 0. Remember, ECMAScript functions can accept any number of arguments (up to 255) regardless of how many are defined. The length property just gives a convenient way to check how many arguments are expected by default.
Function objects also have the standard valueOf() and toString() methods shared by all objects. Both of these methods return the source code for the function and are particularly useful in debugging. For example:
This code outputs the exact text of the doAdd() function (see Figure).
One of the most misunderstood aspects of ECMAScript is its support for closures. Closures are functions whose lexical representation includes variables that aren’t evaluated, meaning that functions are capable of using variables defined outside of the function itself. Using global variables in ECMAScript is a simple example of a closure. Consider the following example:
In this code, the variable sMessage isn’t evaluated for the function sayHelloWorld() while the scripts is being loaded into memory. The function captures sMessage for later use, which is to say that the interpreter knows to check the value of sMessage when the function is called. When sayHelloWorld() is called (on the last line), the value of sMessage is assigned and the message “Hello World!” is displayed. Closures can get more complicated, as when you are defining a function inside of another function, as shown here:
Here, the function addNumbers() contains a function (the closure) named doAddition(). The internal function is a closure because it captures the arguments of the outer function, iNum1 and iNum2, as well as the global variable iBaseNum. The last step of addNumbers() calls the inner function, which adds the two arguments and the global variable and returns the value. The important concept to grasp here is that doAddition() doesn’t accept any arguments at all; the values it uses are captured from the execution environment.
As you can see, closures are a very powerful, versatile part of ECMAScript that can be used to perform complex calculations. Just as when you use any advanced functionality, exercise caution when using closures because they can get extremely complex.
Java Script Related Tutorials
|Adv Java Tutorial||Core Java Tutorial|
|Java-Springs Tutorial||Java Servlets Tutorial|
|EJB(Enterprise JavaBeans) Tutorial||JavaServer Faces (JSF) Tutorial|
|Java Swing Tutorial||Java Tutorial|
|JavaMail API Tutorial||Java 8 Tutorial|
|Java XML Tutorial||Java Bean Utils Tutorial|
|The Java Debugger (JDB) Tutorial||Java.math Package Tutorial|
Java Script Related Interview Questions
|Java Script Interview Questions||Adv Java Interview Questions|
|Core Java Interview Questions||Java-Springs Interview Questions|
|Java Servlets Interview Questions||EJB(Enterprise JavaBeans) Interview Questions|
|JavaServer Faces (JSF) Interview Questions||Java Swing Interview Questions|
|Java 8 Interview Questions||Java XML Interview Questions|
|JavaFX Interview Questions||The Java Debugger (JDB) Interview Questions|
Java Script Related Practice Tests
|Java Script Practice Tests||Adv Java Practice Tests|
|Core Java Practice Tests||Java-Springs Practice Tests|
|Java Servlets Practice Tests||EJB(Enterprise JavaBeans) Practice Tests|
|JavaServer Faces (JSF) Practice Tests||Java 8 Practice Tests|
Java Script Tutorial
Browser And Operating System Detection
All About Events
Advanced Dom Techniques
Forms And Data Integrity
Drag And Drop
Interacting With Plugins
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.