All of JavascriptGeorge MauerRate Me On SpeakerRatehttp://tinyurl.com/0811-brdnug
Owner of Humble Pi ConsultingCurrent senior developer at SurgeFormer Senior Software Developer at EPS SoftwareMember - VirtualBrownBag, VirtualAltNet, gnocode, PhpNOLA, RubyBayouImprov and sketch Comedy with www.NolaComedy.comhttp://georgemauer.net/blog@togakangaroogmauer@gmail.comAbout Me
Join Us For the Virtual Brown Bag12:00 PM CST Thursdays on Livemeetingwww.virtualbrownbag.comTwitter: @virtualbrownbag
Javascript is….Actually called ECMAScriptWhy Javascript?Most popular languageLightweight conceptuallyIt will make your C# a lot betterAll the cool kids are doing it
I want it!You got it…in your browserUse developer add-onsChrome (Ctrl+Shift+J)IE (F12)FirefoxWeb Development HelperFirebugEnable Console and we’re interactive
In the browser Javascript interacts with the Document Object Model Browser’s interpretation of HTMLI wanna…use it?
Your script in the page<script> tagInlineOr LinkAnother HTTP request is made and the script file is downloadedCachedOrder and download timing mattersWords!MinificationBundlingCDNsGlobal scopeYou have to be careful of the sourceFor now let’s use console.log(…)
Syntax – Javascript is NOT JavaNo type declarationvarsomeInt = 123console.log(someInt)Strings use “ or ‘Yes, there are exceptions and try…catch blocksdo…while loopsif and switch statementsNo, we will not talk about themExcept the for loopThere is no function to evaluate stringsThere is nothing to: eval(“alert(‘javascript!’)”);(There totally is, but shhh…)Semi-colons are optional…ish
Control StructuresYes, there are exceptions and try…catch blocksdo…while loopsif and switch statementsNo, we will not talk about themExcept the for loopThere is no function to varsomeString = “alert(‘javascript!’)”;eval(someString);(There totally is, but shhh…)Semi-colons are optional…ish
Concept #1 – Objects as HashesNo such thing as classes, just objectsSo there’s just anonymous objectsObject Literal:Comma-separated, Colon denoted hashTrailing commas not allowedNothing is immutableYou can add propertiesFunctions too!var person = {  name: "Brian May",  occupation: "Mucisian",  who: function() {    console.log(this.name+": I used to be in Queen")  }};person.phD = "Astronomy";person.playMusic = function() {  console.log("Is this the real life?");}
Concept #1 – Objects as HashesObjects ARE Hashes/DictionariesmyObject.propertyName == myObject[“propertyName”]Use console.dir() to explore objectsArraysComma separated, Square bracketsElements in array can be of any typeArrays are objects
FunctionsUse the function keywordNo type information on parametersAll functions return something (though it might be undefined)When invoking parameters are always optionalDo you care?function youLike(name) {  if(typeof name === 'undefined') {console.error("I don’t know who to like");    return;  }  return 'I like ' + name;}console.log(youLike('fred'))  // I like fredconsole.log(youLike())// I don’t know who to like     // undefined
Concept #2 – First Class FunctionsFunctions are objectsCan be stored in variablesOr parameters to other functionsFunctions can have properties! They are just objects that can be invoked.So how are they not objects?Functions are invokableThat’s it (for now)
Function ClosuresSimilar to lambdas in LINQGreat for helper functionsIt works exactly how you instinctually think it shouldNest as many as you wantNot visible outside of functionsAnonymous functions can be assigned to variablesvartellHistory = function () {var who;  function warBrokeOut() {    console.log('war broke out');    console.log('lots of '+who+' died');  }  who = 'Cavemen';  console.log(who+' invented axes');warBrokeOut();    who = 'Babylonians';  console.log(who+'  invented laws');warBrokeOut();  who = 'Greeks';  console.log( who+' invented  democracy');warBrokeOut();warBrokeOut();}
Concept #3 – Loose TypingReally there are typesStrings, Integers, floatsBut you can write whatever you wantJS has it covered: 99% of the time it just works
Concept #3 – Loose TypingLoose means coercions on the spotThis can get wonky1+2+"3" == "33“"1"+2+3 == "33“2==false;=== operator will prevent coercion and is recommendIt’s weird but if you know what you’re doing…
Concept #4 – ClosuresAddresses one of the biggest problems – global scopeFunctions can be nested inside each otherScope works exactly as you instinctively think it would
Concept #4 – ClosuresSelf-executing functions solve global scope issuevarsomeFunc = function() { //stuff}someFunc();//shorten to(function() { //stuff})
Public? Private? Static?We got youConcept #4 – ClosuresLots of variations on this module pattern
Concept #5 – PrototypesJavascript is object-oriented and has no classes!Prototype inheritanceSimpler – each object has a prototype objectFlexible – can mimic class inheritance and moreRemember: Every object is a hashPlus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)Q: Do you have a cupOfSugar?Yes I do (object has cupOfSugar in the hash)No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])No I don’t (object does not and [[prototype]] is null)Can be used to emulate Class InheritanceEnables duck-typing, class-wide dynamicism, more!I recommend a style where you do not use this often
Concept #5 – Prototypes: newJavascript has a ‘new’ keywordVery different from C# newYou don’t really need to use ‘new’ for OO in JavascriptWhat does ‘new do’?All functions have a not null prototype propertycreates a function with the [[prototype]] set to the constructor function’s prototype property You can enforce ‘new’Anti-intuitively works on functions but not objectsNewer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)Constructor functions denoted via convention.Capitalize constructor functionscamelCase non-constructor functions
What is JSON?A subset of Javascript for transporting dataFunctionally equivalent to XMLBut way more succinctLingua franca for ajax data-exchangeTwitter.com – look at the dev tools network tabJSON is parsed with JSON parser, not eval’ed!
Cross-Domain AjaxThe probleMI go to amazon.com and log inMy browser stores information (cookies) to identify me to AmazonI then go to evilpage.comUses ajax to contact amazon.comMy browser thinking the amazon session is still on sends my AmazonAmazon sends back secret information to evilpage.com!
Same Origin PolicyBrowsers limit your ability to request resources across domainsIn general you can request and use across domainsDisplay imagesRun scriptsDisplay iframeYou cannot have programmatic access to these resourcesAnalyze images from other domains in JSGet arbitrary scripts as a stringInspect cross-domain iframe’s DOMResources for understanding:Eric Law on the policyPhil Haackon a simple exploit with this
Cross-Domain SolutionsDisplay data from other domains in iframesCannot use that dataDo all queries to other domains server sideCan much better control cachingProtected better against format changesTakes up your bandwithJSONPService returns and executes:Cross-domain script execution is okAssumes you have a global method called myMethodEvaluated, not parsed like JSONDangerous – if the site is compromised it can inject any script!Always think twice when sending secure data!myMethod({name: ‘George’})
Odds and Ends – JasmineTesting is even more important in dynamic languagesNo compiler to catch errorsEasy to screw up global stateJasmine is a lightweight testing frameworkBased on ruby’s rspecReally simple and easy to learnSample specs from gim.ShannonGame
Odds and Ends – CoffeescriptLightweight Javascript compiler that removes the suckGets rid of the function keywordSignificant whitespace and no need for parensPostfix conditions (number = 42 if answer== true)Splats and object decompositionComprehensionsEasier inheritance setupsTry it outReverse compiler is a great learning toolHeavily influencing the future of Javascript (Harmony)
Why Libraries?Mismatches in browser implementationsThe standard DOM interface is awfulInternet Explorer <8 sucksUnforeseen standards adopted (ie. CSS)Standardize these awayjQuery, prototype, mootools, ext-js, yui, othersJsfiddle.net - Try them out
Some ResourcesDouglas Crockford’sJavaScript the Good PartsVideoMozilla Developer Center – by far the best documentationWhen searching for javascript help, add on “MDC”Introduction to javascript from MDCJavascript OOJavascript GardenFascinating Elegant Code beginner seriesHidden Features of Javascript on StackOverflowjsfiddle.net – In-browser js prototyping sandbox complete with syntax highlighting, formatting, javascript libraries inclusion, and code pasting for sharingGoogle Closure – how not to write javascriptThe console object APIJSLint – Douglas Crockford’s syntax checker.Best explanation of the new keyword.Paul Irish Learns from jQuery source, and morejQuery API Reference Rate Me on SpeakerRate: http://tinyurl.com/0811-brdnugwww.virtualbrownbag.com
That Web 2.0 thing? Yeah, that.Let’s talk about AJAX
HTTP ModelProblems Refresh is uglyUnnecessary bandwithThe operation is user triggeredSolutionUse javascript to fetch data and update the page when it is returnedjQuery has some great helpers for this. Example
The Global ScopeYou don’t have to use varIf you don’t, assignment bubbles up like you would thinkAll the way to the global window object!So always use varIsolate yourself from global scope with self-executing functionsExplanation of variables, properties, scopesfunction doStuff() {varfirstName = 'Fred';  function changeName() {firstName = 'Jim';lastName = 'Halpern';  } changeName();}doStuff();firstName; // undefinedlastName; // Halpern – huh?window.lastName;  // Halpern – uh oh!(function() {  …doWhatever…})();
More Javascript - PrototypesJavascript is object-oriented and has no classes!Prototype inheritanceSimpler – each object has a prototype objectFlexible – can mimic class inheritance and moreRemember: Every object is a hashPlus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)Q: Do you have a cupOfSugar?Yes I do (object has cupOfSugar in the hash)No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])No I don’t (object does not and [[prototype]] is null)Can be used to emulate Class InheritanceEnables duck-typing, class-wide dynamicism, more!
What’s new?Javascript has a ‘new’ keywoadBut no traditional inheritanceYou don’t really need to use ‘new’ for OO in JavascriptWhat does ‘new do’?All functions have a not null prototype propertycreates a function with the [[prototype]] set to the constructor function’s prototype property You can enforce ‘new’Anti-intuitively works on functions but not objectsNewer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)Constructor functions denoted via convention.Capitalize constructor functionscamelCase non-constructor functionsfunction createPerson(name, age) {  return {    name: name,    age: age,toString: function() { return this.name + " is " + this.age + " years old“;  }  }}var bob= createPerson("bob", 39);varsal = createPerson("sal", 22);-------------------------------------------------------------var Cat = function(catName) {this.catName = catName;};Cat.prototype.meow = function() {	console.log(this.catName+" says meow");}var mittens = new Cat("Mittens");var whiskers = new Cat("Whiskers");
What’s this?Javascript has the ‘this’ keywordUse it to refer to the current scope / contextSort ofLots of caveatsIt usually works how you think but double checkCan also be substituted with function’s call() or apply() methodsCan be useful for method reuse
Odds and Ends – RegExTraditionally more important in dynamic languagesTwo ways to createvar r1 = /^a+./;var r2 = new RegEx("^a+.");r1.exec(str); // Returns array of matchesr1.test(str); // Returns true if there is a matchstr.match(r1); //Returns an array of Matchesstr.search(r1); //Returns idx if there is a match or -1str.replace(r1); //Returns string with regex replacedstr.split(r1); //Returns an array of substrings
Odds and Ends – XSSCross Site Scripting – someone causes their Javascript to run on your site for other usersDangerous for: Comments / forums / twitter feeds where you can post things other people can seeSearch areas or GET urls where long user submissions can be embedded in a linkExamples of simple XSS attacksHow to prevent it:Ensure all user input reflected back is Html encodedDon’t place anything from GET requests on the pageBe aware and think!
Javascript Weirdness - HoistingVariable declarations are moved to the top of the scopeFunction declarations are created and declared in the same stepAt the top of the scopeFunction assignments are similar to variable declarationsConsider declaring all variables in scope with one var statementvar bob, joe, jill;var num = 56;function calc() {  console.log(num);var num = 12;  console.log(num);}function calc_isReally() {var num;  console.log(num);  num = 12;  console.log(num);}
Javascript Weirdnessfor..in loops through all keys on hash / properties on objectIncluding those in the prototype chain which isn’t very helpfulUse hasOwnProperty() if this is not desired behaviorDon’t use this to enumerate Arraysfor loop – similar to for loop in c# or c++Use it to loop through arraysBut remember Array.length is a calculated property!for(vari=0; i<arr.length; ++i) { }  Bad!for(vari=0, len=arr.length; i<len; ++i) { }  OK
Javascript WeirdnessString DualityNative and object representations of stringstypeof comparison won’t always workDo you really need to check type?Really?parseInt(), parseFloat() are not so simpleWhat should parseInt("010") return?Read the MDC docs when using built-in functions (there aren’t that many)

All of javascript

  • 1.
    All of JavascriptGeorgeMauerRate Me On SpeakerRatehttp://tinyurl.com/0811-brdnug
  • 2.
    Owner of HumblePi ConsultingCurrent senior developer at SurgeFormer Senior Software Developer at EPS SoftwareMember - VirtualBrownBag, VirtualAltNet, gnocode, PhpNOLA, RubyBayouImprov and sketch Comedy with www.NolaComedy.comhttp://georgemauer.net/blog@togakangaroogmauer@gmail.comAbout Me
  • 3.
    Join Us Forthe Virtual Brown Bag12:00 PM CST Thursdays on Livemeetingwww.virtualbrownbag.comTwitter: @virtualbrownbag
  • 4.
    Javascript is….Actually calledECMAScriptWhy Javascript?Most popular languageLightweight conceptuallyIt will make your C# a lot betterAll the cool kids are doing it
  • 5.
    I want it!Yougot it…in your browserUse developer add-onsChrome (Ctrl+Shift+J)IE (F12)FirefoxWeb Development HelperFirebugEnable Console and we’re interactive
  • 6.
    In the browserJavascript interacts with the Document Object Model Browser’s interpretation of HTMLI wanna…use it?
  • 7.
    Your script inthe page<script> tagInlineOr LinkAnother HTTP request is made and the script file is downloadedCachedOrder and download timing mattersWords!MinificationBundlingCDNsGlobal scopeYou have to be careful of the sourceFor now let’s use console.log(…)
  • 8.
    Syntax – Javascriptis NOT JavaNo type declarationvarsomeInt = 123console.log(someInt)Strings use “ or ‘Yes, there are exceptions and try…catch blocksdo…while loopsif and switch statementsNo, we will not talk about themExcept the for loopThere is no function to evaluate stringsThere is nothing to: eval(“alert(‘javascript!’)”);(There totally is, but shhh…)Semi-colons are optional…ish
  • 9.
    Control StructuresYes, thereare exceptions and try…catch blocksdo…while loopsif and switch statementsNo, we will not talk about themExcept the for loopThere is no function to varsomeString = “alert(‘javascript!’)”;eval(someString);(There totally is, but shhh…)Semi-colons are optional…ish
  • 10.
    Concept #1 –Objects as HashesNo such thing as classes, just objectsSo there’s just anonymous objectsObject Literal:Comma-separated, Colon denoted hashTrailing commas not allowedNothing is immutableYou can add propertiesFunctions too!var person = { name: "Brian May", occupation: "Mucisian", who: function() { console.log(this.name+": I used to be in Queen") }};person.phD = "Astronomy";person.playMusic = function() { console.log("Is this the real life?");}
  • 11.
    Concept #1 –Objects as HashesObjects ARE Hashes/DictionariesmyObject.propertyName == myObject[“propertyName”]Use console.dir() to explore objectsArraysComma separated, Square bracketsElements in array can be of any typeArrays are objects
  • 12.
    FunctionsUse the functionkeywordNo type information on parametersAll functions return something (though it might be undefined)When invoking parameters are always optionalDo you care?function youLike(name) { if(typeof name === 'undefined') {console.error("I don’t know who to like"); return; } return 'I like ' + name;}console.log(youLike('fred')) // I like fredconsole.log(youLike())// I don’t know who to like // undefined
  • 13.
    Concept #2 –First Class FunctionsFunctions are objectsCan be stored in variablesOr parameters to other functionsFunctions can have properties! They are just objects that can be invoked.So how are they not objects?Functions are invokableThat’s it (for now)
  • 14.
    Function ClosuresSimilar tolambdas in LINQGreat for helper functionsIt works exactly how you instinctually think it shouldNest as many as you wantNot visible outside of functionsAnonymous functions can be assigned to variablesvartellHistory = function () {var who; function warBrokeOut() { console.log('war broke out'); console.log('lots of '+who+' died'); } who = 'Cavemen'; console.log(who+' invented axes');warBrokeOut(); who = 'Babylonians'; console.log(who+' invented laws');warBrokeOut(); who = 'Greeks'; console.log( who+' invented democracy');warBrokeOut();warBrokeOut();}
  • 15.
    Concept #3 –Loose TypingReally there are typesStrings, Integers, floatsBut you can write whatever you wantJS has it covered: 99% of the time it just works
  • 16.
    Concept #3 –Loose TypingLoose means coercions on the spotThis can get wonky1+2+"3" == "33“"1"+2+3 == "33“2==false;=== operator will prevent coercion and is recommendIt’s weird but if you know what you’re doing…
  • 17.
    Concept #4 –ClosuresAddresses one of the biggest problems – global scopeFunctions can be nested inside each otherScope works exactly as you instinctively think it would
  • 18.
    Concept #4 –ClosuresSelf-executing functions solve global scope issuevarsomeFunc = function() { //stuff}someFunc();//shorten to(function() { //stuff})
  • 19.
    Public? Private? Static?Wegot youConcept #4 – ClosuresLots of variations on this module pattern
  • 20.
    Concept #5 –PrototypesJavascript is object-oriented and has no classes!Prototype inheritanceSimpler – each object has a prototype objectFlexible – can mimic class inheritance and moreRemember: Every object is a hashPlus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)Q: Do you have a cupOfSugar?Yes I do (object has cupOfSugar in the hash)No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])No I don’t (object does not and [[prototype]] is null)Can be used to emulate Class InheritanceEnables duck-typing, class-wide dynamicism, more!I recommend a style where you do not use this often
  • 21.
    Concept #5 –Prototypes: newJavascript has a ‘new’ keywordVery different from C# newYou don’t really need to use ‘new’ for OO in JavascriptWhat does ‘new do’?All functions have a not null prototype propertycreates a function with the [[prototype]] set to the constructor function’s prototype property You can enforce ‘new’Anti-intuitively works on functions but not objectsNewer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)Constructor functions denoted via convention.Capitalize constructor functionscamelCase non-constructor functions
  • 22.
    What is JSON?Asubset of Javascript for transporting dataFunctionally equivalent to XMLBut way more succinctLingua franca for ajax data-exchangeTwitter.com – look at the dev tools network tabJSON is parsed with JSON parser, not eval’ed!
  • 23.
    Cross-Domain AjaxThe probleMIgo to amazon.com and log inMy browser stores information (cookies) to identify me to AmazonI then go to evilpage.comUses ajax to contact amazon.comMy browser thinking the amazon session is still on sends my AmazonAmazon sends back secret information to evilpage.com!
  • 24.
    Same Origin PolicyBrowserslimit your ability to request resources across domainsIn general you can request and use across domainsDisplay imagesRun scriptsDisplay iframeYou cannot have programmatic access to these resourcesAnalyze images from other domains in JSGet arbitrary scripts as a stringInspect cross-domain iframe’s DOMResources for understanding:Eric Law on the policyPhil Haackon a simple exploit with this
  • 25.
    Cross-Domain SolutionsDisplay datafrom other domains in iframesCannot use that dataDo all queries to other domains server sideCan much better control cachingProtected better against format changesTakes up your bandwithJSONPService returns and executes:Cross-domain script execution is okAssumes you have a global method called myMethodEvaluated, not parsed like JSONDangerous – if the site is compromised it can inject any script!Always think twice when sending secure data!myMethod({name: ‘George’})
  • 26.
    Odds and Ends– JasmineTesting is even more important in dynamic languagesNo compiler to catch errorsEasy to screw up global stateJasmine is a lightweight testing frameworkBased on ruby’s rspecReally simple and easy to learnSample specs from gim.ShannonGame
  • 27.
    Odds and Ends– CoffeescriptLightweight Javascript compiler that removes the suckGets rid of the function keywordSignificant whitespace and no need for parensPostfix conditions (number = 42 if answer== true)Splats and object decompositionComprehensionsEasier inheritance setupsTry it outReverse compiler is a great learning toolHeavily influencing the future of Javascript (Harmony)
  • 28.
    Why Libraries?Mismatches inbrowser implementationsThe standard DOM interface is awfulInternet Explorer <8 sucksUnforeseen standards adopted (ie. CSS)Standardize these awayjQuery, prototype, mootools, ext-js, yui, othersJsfiddle.net - Try them out
  • 29.
    Some ResourcesDouglas Crockford’sJavaScriptthe Good PartsVideoMozilla Developer Center – by far the best documentationWhen searching for javascript help, add on “MDC”Introduction to javascript from MDCJavascript OOJavascript GardenFascinating Elegant Code beginner seriesHidden Features of Javascript on StackOverflowjsfiddle.net – In-browser js prototyping sandbox complete with syntax highlighting, formatting, javascript libraries inclusion, and code pasting for sharingGoogle Closure – how not to write javascriptThe console object APIJSLint – Douglas Crockford’s syntax checker.Best explanation of the new keyword.Paul Irish Learns from jQuery source, and morejQuery API Reference Rate Me on SpeakerRate: http://tinyurl.com/0811-brdnugwww.virtualbrownbag.com
  • 31.
    That Web 2.0thing? Yeah, that.Let’s talk about AJAX
  • 32.
    HTTP ModelProblems Refreshis uglyUnnecessary bandwithThe operation is user triggeredSolutionUse javascript to fetch data and update the page when it is returnedjQuery has some great helpers for this. Example
  • 33.
    The Global ScopeYoudon’t have to use varIf you don’t, assignment bubbles up like you would thinkAll the way to the global window object!So always use varIsolate yourself from global scope with self-executing functionsExplanation of variables, properties, scopesfunction doStuff() {varfirstName = 'Fred'; function changeName() {firstName = 'Jim';lastName = 'Halpern'; } changeName();}doStuff();firstName; // undefinedlastName; // Halpern – huh?window.lastName; // Halpern – uh oh!(function() { …doWhatever…})();
  • 34.
    More Javascript -PrototypesJavascript is object-oriented and has no classes!Prototype inheritanceSimpler – each object has a prototype objectFlexible – can mimic class inheritance and moreRemember: Every object is a hashPlus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)Q: Do you have a cupOfSugar?Yes I do (object has cupOfSugar in the hash)No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])No I don’t (object does not and [[prototype]] is null)Can be used to emulate Class InheritanceEnables duck-typing, class-wide dynamicism, more!
  • 35.
    What’s new?Javascript hasa ‘new’ keywoadBut no traditional inheritanceYou don’t really need to use ‘new’ for OO in JavascriptWhat does ‘new do’?All functions have a not null prototype propertycreates a function with the [[prototype]] set to the constructor function’s prototype property You can enforce ‘new’Anti-intuitively works on functions but not objectsNewer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)Constructor functions denoted via convention.Capitalize constructor functionscamelCase non-constructor functionsfunction createPerson(name, age) { return { name: name, age: age,toString: function() { return this.name + " is " + this.age + " years old“; } }}var bob= createPerson("bob", 39);varsal = createPerson("sal", 22);-------------------------------------------------------------var Cat = function(catName) {this.catName = catName;};Cat.prototype.meow = function() { console.log(this.catName+" says meow");}var mittens = new Cat("Mittens");var whiskers = new Cat("Whiskers");
  • 36.
    What’s this?Javascript hasthe ‘this’ keywordUse it to refer to the current scope / contextSort ofLots of caveatsIt usually works how you think but double checkCan also be substituted with function’s call() or apply() methodsCan be useful for method reuse
  • 37.
    Odds and Ends– RegExTraditionally more important in dynamic languagesTwo ways to createvar r1 = /^a+./;var r2 = new RegEx("^a+.");r1.exec(str); // Returns array of matchesr1.test(str); // Returns true if there is a matchstr.match(r1); //Returns an array of Matchesstr.search(r1); //Returns idx if there is a match or -1str.replace(r1); //Returns string with regex replacedstr.split(r1); //Returns an array of substrings
  • 38.
    Odds and Ends– XSSCross Site Scripting – someone causes their Javascript to run on your site for other usersDangerous for: Comments / forums / twitter feeds where you can post things other people can seeSearch areas or GET urls where long user submissions can be embedded in a linkExamples of simple XSS attacksHow to prevent it:Ensure all user input reflected back is Html encodedDon’t place anything from GET requests on the pageBe aware and think!
  • 39.
    Javascript Weirdness -HoistingVariable declarations are moved to the top of the scopeFunction declarations are created and declared in the same stepAt the top of the scopeFunction assignments are similar to variable declarationsConsider declaring all variables in scope with one var statementvar bob, joe, jill;var num = 56;function calc() { console.log(num);var num = 12; console.log(num);}function calc_isReally() {var num; console.log(num); num = 12; console.log(num);}
  • 40.
    Javascript Weirdnessfor..in loopsthrough all keys on hash / properties on objectIncluding those in the prototype chain which isn’t very helpfulUse hasOwnProperty() if this is not desired behaviorDon’t use this to enumerate Arraysfor loop – similar to for loop in c# or c++Use it to loop through arraysBut remember Array.length is a calculated property!for(vari=0; i<arr.length; ++i) { }  Bad!for(vari=0, len=arr.length; i<len; ++i) { }  OK
  • 41.
    Javascript WeirdnessString DualityNativeand object representations of stringstypeof comparison won’t always workDo you really need to check type?Really?parseInt(), parseFloat() are not so simpleWhat should parseInt("010") return?Read the MDC docs when using built-in functions (there aren’t that many)