SlideShare a Scribd company logo
1 of 20
JAVASCRIPT
FUNCTIONS
ADAM CRABTREE
(REPURPOSED FROM PIYUSH KATARIYA’S

HTTP://GOO.GL/ Z9WEMC)
FUNCTION
Callable first class citizen (Can be passed and return as
object)

No overloading
Definitions
• var add = new Function(‘a’, ‘b’, ‘return a + b’);
• var add = function (a, b) { return a + b; };
• function add(a, b) { return a + b;}

Blessed with
• this
• arguments
JAVASCRIPT - LENGTH
Specifies the number of arguments expected by the function.

Syntax
• functionName.length
E.g.,
• console.log( (function () {}).length );

// 0

• console.log( (function (a) {}).length );

// 1

• console.log( (function (a, b) {}).length ); // 2
INVOCATION PATTERN I
Function invocation (Direct Invocation)
• add(1, 2)
• isPalindrome(‘madam’)
this bound to global object !!!
INVOCATION PATTERN II
Method Invocation
Method => a function stored as property of object

this bound to method holder object

var obj = {
value : 0, //zero
increment : function (inc) {
this.value += typeof inc === ‘number’ ? inc : 1;

}
}
obj.increment() ; // 1
obj.increment(2); // 3
INVOCATION PATTERN III
Constructor Invocation (OO style)
var Employee = function (firstName, title) {
this.firstName = firstName;
this.title = title;
};
Employee.protoype.getName = function () { return this.name;};
Employee.protoype.getTitle = function () { return this.title;};
var employee = new Employee(‘Tom’, ‘Software Engineer’)
employee.getName(); // ‘Tom’
employee.getTitle(); // ‘Software Engineer’
INVOCATION PATTERN IV
Apply Invocation (Reflective Invocation)

var argsArray = [2, 3];
var sum = add.apply( null, argsArray);
var sum = add.call( null, 2, 3);

// 3
// 3

var firstName = Employee.getName.apply(empObject);
var firstName = Employee.getName.call(empObject);
FUNCTION AS A CLASS
var someClass = function (property) {
this.publicProperty = property;

var privateVariable = “value”;
this.publicMethod = function () {
//code for method definition

};
var privateMethod = function () {
//code for method definition
};

// return this;
}
FUNCTION AS A MODULE
var counterModule = ( function( ) {
var privateCount = 0;
function changeBy(val) {
return privateCount += val;
}
return {
increment : changeBy.bind(null, 1),
decrement : changeBy.bind(null, -1),
currentValue : function() {return privateCount;}
};
} ) ( );
JAVASCRIPT - CALL
Calls a function with a given this value and
arguments provided individually.
Syntax
• fun.call(thisArg[, arg1[, arg2[, ...]]])
JAVASCRIPT - CALL
function diplayInfo(year, month, day){
return "Name:" + this.name + ";birthday:" + year +
"." + month + "." + day;

}

var p = { name: "Jason" };
diplayInfo.call(p, 1985, 11, 5);
JAVASCRIPT - APPLY
Calls a function with a given this value
and arguments provided as an array

Syntax
• fun.apply(thisArg[, argsArray])
JAVASCRIPT - APPLY
function diplayInfo(year, month, day){
return "Name:" + this.name + ";birthday:" + year +
"." + month + "." + day;
}
var p = { name: "Jason" };
console.log(diplayInfo.apply(p, [1985, 11, 5]));
JAVASCRIPT - CALLEE
Specifies the currently executing function
callee is a property of the arguments object.
Syntax
• [function.]arguments.callee
JAVASCRIPT - CALLEE
function factorial(n){
if (n <= 0)
return 1;
else
return n * arguments.callee(n - 1);
}
factorial(4);
JAVASCRIPT - BIND
Creates a new function that, when called, has
its this keyword set to the provided value, with a given
sequence of arguments preceding any provided when the
new function is called.

Syntax
fun.bind(thisArg[, arg1[, arg2[, ...]]])
JAVASCRIPT - BIND
var x = 9;
var module = {
x: 81,

getX: function() { return this.x; }
};
module.getX(); //Answer: ?
var getX = module.getX;
getX();

//Answer: ?

var boundGetX = getX.bind(module);
boundGetX();

//Answer: ?

module.x = 100;
boundGetX(); //Answer: ?
JAVASCRIPT - BIND
var checkNumericRange = function (value) {
return value >= this.min && value <= this.max;

}

var range = { min: 10, max: 20 };

var boundCheckNumericRange =
checkNumericRange.bind(range);

var result = boundCheckNumericRange (12);
Result = ??
JAVASCRIPT - BIND

var displayArgs = function (val1, val2, val3, val4) {
console.log(val1 + " " + val2 + " " + val3 + " " + val4);
}

var emptyObject = {};

var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");

displayArgs2("b", "c");

//Answer: ?
JAVASCRIPT - BIND
Function.prototype.bind = function (objToBind) {
var self = this;

return function () {
var argArr = Array.prototype.slice.call(arguments);
return self.apply(objToBind || null, argArr);
};
}

More Related Content

What's hot

Inline function
Inline functionInline function
Inline function
Tech_MX
 
Javascript function
Javascript functionJavascript function
Javascript function
LearningTech
 

What's hot (20)

C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Function C++
Function C++ Function C++
Function C++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Inline function
Inline functionInline function
Inline function
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Javascript function
Javascript functionJavascript function
Javascript function
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
functions of C++
functions of C++functions of C++
functions of C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 

Viewers also liked

Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScript
Roland Bouman
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
brianjihoonlee
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 

Viewers also liked (20)

Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScript
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
PostgreSQL and JSON with Python - Przemek Lewandowski
PostgreSQL and JSON  with Python - Przemek Lewandowski PostgreSQL and JSON  with Python - Przemek Lewandowski
PostgreSQL and JSON with Python - Przemek Lewandowski
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
2java Oop
2java Oop2java Oop
2java Oop
 
TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programming
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
02 java programming basic
02  java programming basic02  java programming basic
02 java programming basic
 
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
 
Fp java8
Fp java8Fp java8
Fp java8
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Programming
ProgrammingProgramming
Programming
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 

Similar to LinkedIn TBC JavaScript 100: Functions

JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
Glan Thomas
 

Similar to LinkedIn TBC JavaScript 100: Functions (20)

25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Javascript Exercises
Javascript ExercisesJavascript Exercises
Javascript Exercises
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 

LinkedIn TBC JavaScript 100: Functions

  • 1. JAVASCRIPT FUNCTIONS ADAM CRABTREE (REPURPOSED FROM PIYUSH KATARIYA’S HTTP://GOO.GL/ Z9WEMC)
  • 2. FUNCTION Callable first class citizen (Can be passed and return as object) No overloading Definitions • var add = new Function(‘a’, ‘b’, ‘return a + b’); • var add = function (a, b) { return a + b; }; • function add(a, b) { return a + b;} Blessed with • this • arguments
  • 3. JAVASCRIPT - LENGTH Specifies the number of arguments expected by the function. Syntax • functionName.length E.g., • console.log( (function () {}).length ); // 0 • console.log( (function (a) {}).length ); // 1 • console.log( (function (a, b) {}).length ); // 2
  • 4. INVOCATION PATTERN I Function invocation (Direct Invocation) • add(1, 2) • isPalindrome(‘madam’) this bound to global object !!!
  • 5. INVOCATION PATTERN II Method Invocation Method => a function stored as property of object this bound to method holder object var obj = { value : 0, //zero increment : function (inc) { this.value += typeof inc === ‘number’ ? inc : 1; } } obj.increment() ; // 1 obj.increment(2); // 3
  • 6. INVOCATION PATTERN III Constructor Invocation (OO style) var Employee = function (firstName, title) { this.firstName = firstName; this.title = title; }; Employee.protoype.getName = function () { return this.name;}; Employee.protoype.getTitle = function () { return this.title;}; var employee = new Employee(‘Tom’, ‘Software Engineer’) employee.getName(); // ‘Tom’ employee.getTitle(); // ‘Software Engineer’
  • 7. INVOCATION PATTERN IV Apply Invocation (Reflective Invocation) var argsArray = [2, 3]; var sum = add.apply( null, argsArray); var sum = add.call( null, 2, 3); // 3 // 3 var firstName = Employee.getName.apply(empObject); var firstName = Employee.getName.call(empObject);
  • 8. FUNCTION AS A CLASS var someClass = function (property) { this.publicProperty = property; var privateVariable = “value”; this.publicMethod = function () { //code for method definition }; var privateMethod = function () { //code for method definition }; // return this; }
  • 9. FUNCTION AS A MODULE var counterModule = ( function( ) { var privateCount = 0; function changeBy(val) { return privateCount += val; } return { increment : changeBy.bind(null, 1), decrement : changeBy.bind(null, -1), currentValue : function() {return privateCount;} }; } ) ( );
  • 10. JAVASCRIPT - CALL Calls a function with a given this value and arguments provided individually. Syntax • fun.call(thisArg[, arg1[, arg2[, ...]]])
  • 11. JAVASCRIPT - CALL function diplayInfo(year, month, day){ return "Name:" + this.name + ";birthday:" + year + "." + month + "." + day; } var p = { name: "Jason" }; diplayInfo.call(p, 1985, 11, 5);
  • 12. JAVASCRIPT - APPLY Calls a function with a given this value and arguments provided as an array Syntax • fun.apply(thisArg[, argsArray])
  • 13. JAVASCRIPT - APPLY function diplayInfo(year, month, day){ return "Name:" + this.name + ";birthday:" + year + "." + month + "." + day; } var p = { name: "Jason" }; console.log(diplayInfo.apply(p, [1985, 11, 5]));
  • 14. JAVASCRIPT - CALLEE Specifies the currently executing function callee is a property of the arguments object. Syntax • [function.]arguments.callee
  • 15. JAVASCRIPT - CALLEE function factorial(n){ if (n <= 0) return 1; else return n * arguments.callee(n - 1); } factorial(4);
  • 16. JAVASCRIPT - BIND Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. Syntax fun.bind(thisArg[, arg1[, arg2[, ...]]])
  • 17. JAVASCRIPT - BIND var x = 9; var module = { x: 81, getX: function() { return this.x; } }; module.getX(); //Answer: ? var getX = module.getX; getX(); //Answer: ? var boundGetX = getX.bind(module); boundGetX(); //Answer: ? module.x = 100; boundGetX(); //Answer: ?
  • 18. JAVASCRIPT - BIND var checkNumericRange = function (value) { return value >= this.min && value <= this.max; } var range = { min: 10, max: 20 }; var boundCheckNumericRange = checkNumericRange.bind(range); var result = boundCheckNumericRange (12); Result = ??
  • 19. JAVASCRIPT - BIND var displayArgs = function (val1, val2, val3, val4) { console.log(val1 + " " + val2 + " " + val3 + " " + val4); } var emptyObject = {}; var displayArgs2 = displayArgs.bind(emptyObject, 12, "a"); displayArgs2("b", "c"); //Answer: ?
  • 20. JAVASCRIPT - BIND Function.prototype.bind = function (objToBind) { var self = this; return function () { var argArr = Array.prototype.slice.call(arguments); return self.apply(objToBind || null, argArr); }; }