SlideShare a Scribd company logo
1 of 14
Advanced
JavaScript
JavaScript Functions: As first
class objects, declarations,
expressions, IIFE’s and hoisting!
In computer science, a programming language is said to support first-class functions
(or function literals) if it treats functions as first-class objects. Specifically, this means
that the language supports constructing new functions during the execution of a
program, storing them in data structures, passing them as arguments to other
functions, and returning them as the values of other functions.
 A function is an instance of the
Object type
 A function can have properties and
has a link back to its constructor
method
 You can store the function in a
variable
 You can pass the function as a
parameter to another function
 You can return the function from a
function
Since JavaScript is single-threaded, meaning that only one operation happens at a
time, each operation that’s going to happen is queued along this single thread. The
strategy of passing in a function to be executed after the rest of the parent
function’s operations are complete is one of the basic characteristics of languages
that support higher-order functions. It allows for asynchronous behavior, so a script
can continue executing while waiting for a result. The ability to pass a callback
function is critical when dealing with resources that may return a result after an
undetermined period of time.
This is very useful in a web programming
environment, where a script may send an Ajax
request off to a server, and then need to
handle the response whenever it arrives.
Node.js frequently uses callbacks to make the
most efficient use of server resources. This
approach is also useful in the case of an app
that waits for user input before performing a
function.
What is a Function Declaration?
A Function Declaration defines a named function variable without requiring
variable assignment. Function Declarations occur as standalone constructs and
cannot be nested within non-function blocks. It’s helpful to think of them as siblings
of Variable Declarations. Just as Variable Declarations must start with “var”,
Function Declarations must begin with “function”.
The function name is visible within it’s scope and the scope of it’s parent which is
good because otherwise it would be unreachable.
function bar() {
return 3;
}
bar() //3
bar //function
What is a Function Expression?
A Function Expression defines a function as a part of a larger expression syntax
(typically a variable assignment ). Functions defined via Functions Expressions
can be named or anonymous. Function Expressions must not start with
“function”, hence the parentheses around the self invoking example below.
//anonymous function expression
var a = function() {
return 3;
}
//named function expression
var a = function bar() {
return 3;
}
//self invoking function expression
(function sayHello() {
alert("hello!");
})();
Wait, what’s Hoisting?
Function declarations and function variables are always moved (‘hoisted’) to the top
of their JavaScript scope by the JavaScript interpreter.
When a function declaration is hoisted the entire function body is lifted with it, so
after the interpreter has finished with the code on the right it runs more like this:
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
alert(foo());
function foo(){
//define bar once
function bar() {
return 3;
}
//redefine it
function bar() {
return 8;
}
//return its invocation
return bar(); //8
}
alert(foo());
An immediately-invoked function expression (or IIFE, pronounced "iffy") is a
JavaScript design pattern which produces a lexical scope using JavaScript's
function scoping. Immediately-invoked function expressions can be used to avoid
variable hoisting from within blocks, protect against polluting the global
environment and simultaneously allow public access to methods while retaining
privacy for variables defined within the function. This pattern has been referred to
as a self-executing anonymous function, but Ben Alman introduced the term IIFE
as a more semantically accurate term for the pattern, shortly after its discussion
arose on comp.lang.javascript.
(function () { // logic here })();
We see below that this is just an anonymous function declaration enclosed in a
set of parentheses. So if we want to invoke this new function expression right
away we just need to tack a couple of parentheses on the end.
Remove the lead parenthesis and the interpreter will ‘see’ an un-callable
function declaration. Remove the trailing parentheses and nothing will
happen… no execution! Passing variables into the scope is done as follows:
(function(a, b) { … })("hello", "world");
// IIFE - Immediately Invoked Function Expression
(function($, window, document) {
// The $, window, document are now locally scoped
// The rest of your code goes here!
}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
This example of the IIFE module pattern passes in three global variable to the
function so that they are now locally scoped. This is more efficient for
accessing these objects in real-time… an often used trick!
Books
Books
Books

More Related Content

What's hot

Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorialadelaticleanu
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript FundamentalsSrdjan Strbanovic
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use casesSrajan Mor
 
Unison Language - Contact
Unison Language - ContactUnison Language - Contact
Unison Language - ContactPhilip Schwarz
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedurepragya ratan
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++Learn By Watch
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingArunaDevi63
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method OverloadingMichael Heron
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 

What's hot (20)

Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
Java script basic
Java script basicJava script basic
Java script basic
 
Java script function
Java script functionJava script function
Java script function
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Unison Language - Contact
Unison Language - ContactUnison Language - Contact
Unison Language - Contact
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedure
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 
Functions1
Functions1Functions1
Functions1
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
 
Linq
LinqLinq
Linq
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 

Viewers also liked

Ponencia de Jose Vte. Besa Gresa (Director de innerUp)
Ponencia de Jose Vte. Besa Gresa (Director de innerUp)Ponencia de Jose Vte. Besa Gresa (Director de innerUp)
Ponencia de Jose Vte. Besa Gresa (Director de innerUp)innerUp
 
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLS
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLSPROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLS
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLSPravin Nkl
 
Associate Degree cerificate of 2nd honours
 Associate Degree cerificate of 2nd honours  Associate Degree cerificate of 2nd honours
Associate Degree cerificate of 2nd honours Abdulaziz Almass
 
Air force request to declassify an osi paper on ufo's
Air force request to declassify an osi paper on ufo'sAir force request to declassify an osi paper on ufo's
Air force request to declassify an osi paper on ufo'sClifford Stone
 
Democracia en atenas
Democracia en atenasDemocracia en atenas
Democracia en atenasGabbyp16
 
Javascript under the hood 1
Javascript under the hood 1Javascript under the hood 1
Javascript under the hood 1Thang Tran Duc
 
Ponencia Sr. Joan López Cobo - "Comunicación Humana"
Ponencia Sr. Joan López Cobo - "Comunicación Humana"Ponencia Sr. Joan López Cobo - "Comunicación Humana"
Ponencia Sr. Joan López Cobo - "Comunicación Humana"innerUp
 
VRはどれくらいあなたの身近にやってくる?
VRはどれくらいあなたの身近にやってくる?VRはどれくらいあなたの身近にやってくる?
VRはどれくらいあなたの身近にやってくる?一貴 加藤
 
Team Virtual Technology Presentation
Team Virtual Technology Presentation Team Virtual Technology Presentation
Team Virtual Technology Presentation William Allen
 
Philosophy and Curriculum
Philosophy and CurriculumPhilosophy and Curriculum
Philosophy and CurriculumRPVadhera
 
Recruiting Agentur als Genossenschaft
Recruiting Agentur als GenossenschaftRecruiting Agentur als Genossenschaft
Recruiting Agentur als GenossenschaftTimo Bock
 

Viewers also liked (17)

Ponencia de Jose Vte. Besa Gresa (Director de innerUp)
Ponencia de Jose Vte. Besa Gresa (Director de innerUp)Ponencia de Jose Vte. Besa Gresa (Director de innerUp)
Ponencia de Jose Vte. Besa Gresa (Director de innerUp)
 
Sociograma del aula
Sociograma del aulaSociograma del aula
Sociograma del aula
 
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLS
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLSPROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLS
PROJECT ENGINEER QUALITY INSPECTOR WITH PROJECT MANAGEMEMT SKILLS
 
4[1]fios soltos
4[1]fios soltos4[1]fios soltos
4[1]fios soltos
 
Associate Degree cerificate of 2nd honours
 Associate Degree cerificate of 2nd honours  Associate Degree cerificate of 2nd honours
Associate Degree cerificate of 2nd honours
 
Budgeting
BudgetingBudgeting
Budgeting
 
FENDER TUNER APP PR
FENDER TUNER APP PRFENDER TUNER APP PR
FENDER TUNER APP PR
 
Air force request to declassify an osi paper on ufo's
Air force request to declassify an osi paper on ufo'sAir force request to declassify an osi paper on ufo's
Air force request to declassify an osi paper on ufo's
 
Cocina estudios 5
Cocina estudios 5Cocina estudios 5
Cocina estudios 5
 
Democracia en atenas
Democracia en atenasDemocracia en atenas
Democracia en atenas
 
Javascript under the hood 1
Javascript under the hood 1Javascript under the hood 1
Javascript under the hood 1
 
Ponencia Sr. Joan López Cobo - "Comunicación Humana"
Ponencia Sr. Joan López Cobo - "Comunicación Humana"Ponencia Sr. Joan López Cobo - "Comunicación Humana"
Ponencia Sr. Joan López Cobo - "Comunicación Humana"
 
VRはどれくらいあなたの身近にやってくる?
VRはどれくらいあなたの身近にやってくる?VRはどれくらいあなたの身近にやってくる?
VRはどれくらいあなたの身近にやってくる?
 
Team Virtual Technology Presentation
Team Virtual Technology Presentation Team Virtual Technology Presentation
Team Virtual Technology Presentation
 
Aws overview
Aws overviewAws overview
Aws overview
 
Philosophy and Curriculum
Philosophy and CurriculumPhilosophy and Curriculum
Philosophy and Curriculum
 
Recruiting Agentur als Genossenschaft
Recruiting Agentur als GenossenschaftRecruiting Agentur als Genossenschaft
Recruiting Agentur als Genossenschaft
 

Similar to Books

Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAMAN ANAND
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes NUST Stuff
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsRuth Marvin
 
What is Closure and Its Uses in PHP
 What is Closure and Its Uses in PHP What is Closure and Its Uses in PHP
What is Closure and Its Uses in PHPAndolasoft Inc
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?Ilya Sidorov
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 

Similar to Books (20)

Function in C++
Function in C++Function in C++
Function in C++
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Java features
Java featuresJava features
Java features
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
What is Closure and Its Uses in PHP
 What is Closure and Its Uses in PHP What is Closure and Its Uses in PHP
What is Closure and Its Uses in PHP
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
4. function
4. function4. function
4. function
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 

Books

  • 1. Advanced JavaScript JavaScript Functions: As first class objects, declarations, expressions, IIFE’s and hoisting!
  • 2. In computer science, a programming language is said to support first-class functions (or function literals) if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.  A function is an instance of the Object type  A function can have properties and has a link back to its constructor method  You can store the function in a variable  You can pass the function as a parameter to another function  You can return the function from a function
  • 3. Since JavaScript is single-threaded, meaning that only one operation happens at a time, each operation that’s going to happen is queued along this single thread. The strategy of passing in a function to be executed after the rest of the parent function’s operations are complete is one of the basic characteristics of languages that support higher-order functions. It allows for asynchronous behavior, so a script can continue executing while waiting for a result. The ability to pass a callback function is critical when dealing with resources that may return a result after an undetermined period of time. This is very useful in a web programming environment, where a script may send an Ajax request off to a server, and then need to handle the response whenever it arrives. Node.js frequently uses callbacks to make the most efficient use of server resources. This approach is also useful in the case of an app that waits for user input before performing a function.
  • 4.
  • 5. What is a Function Declaration? A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”. The function name is visible within it’s scope and the scope of it’s parent which is good because otherwise it would be unreachable. function bar() { return 3; } bar() //3 bar //function
  • 6. What is a Function Expression? A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous. Function Expressions must not start with “function”, hence the parentheses around the self invoking example below. //anonymous function expression var a = function() { return 3; } //named function expression var a = function bar() { return 3; } //self invoking function expression (function sayHello() { alert("hello!"); })();
  • 7. Wait, what’s Hoisting? Function declarations and function variables are always moved (‘hoisted’) to the top of their JavaScript scope by the JavaScript interpreter. When a function declaration is hoisted the entire function body is lifted with it, so after the interpreter has finished with the code on the right it runs more like this: function foo(){ function bar() { return 3; } return bar(); function bar() { return 8; } } alert(foo()); function foo(){ //define bar once function bar() { return 3; } //redefine it function bar() { return 8; } //return its invocation return bar(); //8 } alert(foo());
  • 8.
  • 9. An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This pattern has been referred to as a self-executing anonymous function, but Ben Alman introduced the term IIFE as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.
  • 10. (function () { // logic here })(); We see below that this is just an anonymous function declaration enclosed in a set of parentheses. So if we want to invoke this new function expression right away we just need to tack a couple of parentheses on the end. Remove the lead parenthesis and the interpreter will ‘see’ an un-callable function declaration. Remove the trailing parentheses and nothing will happen… no execution! Passing variables into the scope is done as follows: (function(a, b) { … })("hello", "world");
  • 11. // IIFE - Immediately Invoked Function Expression (function($, window, document) { // The $, window, document are now locally scoped // The rest of your code goes here! }(window.jQuery, window, document)); // The global jQuery object is passed as a parameter This example of the IIFE module pattern passes in three global variable to the function so that they are now locally scoped. This is more efficient for accessing these objects in real-time… an often used trick!