There are two ways to use functions:
1. Using function declarations:
function print() {
...
}
2. Using function expressions:
var print = function() {
....
};
The JS parser does work in 2 passes. In 1st pass - it scans and stores all the functions. In 2nd pass, it actually executes the code. This enables us to write function declarations after the function calls in the code.
When the JS parser is in 1st pass, it comes across declaration #1 and creates a reference variable named "print", and stores the address of the function in it. It then moves forward and encounters #2. Since it is not a declaration but a expression, it ignores and moves forward, and starts the 2nd pass.
When the 2nd pass starts, actual code interpretation is carried out. During this, if it comes across a call to a previously declared function, it simply executes the function as it is previously known. However, as it hits #2, it processes the expression in following way:
- Create a function as per code
- Create a variable named "print" (as per code)
- Store the address of the function in the print variable
How do they differ?
Time of execution: #1 type declarations are processed before run-time, all functions are available before even starting the interpretation of code. #2 type declarations are processed at run-time, meaning the interpreter creates function and reference on the fly. This also means that you have to create a function expression before calling it. This will not work:
foo(); //first call
var foo = function() {
} // then define
Naming: Both the functions use reference variables to store their address. The reference of #1 types are stored in a variable with the same name as the declaration, and this is automatically done by the interpreter. For #2 types, there is no automatic variable generation, simple a reference is returned. It is up to the programmer to decide what to do with it. It can be left as an anonymous function, or assigned to a variable manually.
Functions are First Class members in JavaScript
First class members in any language are those elements which can be - 1. Assigned to a variable
2. Passed to a function
3. Returned from a function
All this can be achieved by passing around function references in JavaScript. A classic example is the Array.sort function:
Array.sort([compareFunction])
compareFunction is a function which knows how to compare any 2 values in the array. The sorting algorithm implicitly calls this function for each sort compare.
Useful information for students Thanks for Sharing.
ReplyDeleteMEAN Stack Training in Hyderabad