M3 - Part2 - JavaScript Functions
M3 - Part2 - JavaScript Functions
JavaScript Function
Functions
Function Object
Function declaration
Passing arguments by value and reference
Variable scope
Function Overloading
Optional argument
Argument objects
Argument hashes
Properties and methods of Function object
Prof Maheswari S VIT Chennai
3
Function Object
In JavaScript all functions are first-class instances of a global object
called Function.
Function object has certain properties and methods that can be
accessed by all functions.
The function objects can be passed as arguments to other
functions and can be returned by other functions.
Function Object
Declaring functions
Using function statement
Using function literal or anonymous function
Using Function class constructor
statement
function
An anonymous function does not have a name.
Anonymous functions can be passed to other functions.
Functions
Constructors
Function Constructors
Passing Arguments
By value
When primitive datatypes are passed to a function they cannot be
modified outside the function
Primitive datatypes (number, string, boolean,null,undefined)
By Reference
In composite type it is possible to modify their value outside the
function
Reference types (Object, Array, Function, Date, RegExp, Error)
Return values
All functions return value.
When no return statement is specified “undefined” is returned.
To return value in a function use return statement.
Variable scope
Scope refers to accessibility of a variable in a program.
Local – Accessible only within the function
Global – Accessible throughout the program
Explicit declaration of variable uses var refers that the variable is
declared in the current scope. (If declared outside-global, If
declared inside a function or loop then it is local).
Implicit declaration does not use var and provides a global scope
Variable scope
Variable scope
Variable scope
Function Overloading
JavaScript does not support function overloading directly.
When functions are overloaded the recent definition will be called.
As the function pointer holds only the reference the recent
function overwrites the original memory location.
Anonymous Function
Anonymous Function
Optional Arguments
JavaScript does not support optional arguments.
When the argument is not passed it is treated as undefined.
Optional Arguments
Argument Hashes
An associative array or a hash or an Object can also be passed to a
function.
REFERENCE