CSE 341 Lecture 25 More about JavaScript functions slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
12-Jun-15 JavaScript Language Fundamentals I. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
CSE 190M Extra Session #5 JavaScript scope and closures slides created by Marty Stepp
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
Taking JavaScript Seriously IS NOT THE WORST IDEA.
CSE 341 Lecture 24 JavaScript arrays and objects slides created by Marty Stepp
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
JS Basics 1 Lecture JavaScript - Basics. JS Basics 2 What is JavaScript JavaScript is a “simple”, interpreted, programming language with elementary object-
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSE 341 Lecture 29 a JavaScript, the bad parts slides created by Marty Stepp see also: JavaScript: The Good Parts, by.
Python Functions.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
CSE 341 Lecture 26 OOP, prototypes, and inheritance slides created by Marty Stepp
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Function the Ultimate Act III. Function Method Class Constructor Module.
Julian on JavaScript: Functions Julian M Bucknall, CTO.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
JavaScript scope and closures
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Functions.  Assignment #2 is now due on Wednesday, Nov 25 th  (No Quiz)  Go over the midterm  Backtrack and re-cover the question about tracing the.
Unit 10-JavaScript Functions Instructor: Brent Presley.
IS2802 Introduction to Multimedia Applications for Business Lecture 4: JavaScript, Loops, and Conditional Statements Rob Gleasure
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
JavaScript for C# developers Dhananjay Microsoft MVP
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Events CS The keyword this  all JavaScript code actually runs inside of an object  by default, code runs inside the global window object  all.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
Click to add Text Javascript Presented by Bunlong VAN Basic.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript Programming. What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers,
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
>> JavaScript: Location, Functions and Objects
JavaScript Syntax and Semantics
Functions Declarations, Function Expressions and IIFEs
JavaScript and Ajax (Expression and Operators)
T. Jumana Abu Shmais – AOU - Riyadh
Dynamic Scoping Lazy Evaluation
Functions, Regular expressions and Events
CS5220 Advanced Topics in Web Programming JavaScript Basics
CSE 341 Lecture 27 JavaScript scope and closures
CSE 341 Lecture 11 b closures; scoping rules
CS3220 Web and Internet Programming JavaScript Basics
Presentation transcript:

CSE 341 Lecture 25 More about JavaScript functions slides created by Marty Stepp

2 First-class functions JS functions are first-class objects. You can:  store a (reference to a) function in a variable  create an array of functions  use a function as a property of an object (a method)  pass a function as a parameter; return a function  write functions that take varying numbers of parameters  write higher-order functions (that take others as params)  define functions inside functions (nested functions)  define anonymous functions (lambdas)  store properties inside functions

3 Defining a function function name(paramName,..., paramName) { statements; } example: function sumTo(n) { var sum = 0; for (var i = 1; i <= n; i++) { sum += i; } return sum; }

4 Returning values function maybeReturn(n) { if (n % 2 == 0) { return "even"; } // else return undefined } parameter and return types are not declared  the function can return anything it wants  if a function returns nothing, it returns undefined  a function can sometimes return values and sometimes not

5 Calling a function functionName(expr,..., expr) example:  sumTo(6) // returns 21 extra parameters passed are ignored:  sumTo(3, "hello", null, 42) // returns 6 expected parameters not passed are undefined :  sumTo() // returns 0

6 Optional parameters function greet(name, msg) { if (typeof(msg) === "undefined") { msg = "Hello"; } print(msg + " to you, " + name); } > greet("Bob", "Good day"); Good day to you, Bob > greet("Sue"); Hello to you, Sue  to have an optional parameter, check whether it is defined

7 Object as argument specifier function mealCost(argObj) { var amt = argObj["subtotal"]; if (argObj["tax"]) { amt *= 1 + argObj["tax"]; } if (argObj["tip"]) { amt *= 1 + argObj["tip"]; } if (argObj["donation"]) { amt += argObj["donation"]; } return amt; } > mealCost({subtotal: 50.0, tip:.15}) 57.5 > mealCost({subtotal: 10.0, tax:.08, donation: true}) 11.8  specify many parameters as properties of a single object –can pass many args in any order; optional args; clear naming –this style is seen in JavaScript libraries (jQuery, Prototype)

8 Variadic functions (var-args) function addAll() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; }  addAll(1, 7, 4, 3) returns 15  addAll(1, 2, "3", 4, 5) returns " 3345" each function has an array property* named arguments that stores all parameter values passed to it  can be used to create variadic (var-args) functions * actually a duck-typed array-like object with a length field

9 Anonymous functions (lambdas) function(paramName,..., paramName) { statements; } anonymous functions can be stored, passed, returned > function foo(x, f) { return f(x) + 1; } > foo(5, function(n) { return n * n; }) 26 Exercise: Sort an array of strings case-insensitively. Exercise: Sort an array of names by last, then first, name.

10 Two ways to declare a function The following are equivalent: function name(params) {var name = function(params) { statements; statements;} var squared = function(x) { return x*x; };

11 Array higher-order functions * * most web browsers are missing some/all of these methods.every(function) accepts a function that returns a boolean value and calls it on each element until it returns false.filter(function) accepts a function that returns a boolean ; calls it on each element, returning a new array of the elements for which the function returned true.forEach(function) applies a "void" function to each element.map(function) applies function to each element; returns new array.reduce(function).reduce(function, initialValue).reduceRight(function).reduceRight(function, initialValue) accepts a function that accepts pairs of values and combines them into a single value; calls it on each element starting from the front, using the given initialValue (or element [0] if not passed) reduceRight starts from the end of the array.some(function) accepts a function that returns a boolean value and applies it to each element until it returns true

12 Higher-order functions in action > var a = [1, 2, 3, 4, 5]; > a.map(function(x) { return x*x; }) 1,4,9,16,25 > a.filter(function(x) { return x % 2 == 0; }) 2,4 Exercise: Given an array of strings, produce a new array that contains only the capitalized versions of the strings that contained 5 or more letters.

13 Nested functions // adds 1 to each element of an array of numbers function incrementAll(a) { function increment(n) { return n + 1; } var result = a.map(increment); return result; } functions can be declared inside of other functions  the scope of the inner function is only within the outer one

14 Invocation patterns functions can be invoked in four ways in JavaScript:  as a normal function  as a method of an object  as a constructor  through their apply property

15 Functions as methods an object's methods are just properties that are functions  the function uses the this keyword to refer to the object > var teacher = { name: "Tyler Durden", salary: 0.25, greet: function(you) { print("Hi " + you + ", I'm " + this.name); }, toString: function() { return "Prof. " + this.name; } }; > teacher.greet("kids"); Hi kids, I'm Tyler Durden

16 Function binding {... propertyName: function, // bind at... // declaration } object.propertyName = function; // bind later when a function is stored as a property of an object, a copy of that function is bound to the object  calling the function through that object will cause that object to be used as this during that particular call  if you don't call the function through the object, that object won't be used as this

17 The this keyword function printMe() { print("I am " + this); } > teacher.print = printMe; > teacher.print(); I am Prof. Tyler Durden > printMe(); I am [object global] > ({p: printMe}).p() I am [object Object] > var temp = teacher.print; > temp(); I am [object global]

18 Aside: Web event handlers Click Me HTML var b1 = document.getElementById("b1"); JS b1.onclick = function() {... }; most JavaScript code in web pages is event-driven  elements in the HTML have events that can be handled  you specify a JS function to run when the event occurs  the function can access/modify the page's appearance

19 Invoking with apply func.apply(thisObj, arguments); You can call a function using its apply property  allows you to set this to be anything you want  allows you to pass a function its arguments as an array var o = ({toString: function(){return "!"}}); > apply(printMe, o, []); I am ! Exercise: Write a function callBoth that takes two functions and an array of parameters and calls both, passing them those parameters, and printing both results.

20 Composing functions function compose(f, g) { return function() { return f(g.apply(this, arguments)); }; } JavaScript has no built-in syntax for composing functions  but you can use apply to write a helper for composition

21 How to curry functions function toArray(a, i) { // converts a var result = [], i = i || 0; // duck-typed obj while (i < a.length) { // into an array result.push(a[i++]); } return result; }; function curry(f) { // Usage: curry(f, arg1,...) var args = toArray(arguments, 1); // remove f return function() { return f.apply(this, args.concat(toArray(arguments))); }; } JavaScript doesn't include syntax for currying functions  but we can add such functionality ourselves

22 Methods of Function objects.toString() string representation of function (its code, usually).apply(this, args) calls a function using the given object as this and passing the given array of values as its parameters.call(this, arg1,...) var-args version of apply ; pass args without array.bind(this) attaches the function's this reference to given obj

23 A JS library: Underscore Adds functional language methods to JavaScript.  Collections: each, map, reduce, reduceRight, detect, select, reject, all, any, include, invoke, pluck, max, min, sortBy, sortedIndex, toArray, size  Arrays: first, rest, last, compact, flatten, without, uniq, intersect, zip, indexOf, lastIndexOf, range  Functions: bind, bindAll, memoize, delay, defer, wrap, compose  Objects: keys, values, functions, extend, clone, tap, isEqual, isEmpty, isElement, isArray, isArguments, isFunction, isString, isNumber, isBoolean, isDate, isRegExp, isNaN, isNull, isUndefined  Utility: noConflict, identity, times, breakLoop, mixin, uniqueId, template  Chaining: chain, value > _([1, 4, 2, 7, 3, 5]).max() 7