JavaScript as Development Platform
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

JavaScript as Development Platform

  • 1,456 views
Uploaded on

JavaScript as Development platform gives overview of JavaScript as Runtime and Programming Language. From this presentation you can find out more about advanced language features and usage patterns.

JavaScript as Development platform gives overview of JavaScript as Runtime and Programming Language. From this presentation you can find out more about advanced language features and usage patterns.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,456
On Slideshare
1,439
From Embeds
17
Number of Embeds
3

Actions

Shares
Downloads
36
Comments
0
Likes
3

Embeds 17

http://www.linkedin.com 10
https://www.linkedin.com 4
https://twitter.com 3

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. javascriptas development platform
  • 2. CONVENTIONS SOURCE CODE BAD PRACTICE LEGACY CODEvar global = 10; function factorial(x) { if (x <= 1) {function foo() { return 1; global++; }} return x * arguments.callee(x - 1); } GOOD PRACTICE(function () { var local = 10; CODE SNIPPET function foo() { function foo() { local++; console.log(‘foo’); } }})();
  • 3. WHAT IS javascript The world`s most misunderstood programming language
  • 4. SOURCES OF CONFUSION JAVA PREFIXCompletely independent from JavaHas syntax similarities
  • 5. SOURCES OF CONFUSION SCRIPT POSTFIXDoesn’t mean that JS isn`t realprogramming languageFull-fledged Object Oriented language
  • 6. SOURCES OF CONFUSION WEAK LEARNING SOURCESStandard has complicated structure makes it hard toread and understandAlmost all books are universally badInternet full of bad advices and practices
  • 7. LEARNING SOURCESBOOKS Javascript: the definitive guide Javascript: the GOOD parts
  • 8. WHAT IS Javascript A scripting language designed as lightweight alternative to Java for Web
  • 9. history1992 James Gosling at Sun Microsystems has been working on superior language to C++ called Oak
  • 10. history1992 Microsoft released Windows 3.1 and preview of Microsoft Windows NT for developers
  • 11. history1995 Oak has failed as a language for interactive television and has been repurposed for Web. At this time language has been renamed to Java.
  • 12. history1995 Sun Microsystems officially announced HotJava browser with support of Java-applets.
  • 13. history1995 Web becomes hot and Microsoft ships Internet Explorer 1.0 and Internet Explorer 2.0 few month later
  • 14. history1995 Brendan Eich at Netscape Communication Corporation begun working on lightweight and simple alternative to Java for Web browser
  • 15. history1995 Later on Netscape released Netscape Navigator 2.0 with support of LiveScript and Java-applets
  • 16. history1995 Anticipated by opportunity to free Web from Microsoft, Sun and Netscape formed the alliance As the result LiveScript has been renamed to JavaScript
  • 17. history1996 Microsoft reverse-engineered JavaScript and named it JScript to avoid trademark issues with Sun
  • 18. history1996 Microsoft released Internet Explorer 3 with support of JScript
  • 19. history1996 To prevent Microsoft from mutating the language, Sun and Netscape made their way to ECMA to standardize the language
  • 20. history1996 Sun and Netscape have failed and Microsoft gathered full control on standardization process. Microsoft insisted on preserving some design errors in the language
  • 21. history1998 ECMA International introduces ECMA-262 1st + 2nd edition of JavaScript language
  • 22. VIEW STANDARD STANDARD ECMA 262ECMA-262 is active standard that defines JavaScriptUses term ECMAScriptStructured in a way that makes it hard to read
  • 23. VIEW STANDARDSTANDARDTIMELINE 1997 1998 1999 2000-2009 2009 Future1st edition 2nd edition 3rd edition 4th edition 5th edition Harmony edition June June December December
  • 24. WHAT IS javascript One of the most popular programming languages
  • 25. Javascript POPULARITY AS OF BEGINNING OF 2013One of the most popularprogramming languages
  • 26. KEY personsBrendan eich Inventor of JavaScript language at Netscape
  • 27. KEY personsDOUGLAS CROCKFORD Active member of JavaScript community Author of JSLint and JSMin Inventor of JSON data format
  • 28. WHAT IS Javascript A programming language designed to be simple and flexible
  • 29. DESIGN PRINCIPLESPROGRAMMINGLightweight & SimpleScriptingDynamicMulti-paradigm
  • 30. DESIGN PRINCIPLESTARGET AUDIENCE WEB AUTHORS Professional programmers
  • 31. DESIGN PRINCIPLESSCALABILITYLimited scalability Lack of modularity Linkage through global space Dynamicity over static typing
  • 32. DESIGN PRINCIPLESMULTI-PARADIGM language OBJECT ORIENTED FUNCTIONAL Imperative
  • 33. DESIGN PRINCIPLESOBJECT ORIENTED LANGUAGE OBJECT ORIENTED CODE SNIPPET function Plane(mass) { this.mass = mass; }; var lightPlane = new Plane(10), heavyPlane = new Plane(1000);
  • 34. DESIGN PRINCIPLESFunctional language FUNCTIONAL CODE SNIPPET var combine = function (a, b) { return function () { a(); b(); }; }, combined = combine( function () { console.log(Logging); }, function () { alert(Alerting); } ); combined();
  • 35. DESIGN PRINCIPLESOBJECT ORIENTED LANGUAGE Imperative CODE SNIPPET function bound(x, min, max) { var value = x; value = Math.min(value, max); value = Math.max(value, min); return value; }
  • 36. WHAT IS Javascript A programming language that is more than just a Web toy
  • 37. RuntimeHost environments JavaScript executes in a JAVASCRIPT ENGINE context of Engine Host environment powers JavaScript Engine HOST SPECIFIC API
  • 38. HOST ENVIRONMENTSTYPES WEB BROWSER OUT OF BROWSER
  • 39. HOST ENVIRONMENTS RESPOSIBILITIESREPOSNSIBLE FOR NOT RESPONSIBLE FOR Input/Output Code execution Graphics Memory management Storage Networking Host specific API
  • 40. WHAT IS Javascript JavaScript is a primary language of Web browser
  • 41. HOST ENVIRONMENTSWEB BROWSER WEB BROWSER HOST JAVASCRIPT ENGINE HOST SPECIFIC API DOCUMENT OBJECT MODEL BROWSER Object MODEL
  • 42. WEB BROWSERDOCUMENT OBJECT MODELRepresentation of document asobjects hierarchyLanguage & browser independentStandardized by W3CRevisions are called DOM levels
  • 43. WEB BROWSERBROWSER Object MODELAPI for interfacing native browserfunctionalityDeals with windows and framesAll functions and object starting atwindowNo corresponding standard
  • 44. WEB BROWSERBROWSER Object MODEL NavigatorWindow objectobject Frames[] Forms[] array array Document links[] object array images[] array screen object
  • 45. ENGINE RUNTIMEESSENTIALSInterpreted (no compilation step)Dynamically typed Class-free Runtime extensibility Duck typingGarbage collected
  • 46. ENGINE RUNTIMEEXECUTIONSingle threadedAsynchrony via message loopLinkage through global variables
  • 47. ENGINE RUNTIMEScript distributionScript are consumed as plain textInterpreted or compiled in-place*.js is a format for script filesMime-type: Officially: application/javascript Practically: text/javascript or no MIME type at all
  • 48. ENGINE RUNTIME Script compressionWHY? techniquesLess traffic consumption GZipFaster load time Minification Obfuscation
  • 49. Runtime engineScript inclusionStatically <script> tagDynamically DOM API Runtime evaluation
  • 50. Static inclusionScript tagScript can be put anywhereon a page with <script> tag CODE SNIPPET <script src="path/to/script.js" type="text/javascript"></script>
  • 51. Static inclusionType attribute<script> tag should have matching </script> tag, exceptwhen document has application/xhtml+xml MIME type BAD PRACTICE <script src="path/to/script.js" type="text/javascript"/> GOOD PRACTICE <script src="path/to/script.js" type="text/javascript"></script>
  • 52. Static inclusionXhtmlvalidationType attribute is optional, butrequired for XHTML validation CODE SNIPPET <script src="path/to/script.js"></script>
  • 53. static inclusionInline scripts<script> tag supports inlining, but generallyit is considered as bad practice CODE SNIPPET <script> console.log(Inline script); </script>
  • 54. static inclusionExecution orderingScripts attached in that way execute inorder, even if script2 got loaded sooner CODE SNIPPET <script src="path/to/script1.js" type="text/javascript"></script> <script src="path/to/script2.js" type="text/javascript"></script>
  • 55. static inclusionExecution orderingSame holds for inline scripts CODE SNIPPET <script src="path/to/script1.js" type="text/javascript"></script> <script> console.log(Inline script); </script>
  • 56. static inclusion rendering Script loading and execution blocks page rendering CODE SNIPPET Script.js<script src="link/to/script.js"></script> var link = document.getElementById(link);<a id="link" href="url/to/somewhere.html">Link</a> console.log(link != null); // false
  • 57. static inclusionrenderingConsider moving script to the bottom ofthe documentNot every script can be moved GOOD PRACTICE <body> <div class="page-content">Ipsum lerrra conde ir salle.</div> <script src="js/script1.js"></script> <script src="js/script2.js"></script> </body>
  • 58. static inclusionAsyncloadingScripts can be loaded asynchronouslyusing async attributeScript loading does not block rendering CODE SNIPPET <script src="link/to/script.js" async></script>
  • 59. Static inclusionASYNC loadingOrdering will not be preservedNo execution time guaranteeAll async scripts are guaranteed to executesometime before window load event CODE SNIPPET <script src="link/to/script1.js" async></script> <script src="link/to/script2.js" async></script>
  • 60. Static inclusiondefer loadingScripts can be loaded in defer mannerusing defer attributeScript loading does not block rendering CODE SNIPPET <script src="link/to/script.js" defer></script>
  • 61. STATIC INCLUSIONdefer loadingOrdering will be preservedScripts are guaranteed to start executionright before DOMContentLoaded event CODE SNIPPET <script src="link/to/script1.js" defer></script> <script src="link/to/script2.js" defer></script>
  • 62. static INCLUSIONAsync+deferloadingCauses legacy browsers to fallback to defer ifasync is not supportedModern browsers treat defer + async as async CODE SNIPPET <script src="link/to/script1.js" async defer></script>
  • 63. static INCLUSIONLOADING TIMELINE Scripting<script> HTML Parser Scripting<script async> HTML Parser Scripting<script defer> HTML Parser Networking Execution Parsing
  • 64. dynamic inclusionDOM APIScript can be attached programmaticallyusing DOM API
  • 65. DYNAMIC INCLUSIONasynchronousAsynchronous Script ordering will not be preserved CODE SNIPPET var head = document.getElementsByTagName(head)[0], script = document.createElement(script); script.src = script.js; head.appendChild(script);
  • 66. Dynamic inclusionasynchronousAsynchronous Script ordering will be preserved Older browsers require tricky solutions CODE SNIPPET var head = document.getElementsByTagName(head)[0], script = document.createElement(script); script.async = false; script.src = script.js; head.appendChild(script);
  • 67. DYNAMIC INCLUSIONDEFERREDDeferred Has no effect when loaded via DOM API CODE SNIPPET var head = document.getElementsByTagName(head)[0], script = document.createElement(script); script.src = script.js; script.defer = defer; head.appendChild(script);
  • 68. DYNAMIC INCLUSIONRuntime evaluationScripts can be evaluated at Runtime withEvalEval is ―EVIL‖ Hurts performance Makes code hard to debug Compromises security
  • 69. VIEW Morescript INCLUSIONParallel loadingNumber of parallel HTTP connections perhostname is limitedTypically varies from 2 ~ 6Consider CDN and subdomain usage
  • 70. WHAT IS Javascript JavaScript is a language that has many design errors
  • 71. ENGINE RUNTIMEStrict EXECUTION ModeAllows to opt-out to strict variant ofJavaScript Intended to correct initial design errors Prohibits usage of error-prone and insecure featuresStandardized in ECMA 262-5
  • 72. STRICT ModeactivationActivated with a Use Strict Directive in aDirective Prologue CODE SNIPPET use strict; var f = function () { console.log(Execution under strict mode); }; f();
  • 73. STRICT Modescoping CODE SNIPPETApplied to a code unit use strict; eval = 10; // SyntaxError To a Function var f = function () { To a code file eval = 20; // SyntaxError };Affects all inner contexts CODE SNIPPETDefined lexically (statically) eval = 10; // 10 var f = function () { use strict; eval = 20; // SyntaxError };
  • 74. STRICT ModeinheritanceDirectly Evaled code inherits Strict ModeIndirectly Evaled code doesn`t inheritStrict ModeFunctions created via new Function ()dont inherit Strict Mode
  • 75. STRICT Mode Error checkingCompile time runtime CODE SNIPPET CODE SNIPPETuse strict; (function () { use strict;eval = 10; // SyntaxError global_variable = 10; // Reference Error })();var f = function () { eval = 20; // SyntaxError};
  • 76. STRICT ModerestrictionsReserved words CODE SNIPPET Implements Protected "use strict"; var let = 10; // SyntaxError Interface Public Let Static Package Yield Private
  • 77. STRICT ModerestrictionsOctal literals are not allowed CODE SNIPPET "use strict"; var x = 010; // SyntaxErrorAssignment to an undeclared identifier CODE SNIPPET "use strict"; a = 10; // ReferenceError
  • 78. STRICT ModerestrictionsAssignment to read-only property CODE SNIPPET "use strict"; var foo = Object.defineProperties({}, { bar: { value: 10, writable: false // by default }, baz: { get: function () { return "baz is read-only"; } } }); foo.bar = 20; // TypeError foo.baz = 30; // TypeError
  • 79. STRICT ModerestrictionsShadowing of inherited read-only properties CODE SNIPPET "use strict"; var foo = Object.defineProperty({}, "x", { value: 10, writable: false }); var bar = Object.create(foo); bar.x = 20; // TypeError
  • 80. STRICT ModerestrictionsEval and arguments Cannot appear as variable declaration of function name CODE SNIPPET "use strict"; // SyntaxError in both cases var arguments; var eval; // also SyntaxError function eval() {} var foo = function arguments() {};
  • 81. STRICT ModerestrictionsEval and arguments Not allowed as argument names Not assignable CODE SNIPPET CODE SNIPPET"use strict"; (function (x) { alert(arguments[0]); // 30// SyntaxError arguments = 40; // TypeErrorfunction foo(eval, arguments) {} })(30);
  • 82. STRICT ModerestrictionsArgument and callee properties CODE SNIPPET "use strict"; function foo() { alert(foo.arguments); // SyntaxError alert(foo.caller); // SyntaxError }
  • 83. STRICT Moderestrictionsdelete operator restrictions CODE SNIPPET "use strict"; var foo = {}; function bar(x) { delete x; // SyntaxError } bar(10); // SyntaxError delete foo; // SyntaxError delete bar; // SyntaxError
  • 84. STRICT Mode restrictions With statement this value CODE SNIPPET Null no longer coerced to window"use strict"; CODE SNIPPET "use strict";// SyntaxErrorwith ({a: 10}) { function foo() { alert(a); console.log(this); // undefined} } foo();
  • 85. STRICT Mode restrictionsthis value Null and undefined are no longer Primitives are not converted to coerced to window wrapper objects CODE SNIPPET CODE SNIPPET"use strict"; "use strict";function foo() { Number.prototype.test = function () { console.log(this); // undefined console.log(typeof this); // number} };foo(); (1).test(); // number
  • 86. STRICT Mode restrictionsthis value CODE SNIPPET "use strict"; Helps to avoid missing new function A(x) { keyword issues this.x = x; } // forget "new" keyword, // error, because undefined.x = 10 var a = A(10); var b = new A(10); // OK
  • 87. STRICT Mode Usage guidelinesDo not apply strict mode to whole scriptfile blindly Will not work when concatenated with some other script Can break other scripts if after concatenation put first Evaled code will inherit Strict ModeConsider wrapping your scripts with self-calling function
  • 88. WHAT IS Javascript JavaScript is a language that has simple but flexible type system
  • 89. Type system essentialsClass-free type systemLoose typingEverything is an object Technically JavaScript has primitive types but they can be programmed as real objects
  • 90. Type system essentialsTwo groups of types Primitive types Object typesPrimitives are not real objectsSome primitives has object wrapper
  • 91. Type system TypesPrimitive types Object types Number Object String Array Boolean Function null RegExp undefined Date
  • 92. numbers essentialsSingle type represents integer and floatingpoint numbersIEEE 754 64 bit numbersBe aware of floating point errors 0.1 + 0.2 !== 0.3 Can be avoided by scaling
  • 93. numbers runtime Runtime type Number object wrapper CODE SNIPPET CODE SNIPPETvar foobar = 0.5; var a = 10;typeof foobar; // "number" var b = new Number(a);var foobar = 1;typeof foobar; // "number" console.log(typeof b); // object
  • 94. numbers Special valuesSpecial values NaN -Infinity Infinity
  • 95. numbersnanParadoxical type CODE SNIPPET var foobar = NaN; typeof foobar; // "number"Watch out, easy to overwrite! CODE SNIPPET var NaN = "string"; typeof NaN; // "string"
  • 96. numbersnanGetting NaN CODE SNIPPET var foobar = "string" * 2, bar = "string" / 2; var foo = +"string", barfoo = +[1, 2, 3], foobar2 = undefined – 2;
  • 97. strings essentialsUnicode UTF-16 Built-in string manipulation routines dont take surrogate pairs into accountImmutableZero-based indexingNo dedicated Char type
  • 98. strings declarationLiteral declaration CODE SNIPPET var a = "string"; var b = string;
  • 99. strings runtime Runtime type String object wrapper CODE SNIPPET CODE SNIPPETvar foobar = "variable types"; var a = foo;typeof foobar; // "string" var b = new String(a); console.log(typeof b); // object
  • 100. boolean essentialsTwo possible predefined values true falseGenerally Boolean produced by comparisons a === 1Any value can be converted to Boolean
  • 101. Boolean Falsyvalues CODE SNIPPETundefined var falsyValue = 0; if (!falsyValue) {null alert("falsy value!"); }0 var falsyValue = "";-0 if (!falsyValue) { alert("falsy value!");NaN }Empty string var falsyValue = NaN; if (!falsyValue) { alert("falsy value!"); }
  • 102. Boolean runtime Runtime type Boolean object wrapper CODE SNIPPET CODE SNIPPETvar foobar = true; var a = true;typeof foobar; // "boolean" var b = new Boolean(a); console.log(typeof b); // object
  • 103. Null essentialsLanguage keywordIndicates absence of valueJavaScript never sets uninitializedvariables to null
  • 104. Null runtime Runtime type CODE SNIPPETvar foobar = null;typeof foobar; // "object" Has no object wrapper
  • 105. undefined essentialsIndicates Variable is not defined Variable is defined, but has no value assigned
  • 106. undefinedruntimeRuntime type CODE SNIPPETvar foobar;typeof foobar; // "undefined"Has no object wrapper
  • 107. Undefined runtime Producing undefined value Can be overridden CODE SNIPPET CODE SNIPPET(function (undefined) { (function () { console.log(typeof undefined); var undefined = 10;})(); console.log(typeof undefined); })();
  • 108. objectessentialsFundamental data typeUnordered collection of key-value pairsHave no fixed schemaRuntime extendableLinked with another object via prototype
  • 109. ENGINE RUNTIMEObject originators Host objects NATIVE OBJECTS User-defined
  • 110. Object originatorsHost objects Host objects Host objects are objects that are supplied to JavaScript by the browser environment Examples of these are window, document, forms, etc Poorly defined
  • 111. Object originatorsNative objects NATIVE OBJECTS Native objects are those objects supplied by JavaScript runtime Examples of these are String, Number, Array, Image, Date, Math, etc Be very cautious extending these
  • 112. Object originatorsUser-defined objects User-defined User-defined object are defined by programmer Full control OK to extend these
  • 113. objectInternal layout[[prototype]] referenceClass discriminator Can`t be set for user-defined objectsExtensible flag Defined in ES5
  • 114. objectdeclarationObject literal syntax CODE SNIPPET CODE SNIPPETvar person = { var person = {}; firstName: Douglas, person.firstName = Douglas; lastName: Crockford, person.lastName = Crockford; age: 45 person.age = 45;};
  • 115. object declaration Constructor function Object.create BAD PRACTICE CODE SNIPPET var person = Object.create(Object.prototype, {var person = new Object(); firstName: { writable: true,person.firstName = Douglas; configurable: true,person.lastName = Crockford; value: Douglas },person.age = 45; lastName: { writable: true, configurable: true, value: Crockford }, age: { writable: true, configurable: true, value: 45 } });
  • 116. objectProperty assessorsTwo ways to access the object’s property CODE SNIPPET obj[property]; obj.property;
  • 117. objectConstructor propertyConstructor property points to constructorfunctionCan be messed up at runtime CODE SNIPPET var object = {}; console.log(object.constructor === Object);
  • 118. objectprototypePrototype links object with another object Internal [[prototype]] field Set at creation based on Function.prototype valueSimple form of inheritance No schema (classes) involved Object inherits directly from another object
  • 119. prototypechaining {} Object.prototype NULL [[prototype]] [[prototype]]
  • 120. prototypeProperty resolutionSearch for property in current objectIf not found search in a prototypeMove along prototype chain until null isreached
  • 121. prototypeProperty resolutionExample toString is not declared in object but rather in Object.prototype CODE SNIPPET var object = {}; console.log(object.toString());
  • 122. prototype inspection Undocumented field Constructor`s prototype BAD PRACTICE CODE SNIPPETvar object = {}; var object = {};console.log(object.__proto__); console.log(object.constructor.prototype); getPrototypeOf CODE SNIPPETvar object = {};console.log(Object.getPrototypeOf(object));
  • 123. object reflection for in hasOwnProperty CODE SNIPPET CODE SNIPPETvar obj = { property: "foobar", for (var i in obj) { method: function() {} if (obj.hasOwnProperty(i)) {}; alert("The value of key " + i +for (var i in obj) { " is " + obj[i]); alert("The value of key " + i +" is " + } obj[i]); }}
  • 124. object reflection in __count__ CODE SNIPPET BAD PRACTICEvar obj = { var obj = { a: 10 property: "foobar",}; method: function() {} };var hasProperty = (a in obj); obj.__count__; // 2
  • 125. arrayessentialsOrdered collection of valuesZero-based 32bit indexingDynamic No need for memory reallocationSpecialized form of objects with lengthproperty
  • 126. ArrayruntimeRuntime type CODE SNIPPETvar array = [1, 2, 3];typeof array; // object
  • 127. Arrayruntime Array detection (fails in multi-frame scenario) CODE SNIPPET array instanceof Array The most reliable way of array detection CODE SNIPPET Object.prototype.toString.call(array) === "[object Array]"
  • 128. array declaration Array literal Array constructor CODE SNIPPET BAD PRACTICEvar array = []; var array = new Array();
  • 129. array behavior Dynamic grow & shrink Length property CODE SNIPPET CODE SNIPPETvar array = [1, 2, 3]; var array = [1, 2, 3];array.push(4); console.log(array.length); // 3array.pop(); // 4
  • 130. arrayperformanceJavaScript arrays are special type of objectMuch slower than real arrays
  • 131. operatorsoperator =―=― Multiple assignment Assignment order is from right to left CODE SNIPPET var foobar = 1; var foo = 2; var bar = foo = foobar = 3; // bar == 3, foo == 3, foobar == 3
  • 132. Operatorsoperator +String concatenation CODE SNIPPET var foobar = "This " + "is " + "a variable.";Casting to number CODE SNIPPET var foobar = +true; // 1 var foobar = +false; // 0
  • 133. Operators operator + Adding CODE SNIPPETvar foobar = 5 + 1; // 6 String priority CODE SNIPPET CODE SNIPPETvar foobar = "1" + 0; // 10 ! var foobar = function() {};typeof foobar; // "string" var foobar2string = "" + foobar;var foobar = 0 + "1"; // 01 //"function() {}"typeof foobar; // "string" typeof foobar2string; // "string"
  • 134. Operators operators += and ++ Addition Casting to string CODE SNIPPET CODE SNIPPETvar foobar = 1; var foobar = "1";foobar += 1; // 2 foobar += 5; // "15" Casting to number CODE SNIPPETvar foobar = "5";foobar++;typeof foobar; // "number"
  • 135. Operatorsoperators += and ++Multiple assignments CODE SNIPPET var foo = 1; var bar = 2; foo += bar += 3; // foo == 6; bar == 5; CODE SNIPPET var foo = "1"; var bar = "2"; foo += bar += " is a string"; // foo == "12 is a string; // bar == "2 is a string";
  • 136. Operators operators -= and -- Decrement CODE SNIPPETvar foobar = 1;foobar -= 1; // 0 -= does not behave like += CODE SNIPPET CODE SNIPPET var foobar = "5";var foobar = "1"; foobar--;foobar -= 5; // -4 (number) // 4 typeof foobar; // "number"
  • 137. Operatorsoperators -= and --Multiple assignments CODE SNIPPET var foo = 3; var bar = 2; foo -= bar -= 1; // foo == 2; bar == 1; CODE SNIPPET var foo = "1"; var bar = "2"; foo -= bar -= " is a string"; // foo == NaN // bar == NaN
  • 138. Operators operator | | Assignment CODE SNIPPET CODE SNIPPETvar foo = false; var foo = true;var bar = function() {}; var bar = function() {};var foobar = foo || bar; // foobar === bar var foobar = foo || bar; // foobar === truefoobar(); foobar(); // error CODE SNIPPET var foo = false; var bar = false; var barfoo = 5; var foobar = foo || bar || barfoo; // foobar === 5
  • 139. Operators operator && Assignment CODE SNIPPET CODE SNIPPETvar foo = true; var foo = false;var bar = function() {}; var bar = function() {};var foobar = foo && bar; // foobar === bar var foobar = foo && bar; // foobar === falsefoobar(); foobar(); // error Inline conditions CODE SNIPPETvar foo = true;var bar = function() { alert("hello world!"); };foo && bar(); // hello word!
  • 140. Operatorsoperators && and | |Good order makes a difference CODE SNIPPET var foo = true; var bar = false; var barfoo = false; var foobar = foo && bar || barfoo || 5; // foobar === 5
  • 141. Operators Operator ! Negation Double negation (converts to Boolean) CODE SNIPPET CODE SNIPPETvar foo = 5; var foo = 5;!foo; // false !!foo; // truevar foo = 0;!foo; // truevar foo = "0";!foo; // falsevar foo = "1";!foo; // false
  • 142. Operators operator ~ Bitwise operator Numbers rounding CODE SNIPPETvar foo = 5.743534;~~foo; // 5typeof ~~foo; // "number" -(n + 1) when ―n‖ is an integer CODE SNIPPETvar foo = -1;~foo; // 0
  • 143. Operators comparison operators ( > , >= , <, <=, ==, ===, !=, !==) Return value of Boolean type Can be used as part of more complex expression CODE SNIPPETvar a = 0, b = 5, c = a || b > aalert(c); // "true"
  • 144. OperatorsString comparisonStrings are compared using alphabetical order―Alphabetical order‖ is defined by the numerical order of the16-bit Unicode values that make up the strings CODE SNIPPET CODE SNIPPETalert("b" > "a"); // "true" alert("cat" > "cats"); // "false"
  • 145. OperatorsComparison of Different typesValues are converted to numbers except for the casewhen both values are strings CODE SNIPPETalert("2" > 1); // "true"alert("02" == 2); // "true"alert(0 == false); // "true"
  • 146. OperatorsStrict Equality(===, !==)Usual equality check cant distinguish the values that belongto different types but have the same number representationStrict equality operator is used to check equality withouttype conversion CODE SNIPPETalert("02" === 2); // "false"alert(0 === false); // "false"
  • 147. OperatorsComparison with NULL and Undefinednull and undefined are not equal to 0 in comparisonsnull and undefined are equal only to each otherWhen converted to a numbernull is 0undefined is NaN CODE SNIPPET CODE SNIPPETalert(null > 0); // "false" alert(undefined > 0); // "false"alert(null == 0); // "false" alert(undefined < 0); // "false"alert(null >= 0); // "true" alert(undefined == 0); // "false"
  • 148. OperatorsObject ConversiontoString and valueOf are methods for string and numberconversion respectivelyString and number conversion can be overriddenIf the operation requires a primitive value the object isconverted to the primitive first and then operation isperformedNumber conversion is used to convert object to primitive(exception is built-in Date object)
  • 149. alert(user); // [object Object] Operators string Conversion of objects toString is declared in Object.prototype toString can be overridden in user-defined object toString should return any primitive value, otherwise it will cause an error CODE SNIPPET CODE SNIPPET var user = { var user = { firstName: "John" firstName: "John", }; toString: function () { return "user " + this.firstName alert(user) // "[object Object]" } }; alert(user) // "user John"
  • 150. OperatorsString conversion of objectsBuilt-in objects have their own implementation of toString CODE SNIPPET alert([1, 2]); // toString for Arrays – list of elements "1, 2" alert(new Date()); // toString for Date – string representation of date alert(function () {}); // toString for Function – source code of function
  • 151. OperatorsNumber conversion of objectsvalueOf is declared in Object.prototype but it returns objectitself and therefore is ignoredvalueOf can be overridden in user-defined objectvalueOf should return any primitive value, otherwise it willbe ignoredIn case valueOf is ignored or not declared toString methodis used instead
  • 152. OperatorsNumber conversion of objectsMost built-in objects dont have valueOf implementationand therefore string and number conversion gives the sameresults (exception is Date object which supports both stringand number conversion) CODE SNIPPET alert(new Date()); // toString - string representation of date alert(+new Date()); // valueOf – number of milliseconds from 01.01.1970
  • 153. OperatorsComparisons with objectsIf both operands are objects operators (==, !=) check ifoperands are or arent references to the same objectIn all other cases number conversion is used to get primitivetype and then perform operation (this is also true forarithmetic operators) CODE SNIPPET var a = {}, b = {}, c = a; alert(a == b); // "false" alert(a == c); // "true"
  • 154. Operators Comparisons with objects CODE SNIPPET CODE SNIPPETvar obj = { var a = { valueOf: function () { valueOf: function () { return 1; return 1; } }}; };alert(obj == true); // "true" var b = {alert(obj + "test"); // "1test" valueOf: function () { return 2; } }; alert(b > a); // "true"
  • 155. WHAT IS Javascript JavaScript is a language that has unique execution nuances
  • 156. ENGINE RUNTIMEExecution ContextAbstract concept for differentiation ofexecutable codeEvery time when control is transferred to executablecode, control enters an execution context.Defined in ECMA-262 Consistent concept, but multiple implementations
  • 157. Execution contextTypes of executable codeThere are 3 types of JavaScript code Global code Function code Eval codeEvery code is evaluated in its context
  • 158. Execution contextProgram runtimeProgram Runtime EC0 active ECrepresented as stack of EC EC1Pushed every time on EC2entering a function EC3 EC4 GLOBAL EC
  • 159. Execution context Function code Executable code EC stack CODE SNIPPET CODE SNIPPET(function foo(flag) { // first activation of foo if (flag) { ECStack = [ return; <foo> functionContext } globalContext foo(true); ];})(false); // recursive activation of foo ECStack = [ <foo> functionContext – recursively <foo> functionContext globalContext ];
  • 160. Execution contextEvalcodeVery special type of codeExecutes in its own context but affectscalling context In Strict Mode evaled code evaluates in its own sandbox
  • 161. Execution context Evalcode Executable code EC stack CODE SNIPPET CODE SNIPPET ECStack = [// influence global context globalContexteval(var x = 10); ]; // eval(var x = 10);(function foo() { ECStack.push({ // and here, variable "y" is context: evalContext, callingContext: globalContext // created in the local context }); // of "foo" function ECStack.pop(); // eval exited context eval(var y = 20); ECStack.push(<foo> functionContext); // foo function call})(); // eval(var y = 20); ECStack.push({alert(x); // 10 context: evalContext, callingContext: <foo> functionContextalert(y); // "y" is not defined }); ECStack.pop(); // return from eval ECStack.pop(); // return from foo
  • 162. Execution contextLOGICAL layout Execution contextEC may be represented assimple object VARIABLE OBJECT Scope chain THIS VALUE
  • 163. Execution contextVariable objectA Variable Object (VO) is tied to ECAbstract store for Variables (var, VariableDeclaration) Function declarations (FunctionDeclaration, FD) Function format parameters
  • 164. Variable Object Logical layout Declaration Variable Object CODE SNIPPET CODE SNIPPETvar a = 10; // Variable object of the global context VO(globalContext) = {function test(x) { a: 10, var b = 20; test: <reference to function>}; };test(30); // Variable object of the "test" function context VO(test functionContext) = { x: 30, b: 20 };
  • 165. Variable Objecttypes Function context VO GLOBAL context VO (VO === AO, <arguments> object and (vo===this===global) <formal parameters> are added)
  • 166. Variable ObjectGlobal context voAllows indirect referencing throughwindow objectLifetime tied to applicationlifetime CODE SNIPPET global = {Singleton Math: <...>, String: <...> ... ... window: global };
  • 167. Variable Objectfunction context voDoesn`t allow indirect referencingVO`s role plays Activation Object An activation object is created on entering the context of a function and initialized by property arguments which value is the Arguments object CODE SNIPPET VO(functionContext) === AO;
  • 168. Variable ObjectActivation objectArguments contains CODE SNIPPET AO = { callee - the reference to the current function arguments: <ArgO> }; length - quantity of real passed arguments properties-indexes
  • 169. Variable ObjectActivation object CODE SNIPPET function foo(x, y, z) { alert(foo.length); // 3Variable number of parameters alert(arguments.length); // 2 // reference of a function to itselfRuntime function inspection alert(arguments.callee === foo); // true // parameters sharing alert(x === arguments[0]); // true alert(x); // 10 arguments[0] = 20; alert(x); // 20 x = 30; alert(arguments[0]); // 30 z = 40; alert(arguments[2]); // undefined arguments[2] = 50; alert(z); // 40 } foo(10, 20);
  • 170. Execution contextExecution stagesTwo stages of code handling Entering the context where all the data are created Formal parameter initialization Function declaration Variable declaration The code execution stage
  • 171. Execution contextEntering Execution contextFor each formal parameter Property of the VO with a name and value of formal parameter is created For not passed parameters — property of VO with a name of formal parameter and value undefined is created
  • 172. Execution contextEntering Execution contextFor each function declaration A property of the variable object with a name and value of a function-object is created If the variable object already contains a property with the same name, replace its value and attributes
  • 173. Execution contextEntering Execution contextFor each variable declaration a property of the variable object with a variable name and value undefined is created if the variable name is already declared, declaration does not disturb the existing property.
  • 174. Execution context Entering Execution context Executable code Activation Object CODE SNIPPET CODE SNIPPETfunction test(a, b) { AO(test) = { var c = 10; a: 10, function d() { } b: undefined, var e = function _e() { }; c: undefined, (function x() { }); d: <reference to FunctionDeclaration "d">} e: undefined, arguments: <Args>test(10); // call };
  • 175. Execution context Execution phase Variables and function declarations are hoisted, but not assignmentsOriginal source Internal representation CODE SNIPPET CODE SNIPPET foo(); var bar; function foo() { function foo() { console.log(bar); alert(bar); } } var bar = 10; foo(); bar = 10;
  • 176. Execution contextFunction -level scopingES3 has no block-level scoping defined Variable declared in a block visible everywhere in a function CODE SNIPPET (function () { { var a = 10; } console.log(a); // 10 })();
  • 177. Execution contextFunction -level scopingES6 Harmony allows block-level scopingwith let keyword CODE SNIPPET (function () { { let a = 10; } console.log(a); // Reference error })();
  • 178. Execution contextLOGICAL layout Execution contextEC may be represented assimple object VARIABLE OBJECT Scope CHAIN THIS VALUE
  • 179. Execution contextScope chainList of all (parent) variable objects for theinner contextsCreated at function callConsists of Variable Object of currently executing code unit Internal [[Scope]] field
  • 180. Scope chainLogical layout CODE SNIPPETUsed for identifier lookup activeExecutionContext = { VO: {...}, // or AO Traversing scope chain this: thisValue, Scope: [ // Scope chain 2D lookup with prototypes // list of all variable objects // for identifiers lookup ] } CODE SNIPPET Scope = AO + [[Scope]]
  • 181. Scope chain[[scope]] property[[Scope]] is a chain of all parent VO, which are abovethe current function context[[Scope]] is saved to the function at its creation Implements Lexical (Static) Scoping
  • 182. Scope chain scoping Executable code Scope chain CODE SNIPPET CODE SNIPPETvar x = 10; barContext.Scope = barContext.AO + bar.[[Scope]] // i.e.:function foo() { var y = 20; barContext.Scope = [ barContext.AO, function bar() { fooContext.AO, var z = 30; globalContext.VO alert(x + y + z); ]; } bar();}foo(); // 60
  • 183. Scope chainclosureClosure is a functional conceptConsist of 2 parts Function or function pointer Referencing environment – a table of references to variables form outer scope
  • 184. Closureexample CODE SNIPPETInner is a function var f = function outer() { var a = 10;Scope of outer function forms return function inner() {referencing environment } return a; }; f1 = f(); console.log(f1()); // 10
  • 185. ClosurenuancesReferencing environment consist of references to outervariablesClosures on iterator variables work incounterintuitive way
  • 186. Closure nuancesincorrect Correct CODE SNIPPET CODE SNIPPETvar array = [0, 1, 2]; var array = [0, 1, 2];for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) { array[i] = function () { (function (i) { console.log(i); array[i] = function () { }; console.log(i);} }; })(i);array[0](); // 3 } array[0](); // 0
  • 187. Closure nuances Watch out for context switches CODE SNIPPET CODE SNIPPETvar person = { var person = { firstName: Douglas, firstName: Douglas, say: function () { say: function () { function sayName() { var me = this; console.log(this); // window or undefined return this.firstName; function sayName() { } return me.firstName; } return sayName(); return sayName(); } }}; };person.say(); person.say();
  • 188. Execution contextLOGICAL layout Execution contextEC may be represented assimple object VARIABLE OBJECT Scope chain THIS VALUE
  • 189. Execution contextThis valueSpecial context object Not tied to particular object Can be set at runtimeProperty of EC Never participates in identifier lookup Determined only once when entering EC Immutable
  • 190. This value Global scope Executable code CODE SNIPPET// explicit property definition of the global objectthis.a = 10; // global.a = 10alert(a); // 10// implicit definition via assigning to unqualified identifierb = 20;alert(this.b); // 20// also implicit via variable declaration because variableobject of the global context// is the global object itselfvar c = 30;alert(this.c); // 30
  • 191. This valueCall expression CODE SNIPPETValue of this is determined function foo() { alert(this);by the form of a call }expression foo(); // global or undefined (strict mode) alert(foo === foo.prototype.constructor); // true // but with another form of the call expression // of the same function, this value is different foo.prototype.constructor(); // foo.prototype
  • 192. This valueCall expressionManual setting of ThisValue Function.prototype.call Function.prototype.apply Function.prototype.bindThisValue as first parameter
  • 193. This valueCALL CODE SNIPPETThisValue as first parameter function a(c) { alert(this.b);Comma-separated list of } alert(c);parameters // this === {b: 20}, this.b == 20, c == 30 a.call({ b: 20 }, 30);Executes a function
  • 194. This valueapply CODE SNIPPETThisValue as first parameter function a(c) { alert(this.b);Array of parameters } alert(c);Executes a function // this === {b: 30}, this.b == 30, c == 40 a.apply({ b: 30 }, [40])
  • 195. This valuebind CODE SNIPPETThisValue as first parameter function a(c) { alert(this.b);Comma-separated list of } alert(c);parameters // this === {b: 30}, this.b == 30, c == 40 (a.bind({ b: 30 }, 40))();Returns a function
  • 196. WHAT IS Javascript JavaScript is a language that has unique implementation of OOP
  • 197. patterns & practicesmodularityModules are building blocks of the appKey properties Loose coupling High cohesionFacilitate clean and flexible architecture
  • 198. patterns & practicesmodularityLanguage has no built-in concept of modulesModules are simulated using Functions Local variables ClosuresDozen of design patterns available
  • 199. modularityModule patternProvides encapsulation for Privacy State StructurePhysical shielding of private and publicmembers
  • 200. modularityModule pattern CODE SNIPPETLanguage features used var MY_APP_ONE = (function () { // Private variables Self-calling functions var secret1 = Hello; var secret2 = World; Closures // Private functions var privateFoo = function() { }; // Publicly exposed return { foo: function() { // Do stuff }, bar: function() { // Do stuff } }; })();
  • 201. modularityModule pattern pros consClean syntax Hard to refactorPrivate members Hard to extend Hard to override No way of dependency management
  • 202. modularityREVEALING Module patternVery similar to Module PatternAll members declared as privatePublic members then ―revealed‖ by returnstatement
  • 203. modularityRevealing Module pattern CODE SNIPPETLanguage features used var MY_APP_ONE = (function () { // Private variables var secret1 = Hello; Self-calling functions var secret2 = World; Closures // Private functions var privateFoo = function () {}; var publicFoo = function () {}; var publicBar = function() {}; // Publicly exposed return { foo: publicFoo, bar: publicBar }; })();
  • 204. modularityModule revealing pattern pros consClean syntax Hard to extendPrivate members Even harder toCommon syntax for accessing overrideprivate and public members No way of dependency management
  • 205. modularityAMDDeveloped as standard for async moduleloadingOn demand async module loadingBuilt-in dependency managementHas corresponding specification
  • 206. modularityAMDConcise API define requireNamespace-free architectureModules referred to by name or path
  • 207. modularityAMD CODE SNIPPETLanguage features used // shirt.js define({ color: "black", Self-calling functions size: "large" }); Closures // logger.js define(["shirt"], function (shirt) { return { logTheShirt: function () { console.log( "color: " + shirt.color + ", size: " + shirt.size ); } }; });
  • 208. modularityAMD pros consClean syntax Async nature may leadAsync loading to spaghetti codeDependency management Requires build tool to be used in minified file
  • 209. modularityCommonjsmodules 1.1Developed as part of CommonJS projectOn demand synchronous module loadingBuilt-in dependency managementHas corresponding specification
  • 210. modularityCommonjsmodules 1.1Concise API require module.exportsModules referred to by name or pathOne module one script file mapping Can`t be used in minification scenarios
  • 211. modularityCommonjsmodules 1.1 CODE SNIPPETLanguage features used // hello.js exports.hello = function () { return Hello World; Closures }; //app.js var example = require(./example.js); example.hello();
  • 212. modularityCommonjsmodules 1.1 pros consClean syntax Sync loading is inappropriate inDependency management Web browser Doesn`t support minification scenarios
  • 213. patterns & practicesinheritanceNo classical inheritanceLots of ways to achieve inheritance Pseudo-classical Prototypal FunctionalDon’t try to pretend you`re programming on someother language
  • 214. inheritancePseudo-classicalInvented to make classical style inheritancepossibleNative JavaScript objects follow thispattern
  • 215. Pseudo-classical patternKey ideasKey ideas The object is created by a constructor function Properties are put into constructor function Methods and default properties are put into prototype
  • 216. Pseudo-classical patternBase class CODE SNIPPETExample function Animal(name) { canWalk property will be this.name = name overridden in concrete instance } Animal.prototype = { Constructor assignment makes constructor: Animal, instanceof operator work canWalk: true, sit: function() { this.canWalk = false alert(this.name + sits down.) } } var animal = new Animal(Pet) // (1)
  • 217. Pseudo-classical pattern Base classInitially After sit Animal.prototype Animal.prototype { { canWalk: ‘true’, canWalk: ‘true’, sit: function sit: function } }[[prototype]] [[prototype]] instance instance { { name: ‘Pet’, name: ‘Pet’ canWalk: ‘false’ } }
  • 218. Pseudo-classical patternInheritance functionInherit base class prototypeand allow extensibility CODE SNIPPET function extend(Child, Parent) { var F = function () { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }
  • 219. Pseudo-classical patternDerived class CODE SNIPPETExample function Rabbit(name) { Superclass constructor called to Rabbit.superclass.constructor.apply(this, arguments); initialize properties defined in } base class extend(Rabbit, Animal); Rabbit.prototype.jump = function () { this.canWalk = true; alert(this.name + is jumping.); };
  • 220. Pseudo-classical patternMethod overridingSuperclass call CODE SNIPPET Rabbit.prototype.sit = function () { alert(this.name + is about to sit!); Rabbit.superclass.sit.apply(this, arguments); };
  • 221. Pseudo-classical patternencapsulation CODE SNIPPETConvention based encapsulation Animal.prototype.walk = function () { Common practice is to prefix alert(walking); }; protected members with _ Animal.prototype._run = function () { alert(running); }
  • 222. Pseudo-classical patternstatics CODE SNIPPETStatic properties and functions function Animal() { Assigned directly to the constructor Animal.count++ } Animal.count = 0 new Animal() new Animal() alert(Animal.count); // 2
  • 223. inheritanceprototypalPrototypal inheritance is native toJavaScriptMay or may not use concept of class
  • 224. PrototypalKey ideasKey ideas The object is created by special function This function links object with prototype Freedom of choice where to put properties and methods
  • 225. Prototypal Object creation Links empty object with ES5 has dedicated function specified prototype CODE SNIPPET CODE SNIPPETfunction object(o) { function F() { } Object.create(prototype, propertyDescriptors) F.prototype = o; return new F();}
  • 226. Prototypalexample CODE SNIPPETDerived object inherits var base = {from base via prototype }; a: 1 var derived = object(base); derived.print = function() { console.log(this.a); }; derived.print();
  • 227. inheritanceParasiticObject inherits base class properties byextending itMay or may not use concept of class
  • 228. parasiticKey ideasKey ideas Derived object extends base object Prototype is not used at all Fast property resolution
  • 229. WHAT IS Javascript JavaScript is a script language distant from actual hardware
  • 230. Performance optimizationreasoningPremature optimization is Evil Performance optimizations needs to based on actual profiling dataPareto principle: 90/10Consider algorithmic optimizations first
  • 231. Performance optimizationFunction callsAvoid intensive functions calling CODE SNIPPET while (i) { fn(i); var i = fn2(); fn3(i); };
  • 232. Performance optimizationLocal variablesUse local variables CODE SNIPPET var fn = function() { var events = library.utils.events; var proxy = library.services.proxy; };
  • 233. Performance optimization LICM Loop invariant code motion CODE SNIPPET CODE SNIPPETvar arr = [1, 2, 3, 4]; var arr = [1, 2, 3, 4];for (var i = 0; i < arr.length; i++) {}; for (var i = 0, j = arr.length; i < j; i++) {}; CODE SNIPPET var arr = [1, 2, 3, 4]; var i = arr.length; while(i--) {};
  • 234. Performance optimizationMemoizationMemoization CODE SNIPPET var arr = [1, 2, 3, 4, 4, 2, 3, 1, 2, 3, 4, 5, 6, 1]; var fn = function fn(i) { fn.cache = fn.cache || {}; if (i in fn.cache) { return fn.cache[i]; } return (fn.cache[i] = Math.cos(i)); };
  • 235. Performance optimizationCode optimizationAvoid try {} catch() {}Avoid bit operatorsYielding
  • 236. Performance optimizationKeep it simpleSimpler - faster Slow CODE SNIPPET var min = Math.min(a, b); arr.push(val); Fast CODE SNIPPET var min = a < b ? a : b; arr[arr.length] = val;
  • 237. Special thanksReviewers & inspirationsDamian Wielgosik His amazing depth knowledge of JS inspired my presentation. Check out his Just Advanced JavaScript on SlideShare.Pavel Hizhuk His amazing understanding of type casting and comparisons reflected directly in this presentation.
  • 238. Special thanksReviewers & inspirationsMy Girlfriend For constant support and patience in listening my crazy saying about how badly something implemented, for sleepless nights and funny jokes :)
  • 239. The end