SlideShare una empresa de Scribd logo
1 de 52
Beyond the Curly Braces Advanced JavaScript Sergio Pereira WI.NET Users Group – July 14th2009
WHOIS About Sergio sergio@sergiopereira.com http://sergiopereira.com/blog @sergiopereira http://chicagoalt.net
agenda
Advanced javascript
Advanced javascript BUT FIRST THE BASICS
Advanced javascript Once upon a time… ,[object Object]
1995: NS Navigator 2.0 (Java + JavaScript)
1995: Confusion started
1996: MS IE 3.0 calls it JScript (not quite the same)
1997: ECMA-262, ECMAScript,[object Object]
Mispositioning
Design Errors
Bad Implementations
The Browser
Bad Books
Substandard Standard
JavaScript is a Functional Language,[object Object]
Solves real problems as a real language
Quite fancy sometimes
Not freaking Java (or C#), OK?,[object Object]
Objects: glorified containers
Prototypal inheritance
Textual delivery
Lambdas
Global variables tie it all,[object Object]
Advanced Javascript Undefined (undefined) Null (null) Default value for variables,  parameters,  and missing object properties var name = "Homer"; varhairColor = null; var city = "Springfield"; var state;
Advanced Javascript Number (IEEE-754, 64-bit, Double) Boolean (true, false) //integer literals varage = 26; vartemperature = -8; varpermission = 0775; //=509 varflags = 0x1c; //=28 //Double prec. literals varheight = 6.15; varfactor = 5.73e-1; //=.573 //NaN varwhat = "x"/3; //= NaN varfirstTime = true; varfound = false; String varfirstName = "Selma"; varlastName = 'Bouvier';
Advanced Javascript Array varnames = new Array(); names[0] = 'Steve'; names[1] = 'Chuck'; names[names.length] = 'Jeff'; names.push('Jason'); varnames = [ ]; //repeat as above… //or, preferred varnames = ['Steve', 'Chuck',    'Jeff', 'Jason'];
Advanced Javascript Date vartoday = new Date(); //milliseconds since 1/1/1970 vard = new Date(1234); //explicit var xmas = new Date(2008, 11, 25); //parsing, locale-dependent, avoid var xmas = new Date(Date.parse('12/25/2008'));
Advanced Javascript RegExp varpatt1 = new RegExp('d{2}$'); varpatt2 = /{2}$/; varpatt3 = new RegExp('d{2}$', 'gi'); varpatt4 = /{2}$/gi; alert(patt1.test('abc78')); //  true '12a78'.replace(/{2}$/, 'XYZ'); // '12aXYZ' 'a1b2c7d8e'.split(//); // ['a','b','c','d','e']
Advanced Javascript Function //normal declaration function play(chord) {     alert('playing ' + chord); }  //normal invocation play('Cm'); //  'playing Cm'
Advanced Javascript Function //functions are data as well function f1() {     alert('inside f1'); } var f2 = f1; function run( someFunc ){     someFunc(); } run( f2 ); //  'inside f1'
Advanced Javascript Function //functions are data as well function f1() {     alert('inside f1'); } var f2 = f1; function run( someFunc ){     someFunc(); } run( f2 ); //  'inside f1'
Advanced Javascript Function //functions don't need a name function run( someFunc ){     someFunc(); } run(function () {   alert('inside function'); }); //  'inside function'
Advanced Javascript Function //functions don't need a name function run( someFunc ){     someFunc(); } run( 	function () {     		alert('inside function'); 	} ); //  'inside function'
Advanced Javascript Function //parameter lists are optional function concat(){ var res = ''; for (var i=0; i<arguments.length; i++) {         res += arguments[i];     } return res; } alert( concat(123, 'abc', [7, 8, 9]) ); //  '123abc7,8,9'
Advanced Javascript Function //can be nested function prettyPrint(value, currency, rate){ function formatCurr(num) { returnnum + ' ' + currency;     }  function convert() { return rate * value;     } var converted = convert(value); var text = formatCurr(converted);     alert(text); } prettyPrint(10.5, 'EUR', 0.797); //  8.3685 EUR
Advanced Javascript Function //single-use, pinned functions (function (someParameter){ //do something     // … })(someArgument); Invocation!
Advanced Javascript Invocation and the problem with this function func(arg1, arg2){ return [this, arg1, arg2]; } func(123, 456); //  [window, 123, 456] var car = new Object(); car.start = func; car.start('now', 9); //  [car, 'now', 9] func.apply(car, ['p1', 'p2']);//  [car, 'p1', 'p2'] func.call(car, 'p1', 'p2'); //  [car, 'p1', 'p2']
Advanced Javascript Inner functions and this function calculateTotal(){ function getTax(){ return this.price * this.tax;     } returnthis.price + getTax() + this.shippingCost; } var order = new Object(); order.price = 10.25;  order.tax = 0.07; order.shippingCost = 5; order.getTotal = calculateTotal; order.getTotal();
Advanced Javascript Inner functions and this (the fix) function calculateTotal(){ var that = this; //  very common function getTax(){ return that.price * that.tax;     } returnthis.price + getTax() + this.shippingCost; } var order = new Object(); order.price = 10.25;  order.tax = 0.07; order.shippingCost = 5; order.getTotal = calculateTotal; order.getTotal();
Advanced Javascript Closures function createFuncArray() {     var funcs = [ ];     for (var n=0; n<10; n++) {         funcs[n] = function () {              alert('The number is ' + n);          };     } return funcs; } var allFunctions = createFuncArray(); var show = allFunctions[6]; show();//  Can you guess?
Advanced javascript Other Function-related gotchas ,[object Object]
No overloading, last one wins. Use default values.
arguments and this not passed to inner functions.,[object Object]
Advanced Javascript Object //factory function functioncreateGuitar(strings, make, model){ var guitar = new Object();     guitar.stringCount = strings;     guitar.make = make;     guitar.model = model;  return guitar; } var g = createGuitar(6, 'Gibson', 'Les Paul'); alert(g.make); //  'Gibson'
Advanced Javascript Object //Object literal notation var emptyObject = {}; var guitar = {     stringCount: 6,     make: 'Gibson',     model: 'Les Paul' }; //  don't forget the ';' //or var guitar = { 'stringCount': 6, 'make': 'Gibson', 'model': 'Les Paul' };
Advanced Javascript Object //notation for methods var guitar = {     stringCount: 6,     make: 'Gibson',     model: 'Les Paul', play: function (chord) {         alert(chord + ' from a ' + this.model);     } };  guitar.play('C#'); //  'C# from a Les Paul'
Advanced Javascript Object Wait, was that JSON? Not exactly. //JSON (see http://www.json.org/ ) var guitarJson = "{ " + " 'stringCount': 6, " + " 'make': 'Gibson'," +  " 'colors': [ 'black', 'white', 'red']," + " 'model': 'Les Paul'" +     "} ";  JSON is basically  a collection of name:value pairs. - name is a string literal - value can be: a string, a number, null, true, false,  an array, or another JSON object literal.
Advanced Javascript Object //constructor function functionGuitar(strings, make, model){ this.stringCount = strings; this.make = make; this.model = model; this.play = function (chord) {         alert(chord + ' from a ' + this.model);     }; } var g = new Guitar(6, 'Gibson', 'Les Paul'); g.play('C#'); //  'C# from a Les Paul'
Advanced Javascript Member access notations //good 'ole dot notation guitar.model = 'Gibson'; var p = guitar.price; //indexer notation guitar['model'] = 'Gibson'; guitar['play']('C#');
Advanced javascript What about document, window, etc? ,[object Object]

Más contenido relacionado

La actualidad más candente

Building Interpreters with PyPy
Building Interpreters with PyPyBuilding Interpreters with PyPy
Building Interpreters with PyPyDaniel Neuhäuser
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Nikita Popov
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightGiuseppe Arici
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightGiuseppe Arici
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Make Your Own Perl with Moops
Make Your Own Perl with MoopsMake Your Own Perl with Moops
Make Your Own Perl with MoopsMike Friedman
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
PHP applications/environments monitoring: APM & Pinba
PHP applications/environments monitoring: APM & PinbaPHP applications/environments monitoring: APM & Pinba
PHP applications/environments monitoring: APM & PinbaPatrick Allaert
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Nikita Popov
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)Mike Friedman
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11Uilian Ries
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctestmitnk
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 

La actualidad más candente (20)

Effective ES6
Effective ES6Effective ES6
Effective ES6
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Building Interpreters with PyPy
Building Interpreters with PyPyBuilding Interpreters with PyPy
Building Interpreters with PyPy
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
 
Make Your Own Perl with Moops
Make Your Own Perl with MoopsMake Your Own Perl with Moops
Make Your Own Perl with Moops
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
PHP applications/environments monitoring: APM & Pinba
PHP applications/environments monitoring: APM & PinbaPHP applications/environments monitoring: APM & Pinba
PHP applications/environments monitoring: APM & Pinba
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctest
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 

Destacado

General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptSpike Brehm
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScriptd0nn9n
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesSencha
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScriptYnon Perek
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 

Destacado (8)

General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScript
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other Puzzles
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 

Similar a JavaScript, Beyond the Curly Braces

JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraumpatricklee
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011Scalac
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into JavascriptMassimo Franciosa
 
What's new in Perl 5.10?
What's new in Perl 5.10?What's new in Perl 5.10?
What's new in Perl 5.10?acme
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Specs Presentation
Specs PresentationSpecs Presentation
Specs PresentationSynesso
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryTricode (part of Dept)
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jqueryciberglo
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Parkpointstechgeeks
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 

Similar a JavaScript, Beyond the Curly Braces (20)

JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
What's new in Perl 5.10?
What's new in Perl 5.10?What's new in Perl 5.10?
What's new in Perl 5.10?
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Specs Presentation
Specs PresentationSpecs Presentation
Specs Presentation
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Groovy
GroovyGroovy
Groovy
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j query
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 

Más de Chicago ALT.NET

Specflow: One Step closer to Executable Specifications
Specflow: One Step closer to Executable SpecificationsSpecflow: One Step closer to Executable Specifications
Specflow: One Step closer to Executable SpecificationsChicago ALT.NET
 
Dynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesDynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesChicago ALT.NET
 
CouchDB + .NET - Relax in Style
CouchDB + .NET - Relax in StyleCouchDB + .NET - Relax in Style
CouchDB + .NET - Relax in StyleChicago ALT.NET
 

Más de Chicago ALT.NET (6)

Poor Man's Kanban
Poor Man's KanbanPoor Man's Kanban
Poor Man's Kanban
 
Specflow: One Step closer to Executable Specifications
Specflow: One Step closer to Executable SpecificationsSpecflow: One Step closer to Executable Specifications
Specflow: One Step closer to Executable Specifications
 
CQRS In An Hour Or So
CQRS In An Hour Or SoCQRS In An Hour Or So
CQRS In An Hour Or So
 
Dynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesDynamic C# and a New World of Possibilities
Dynamic C# and a New World of Possibilities
 
CouchDB + .NET - Relax in Style
CouchDB + .NET - Relax in StyleCouchDB + .NET - Relax in Style
CouchDB + .NET - Relax in Style
 
Git Without Puns
Git Without PunsGit Without Puns
Git Without Puns
 

Último

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Último (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

JavaScript, Beyond the Curly Braces

  • 1. Beyond the Curly Braces Advanced JavaScript Sergio Pereira WI.NET Users Group – July 14th2009
  • 2. WHOIS About Sergio sergio@sergiopereira.com http://sergiopereira.com/blog @sergiopereira http://chicagoalt.net
  • 5. Advanced javascript BUT FIRST THE BASICS
  • 6.
  • 7. 1995: NS Navigator 2.0 (Java + JavaScript)
  • 9. 1996: MS IE 3.0 calls it JScript (not quite the same)
  • 10.
  • 17.
  • 18. Solves real problems as a real language
  • 20.
  • 25.
  • 26. Advanced Javascript Undefined (undefined) Null (null) Default value for variables, parameters, and missing object properties var name = "Homer"; varhairColor = null; var city = "Springfield"; var state;
  • 27. Advanced Javascript Number (IEEE-754, 64-bit, Double) Boolean (true, false) //integer literals varage = 26; vartemperature = -8; varpermission = 0775; //=509 varflags = 0x1c; //=28 //Double prec. literals varheight = 6.15; varfactor = 5.73e-1; //=.573 //NaN varwhat = "x"/3; //= NaN varfirstTime = true; varfound = false; String varfirstName = "Selma"; varlastName = 'Bouvier';
  • 28. Advanced Javascript Array varnames = new Array(); names[0] = 'Steve'; names[1] = 'Chuck'; names[names.length] = 'Jeff'; names.push('Jason'); varnames = [ ]; //repeat as above… //or, preferred varnames = ['Steve', 'Chuck', 'Jeff', 'Jason'];
  • 29. Advanced Javascript Date vartoday = new Date(); //milliseconds since 1/1/1970 vard = new Date(1234); //explicit var xmas = new Date(2008, 11, 25); //parsing, locale-dependent, avoid var xmas = new Date(Date.parse('12/25/2008'));
  • 30. Advanced Javascript RegExp varpatt1 = new RegExp('d{2}$'); varpatt2 = /{2}$/; varpatt3 = new RegExp('d{2}$', 'gi'); varpatt4 = /{2}$/gi; alert(patt1.test('abc78')); //  true '12a78'.replace(/{2}$/, 'XYZ'); // '12aXYZ' 'a1b2c7d8e'.split(//); // ['a','b','c','d','e']
  • 31. Advanced Javascript Function //normal declaration function play(chord) { alert('playing ' + chord); } //normal invocation play('Cm'); //  'playing Cm'
  • 32. Advanced Javascript Function //functions are data as well function f1() { alert('inside f1'); } var f2 = f1; function run( someFunc ){ someFunc(); } run( f2 ); //  'inside f1'
  • 33. Advanced Javascript Function //functions are data as well function f1() { alert('inside f1'); } var f2 = f1; function run( someFunc ){ someFunc(); } run( f2 ); //  'inside f1'
  • 34. Advanced Javascript Function //functions don't need a name function run( someFunc ){ someFunc(); } run(function () { alert('inside function'); }); //  'inside function'
  • 35. Advanced Javascript Function //functions don't need a name function run( someFunc ){ someFunc(); } run( function () { alert('inside function'); } ); //  'inside function'
  • 36. Advanced Javascript Function //parameter lists are optional function concat(){ var res = ''; for (var i=0; i<arguments.length; i++) { res += arguments[i]; } return res; } alert( concat(123, 'abc', [7, 8, 9]) ); //  '123abc7,8,9'
  • 37. Advanced Javascript Function //can be nested function prettyPrint(value, currency, rate){ function formatCurr(num) { returnnum + ' ' + currency; } function convert() { return rate * value; } var converted = convert(value); var text = formatCurr(converted); alert(text); } prettyPrint(10.5, 'EUR', 0.797); //  8.3685 EUR
  • 38. Advanced Javascript Function //single-use, pinned functions (function (someParameter){ //do something // … })(someArgument); Invocation!
  • 39. Advanced Javascript Invocation and the problem with this function func(arg1, arg2){ return [this, arg1, arg2]; } func(123, 456); //  [window, 123, 456] var car = new Object(); car.start = func; car.start('now', 9); //  [car, 'now', 9] func.apply(car, ['p1', 'p2']);//  [car, 'p1', 'p2'] func.call(car, 'p1', 'p2'); //  [car, 'p1', 'p2']
  • 40. Advanced Javascript Inner functions and this function calculateTotal(){ function getTax(){ return this.price * this.tax; } returnthis.price + getTax() + this.shippingCost; } var order = new Object(); order.price = 10.25; order.tax = 0.07; order.shippingCost = 5; order.getTotal = calculateTotal; order.getTotal();
  • 41. Advanced Javascript Inner functions and this (the fix) function calculateTotal(){ var that = this; //  very common function getTax(){ return that.price * that.tax; } returnthis.price + getTax() + this.shippingCost; } var order = new Object(); order.price = 10.25; order.tax = 0.07; order.shippingCost = 5; order.getTotal = calculateTotal; order.getTotal();
  • 42. Advanced Javascript Closures function createFuncArray() { var funcs = [ ]; for (var n=0; n<10; n++) { funcs[n] = function () { alert('The number is ' + n); }; } return funcs; } var allFunctions = createFuncArray(); var show = allFunctions[6]; show();//  Can you guess?
  • 43.
  • 44. No overloading, last one wins. Use default values.
  • 45.
  • 46. Advanced Javascript Object //factory function functioncreateGuitar(strings, make, model){ var guitar = new Object(); guitar.stringCount = strings; guitar.make = make; guitar.model = model; return guitar; } var g = createGuitar(6, 'Gibson', 'Les Paul'); alert(g.make); //  'Gibson'
  • 47. Advanced Javascript Object //Object literal notation var emptyObject = {}; var guitar = { stringCount: 6, make: 'Gibson', model: 'Les Paul' }; //  don't forget the ';' //or var guitar = { 'stringCount': 6, 'make': 'Gibson', 'model': 'Les Paul' };
  • 48. Advanced Javascript Object //notation for methods var guitar = { stringCount: 6, make: 'Gibson', model: 'Les Paul', play: function (chord) { alert(chord + ' from a ' + this.model); } }; guitar.play('C#'); //  'C# from a Les Paul'
  • 49. Advanced Javascript Object Wait, was that JSON? Not exactly. //JSON (see http://www.json.org/ ) var guitarJson = "{ " + " 'stringCount': 6, " + " 'make': 'Gibson'," + " 'colors': [ 'black', 'white', 'red']," + " 'model': 'Les Paul'" + "} "; JSON is basically a collection of name:value pairs. - name is a string literal - value can be: a string, a number, null, true, false, an array, or another JSON object literal.
  • 50. Advanced Javascript Object //constructor function functionGuitar(strings, make, model){ this.stringCount = strings; this.make = make; this.model = model; this.play = function (chord) { alert(chord + ' from a ' + this.model); }; } var g = new Guitar(6, 'Gibson', 'Les Paul'); g.play('C#'); //  'C# from a Les Paul'
  • 51. Advanced Javascript Member access notations //good 'ole dot notation guitar.model = 'Gibson'; var p = guitar.price; //indexer notation guitar['model'] = 'Gibson'; guitar['play']('C#');
  • 52.
  • 53. Part of the DOM.
  • 54. Provided by the hosting environment.
  • 55.
  • 56. Not even part of the DOM.
  • 57.
  • 58. Convention: start variables and functions with lower case.
  • 60.
  • 61.
  • 64.
  • 65. Advanced Javascript Inheritance in JavaScript generic var generic = { make: 'none', price :0 }; var guitar = object( generic ); guitar.model = 'Les Paul'; guitar.price = 1200; guitar generic.year = 2001; generic.model = 'n/a'; alert(guitar.model); //  Les Paul alert(guitar.year); //  2001
  • 66. Advanced Javascript Inheritance in JavaScript Every object inherits from Object.prototype var obj = new Object(); //same as var obj = object( Object.prototype ); var d = new Date(1000); //behind the scenes: var newObj = object( Date.prototype ); d = Date.apply( newObj, [1000] ); if (d == null ) d = newObj;
  • 67. Advanced Javascript Inheritance in JavaScript Our constructors also have a prototype functionGuitar(strings, make, model){ this.stringCount = strings; this.make = make; this.model = model; } Guitar.prototype.play = function (chord) { alert(chord + ' from a ' + this.model); };
  • 68. Advanced Javascript Inheritance in JavaScript Object.prototype Guitar.prototype myGuitarInstance
  • 69. Advanced Javascript Inheritance in JavaScript Oldest trick in JavaScript inheritance String.prototype.trim = function () { return this.replace( /^*(*(++)*)*$/, "$1"); }; var text = ' some user-entered value '; alert(text); //  'some user-entered value'
  • 70. Advanced Javascript I lied There's no object() function in Javascript. But let me give you one. function object(o) { function F() {} F.prototype = o; returnnew F(); }
  • 71. Advanced Javascript JavaScript Idioms: Truthy & Falsy //Falsy values var f[1]= false;// D'oh! var f[2] = null; var f[3] = undefined; var f[4] = 0; var f[5] = ""; var f[6] = NaN; if( f[X] ){ // never gets here } //Truthy values var t[1] = true; var t[2] = new Object(); var t[3] = "1"; var t[4] = "0"; //  !! var t[5] = "false";//  !! if( t[X] ){ // gets here always }
  • 72. Advanced Javascript JavaScript Idioms: || Default operator //returns the first Truthy or last operand. //e.g.: overriding missing arguments var sortOrder; if (arg) { sortOrder = arg; } else { sortOrder = 'Name ASC'; } //same as var sortOrder = arg || 'Name ASC';
  • 73. Advanced Javascript JavaScript Idioms: && Guard operator //returns the first Falsy or last operand. // e.g.: avoiding null reference errors var obj2; if (obj1) { obj2 = obj1.prop; } else { obj2 = obj1; } //same as var obj2 = obj1 && obj1.prop;
  • 74. Advanced Javascript JavaScript Idioms: === and !== if (0 == "") { alert('Hey, I did not expect to see this.');//displayed } if (0 === "") { alert('This will not be displayed.');//not displayed } if (1 != true) { alert('Hey, I expected to see this.'); //not displayed } if (1 !== true) { alert('This will be displayed.');//displayed }
  • 75. Advanced Javascript JavaScript Idioms: Namespaces var ACME = { version: '7.1', formatCurrency: function(num){ /* … */ }, //… }; ACME.Ajax = { ajaxifyForm: function(formId){ /* … */ }, showError: function(){ /* … */ }, //… }; ACME.Ajax.ajaxifyForm('myForm');
  • 76. Advanced javascript Coding convention: Always use curly braces if (something) doSomething(); doSomethingElse(); if (something){ doSomething(); } doSomethingElse();
  • 77. Advanced javascript Coding convention: Always end lines with punctuation return tax + shipping + price; var amount = tax + shipping + price; var amount = tax + shipping + price; Parsed as return; tax + shipping + price; return tax + shipping + price;
  • 78.
  • 79. Tend to clobber each other.
  • 81.
  • 82. Advanced javascript Coding convention: Declare variables at the top of function function f1(){ var a, b, c; a = getA(); if (a) { b = calcB(a); } else { c = getC(); b = calcB(c); } }
  • 83. Advanced javascript Coding convention: Do not use assignments as expressions if ( flag = getFlag() ) { alert(flag); } //prefer: var flag = getFlag(); if (flag) { alert(flag); }
  • 85.
  • 86. JavaScript: The Definitive Guide by David Flanagan.
  • 87. Videos: Search for Douglas Crockford.
  • 88. Shameless plug: my blog, JavaScript category.sergio@sergiopereira.com http://sergiopereira.com/blog @sergiopereira http://chicagoalt.net

Notas del editor

  1. In trivia we will give an abridged version of JS history and where it stands todayDrive by shooting: just to make sure we mention the basic data types we deal with all the time. The one item that can be surprisingly different and longer than you might expect are the functions. We will spend a little bit of time talking about them.As the title of the presentation suggests, it can be easy to look at JS syntax and its name and try to map everything else to C#, Java, C, etc. We will see that this is a big mistake and we will point out very important differences.In idiomatic JS we will see what proficient JS looks likeWe will take some time to explain how object creation and inheritance works in JS. If you haven’t read about it before it might just be completely different from anything you saw.JS lives in a very hostile environment. In coding conventions and pitfalls we will learn tidbits of advice that can spare you from a lot of grief.Finally, all the above has just been preparation to really get to the more practical goal. Understanding jQuery and using it to write less and better JS code. We will see that jQuery has good documentation but it can be hard to read if you’re not up to speed with some of the previous topics. Event the jQuery source code is very readable once you get comfortable with idiomatic JS.
  2. In trivia we will give an abridged version of JS history and where it stands todayDrive by shooting: just to make sure we mention the basic data types we deal with all the time. The one item that can be surprisingly different and longer than you might expect are the functions. We will spend a little bit of time talking about them.As the title of the presentation suggests, it can be easy to look at JS syntax and its name and try to map everything else to C#, Java, C, etc. We will see that this is a big mistake and we will point out very important differences.In idiomatic JS we will see what proficient JS looks likeWe will take some time to explain how object creation and inheritance works in JS. If you haven’t read about it before it might just be completely different from anything you saw.JS lives in a very hostile environment. In coding conventions and pitfalls we will learn tidbits of advice that can spare you from a lot of grief.Finally, all the above has just been preparation to really get to the more practical goal. Understanding jQuery and using it to write less and better JS code. We will see that jQuery has good documentation but it can be hard to read if you’re not up to speed with some of the previous topics. Event the jQuery source code is very readable once you get comfortable with idiomatic JS.