KEMBAR78
JavaScript Basics and Best Practices - CC FE & UX | PDF
JavaScript Basics & Best Practices
Competence Center Front-end & UX
Dennis Jaamann
Front-end developer
Overview
▪ Part 1: Introduction
▪ What is JavaScript?
▪ How a JavaScript engine works
▪ Language features
▪ The future of JavaScript
Overview
▪ Part 2: The Basics
▪ Types, variables, constants and literals
▪ Expressions and operators
▪ Statements
▪ Functions
▪ Objects
▪ Prototypical inheritance
▪ Equality
Overview
▪ Part 3: Best Practices for enterprise apps
JavaScript Basics & Best Practices
Part 1: Introduction
What is JavaScript? According to java devs
▪ Works in all browsers except IE
▪ A crappy version of Java
▪ No type safety
▪ Something to stay miles away from
▪ JavaScript sucks *ss (1)
(1) = Actual wording of most Java developers, presenter cannot be held accountable for harshness thereof
What is JavaScript? Really
▪ Invented by Brendan Eich (1995)
▪ Former CTO / CEO of mozilla
▪ Cross-platform
▪ Object based
▪ Dynamic
▪ Scripting language
▪ Currently ECMA-262 (ECMAScript 5)
▪ Web APIs (DOM, ..)
How a JavaScript engine works
▪ Virtual machine
▪ Interpret and execute JavaScript
▪ Most common in browsers
▪ For example: Google V8 engine
Language features - The bad
▪ Easy to introduce globals = root of all evil
▪ Automatic line termination
▪ Semicolons automatically inserted by interpreter
▪ Can lead to quirky behavior
▪ No warning
▪ Object equality and Object comparison
▪ Error prone due to dynamically typed objects
▪ Type coercion happens automagically (= auto casting)
Language features - The good
▪ Everything is an Object
▪ Including functions
▪ Objects are loosely typed
▪ Every object can be assigned any value
▪ Objects are dynamic
▪ Can change type @ runtime
▪ Add members on the fly
▪ Object literals
The future of JavaScript
▪ ECMAScript 6
▪ Classes
▪ Modules
▪ Promises
▪ http://kangax.github.io/compat-table/es6/
▪ WebComponents
▪ Extend HTML with your own components
▪ Already available through usage of Polymer
JavaScript Basics & Best Practices
Part 2: The basics
Types, variables, constants and literals - Types
▪ 5 primitive types in JavaScript
Type Possible values
Number 1337, 3.14
String “JavaScript sucks *ss according to java
devs”
Boolean true, false
null null
undefined undefined
Types, variables, constants and literals - Types
▪ 2 complex types in JavaScript
▪ Object
▪ Constructor
▪ Members
▪ Inheritance-like behavior through prototypes
▪ Function
▪ Every function is a new instance of the Function object
▪ Block of code designed to perform a specific task
Types, variables, constants and literals - Types
▪ null vs. undefined
▪ null: value that can be assigned to a variable to indicate an empty value
▪ undefined: value of a variable that has been declared but has not been
assigned a value
var someNullifiedVariable = null;
console.log(someNullifiedVariable); // null
console.log(typeof someNullifiedVariable); // Object
var someUndefinedVariable;
console.log(someUndefinedVariable); // undefined
console.log(typeof someNullifiedVariable); // undefined
Types, variables, constants and literals - Variables
▪ Declaring a variable
▪ The good way
▪ Use var keyword
▪ Variable always declared on current scope
▪ The evil way
▪ No keyword
▪ Variable always declared on global scope
▪ Warning in strict mode
var someNumber = 42; // The good way
someOtherNumber = 42 // The evil way
Types, variables, constants and literals - Variables
▪ Variable scope
▪ Global scope
▪ Variable declared outside of any function
▪ Accessible to any other code in the document
▪ Function scope
▪ Variable declared inside of any function
▪ Accessible to function and all inner functions
▪ Block scope
▪ Variable declared within block is local to containing function
Types, variables, constants and literals - Variables
if(true){
var someGlobalVar = 1337; //global scope, since block is outside of any function
}
function someFunction(){
var someLocalVar = 9000; // function scope
function someInnerFunction(){
console.log(someLocalVar); //9000
someLocalVar = 90210;
}
someInnerFunction();
console.log(someLocalVar); //90210
}
console.log(someGlobalVar); //1337
someFunction();
console.log(someLocalVar); //Uncaught ReferenceError
Types, variables, constants and literals - Constants
▪ Defining a constant
const myTotallyAwesomeConstant = 3;
console.log(myTotallyAwesomeConstant); // 3
const myTotallyAwesomeConstant = 1337;
console.log(myTotallyAwesomeConstant); // 3
Types, variables, constants and literals - Literals
▪ Defining literals
▪ Represent fixed values, not variables
▪ Literally providing values in code
var myAwesomeArray = [1,2,"test",true];
var myAwesomeObject = {firstMember:1,secondMember:2};
var myAwesomeBoolean = true;
var myAwesomeNumber = 1337;
var myAwesomeString = "Ordina is too awesome";
console.log(myAwesomeArray.toString()); // 1,2,test,true
console.log(myAwesomeObject); // Object {firstMember: 1, secondMember: 2}
console.log(myAwesomeBoolean); // true
console.log(myAwesomeNumber); // 1337
console.log(myAwesomeString); // Ordina is too awesome
Expressions and operators
▪ Expressions and operators very similar to Java
▪ Precedence also similar
Assignment Comparison Arithmetic Bitwise Logical String
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
==
!=
===
!==
>
>=
<
<=
%
++
--
-
&
|
^
~
<<
>>
>>>
&&
||
!
+
+=
Statements
▪ Statements also very similar to Java
Conditional Loops Exceptions
if(){}else{}
switch(){}
while(){};
do{}while();
for(){};
continue;
break
throw
try{}catch(){};
Functions
▪ Fundamental building blocks in JavaScript
▪ Perform a set of statements
▪ Calculate a value
▪ Perform a task
▪ Define on the scope from where you want to call it
Functions - Arguments
▪ Primitive arguments always passed by value (copy)
function myAwesomeFunction(somePrimitiveNumber){
console.log(somePrimitiveNumber); // 99
somePrimitiveNumber = 1337;
console.log(somePrimitiveNumber); // 1337
}
var someNumber = 99;
console.log(someNumber)// 99
myAwesomeFunction(someNumber);
console.log(someNumber); // 99
Functions - Arguments
▪ Complex arguments always passed by reference
▪ Arrays, Objects, Functions
▪ Changing value of any property => visible outside function scope
function myAwesomeFunction(someComplexObject){
console.log(someComplexObject); // Object {member1:"gold",member2:"silver"}
someComplexObject.member2 = "wood";
console.log(someComplexObject); // Object {member1:"gold",member2:"wood"}
}
var someComplexObject = {member1:"gold",member2:"silver"};
console.log(someComplexObject)// Object {member1:"gold",member2:"silver"}
myAwesomeFunction(someComplexObject);
console.log(someComplexObject); // Object {member1:"gold",member2:"wood"}
Functions - Arguments
▪ Complex arguments always passed by reference
▪ Arrays, Objects, Functions
▪ Changing argument value => NOT visible outside function scope
function myAwesomeFunction(someComplexObject){
console.log(someComplexObject); // Object {member1:"gold",member2:"silver"}
someComplexObject = {superMember:"Titanium"};
console.log(someComplexObject); // Object {superMember:"Titanium"}
}
var someComplexObject = {member1:"gold",member2:"silver"};
console.log(someComplexObject)// Object {member1:"gold",member2:"silver"}
myAwesomeFunction(someComplexObject);
console.log(someComplexObject); // Object {member1:"gold",member2:"silver"}
Functions - Multiple Arguments
▪ Array-like object to iterate through arguments
▪ Can pass any number of arguments (overloading-ish)
function myAwesomerFunction(firstNumber){
var result = "" + firstNumber;
for(var i = 1; i < arguments.length; i++) {
result += "," + arguments[i];
}
console.log(result);
}
var myFirstNumber = 99;
myAwesomerFunction(myFirstNumber); // 99
myAwesomerFunction(myFirstNumber,100); // 99,100
myAwesomerFunction(myFirstNumber,100,101); // 99,100,101
Functions - Closures
▪ Powerful JavaScript feature
▪ Closure = nested function
▪ Inner function can access all variables and functions of outer function
▪ Inner function can access scope of outer function
▪ Outer function CANNOT access any variable or function of inner function
▪ Encapsulation of variables and functions of inner function
Functions - Closures
▪ A simple example
var outerCarFunction = function(outerMake) {
var getInnerMake = function() {
return outerMake; //Inner function has access to outer function variables
}
return getInnerMake; //Expose inner method to outer scope
};
var myCar = outerCarFunction("Beamer, Benz or Bentley");
console.log(myCar()); // Beamer, Benz or Bentley
Functions - Closures
▪ A more complex example
var createCar = function(manufacturer,model) {
return {
setManufacturer: function(newManufacturer) {
manufacturer = newManufacturer;
},
getManufacturer:function(){
return manufacturer;
},
setModel: function(newModel) {
model = newModel;
},
getModel: function(){
return model;
}};
}
Functions - Closures
▪ A more complex example (2)
var car = createCar("Crappy Co.","Ruster");
console.log(car.getManufacturer());// Crappy Co.
console.log(car.getModel()); // Ruster
car.setManufacturer("Bugatti");
car.setModel("Veyron");
console.log(car.getManufacturer());// Bugatti
console.log(car.getModel()); // Veyron
Objects
▪ JavaScript is designed to be Objects-based
▪ Objects can have properties
▪ Objects can have methods
▪ Use predefined objects or create your own
▪ Objects are also associative arrays (basic maps)
var movie = new Object(); // or var movie = {};
movie.title = "Sharknado";
movie.rating = "Utter crap";
var movie = new Object(); // or var movie = {};
movie["title"] = "Sharknado";
movie["rating"] = "Utter crap";
Objects
▪ Creating objects
▪ Using literals
▪ Using a constructor function
var movie = {title:”Sharknado”,rating:”Utter crap”};
function Movie(title,rating){
this.title = title;
this.rating = rating;
};
var sharknado = new Movie("Sharknado","Utter crap");
Prototypical inheritance
▪ No classes in JavaScript
▪ JavaScript uses object linking
▪ Also known as prototypes
▪ Multiple ways to create a prototype
▪ Object.create()
▪ Constructor
▪ Can have a performance impact
▪ Never extend native prototypes. For example Object.prototype
Prototypical inheritance - Object.create()
var baseAnimal = {
hasTail:true,
numberOfLegs:4,
makeSound: function(){
return "Roar";
}
};
console.log(baseAnimal.makeSound()); // Roar
var spider = Object.create(baseAnimal);
spider.hasTail = false;
spider.numberOfLegs = 8;
spider.makeSound = function(){return "Kill it, with fire!"};
console.log(spider); // Object {hasTail: false, numberOfLegs: 8, makeSound: function,
hasTail: true, numberOfLegs: 4…}
console.log(spider.makeSound()); // Kill it, with fire!
Prototypical inheritance - Constructor
var baseAnimal = { hasTail:true, numberOfLegs:4, makeSound: function(){ return
"Roar";}};
function Spider(){
this.hasTail = false;
this.numberOfLegs = 8;
this.makeSound = function(){return "Kill it, with fire!"};
};
Spider.prototype = baseAnimal;
var spider = new Spider();
console.log(spider); // Object {hasTail: false, numberOfLegs: 8, makeSound: function,
hasTail: true, numberOfLegs: 4…}
console.log(spider.makeSound()); // Kill it, with fire!
Equality
▪ 2 ways of determining equality of 2 objects
▪ Abstract equality
▪ Attempts an automatic type conversion, then compare
▪ Error prone, avoid whenever possible
▪ Strict equality
▪ No automatic type conversion, return false when object not of same type
x == y
x === y
Equality
▪ Equality only works on primitives & same object references
▪ Does not apply to complex objects, no traversal of properties
var developer = {totallyAwesome:true};
var architect = {totallyAwesome:true};
var manager = {totallyAwesome:false};
console.log(developer == manager);// false
console.log(developer === manager);// false
console.log(developer == architect);// false
console.log(developer === architect);// false
console.log(developer == developer);// true, same object reference
console.log(developer === developer);// true, same object reference
Equality - Abstract vs. strict equality
x y == ===
undefined undefined true true
null null true true
true true true true
false false true true
“0rd1n4 r0ck5” “0rd1n4 r0ck5” true true
{member:”one”} x true true
0 0 true true
Equality - Abstract vs. strict equality (2)
x y == ===
0 false true false
“” false true false
“” 0 true false
“0” 0 true false
“17” 17 true false
[1,2] “1,2” true false
null undefined true false
Equality - Abstract vs. strict equality (3)
x y == ===
null false false false
undefined false false false
{member:”one”} {member:”one”} false false
0 null false false
0 NaN false false
“0rd1n4 r0ck5” NaN false false
NaN NaN false false
JavaScript Basics & Best Practices
Part 3: Best Practices for enterprise applications
Best Practices #1
▪ Use JSLint / JSHint
▪ Automatically detect problems in your JavaScript code
▪ Strict equality
▪ Trailing comma
▪ Missing semicolon
▪ Undeclared variables
▪ ...
▪ Available in the better JS IDE
▪ Plugins available for CI environments
Best Practices #2
▪ Use a code formatter
▪ Code should be easy to read
▪ Team standard
▪ Easy to spot potential problems in your code
▪ Missing semicolon
▪ Trailing comma
▪ Available by default in the better JS IDE
Best Practices #3
▪ Never use inline <script>
▪ Always use an external .js file
▪ Separation of concerns
▪ Easier to maintain
▪ Reusability
▪ Inline scripts cannot be cached
▪ Inline scripts block the browser while processing JavaScript
Best Practices #4
▪ Use strict mode
▪ Indicate that code should execute in strict mode
▪ No undeclared variables
▪ No defining a variable multiple times
▪ No duplication of parameters
▪ File or function scope
▪ ECMAScript 5+ only
“use strict”
Best Practices #5
▪ Do not use native Array.sort()
▪ Quirky behaviour in some browsers
▪ Converts all items to strings by default and sorts them alphabetically
Best Practices #6
▪ eval() is evil
▪ Takes any string containing js code, compiles it and runs it
▪ Usually used for
▪ Serialization of objects
▪ Parsing of user input
▪ Problems
▪ Will try to convert any string into an object
▪ Slow
▪ Difficult to debug
Best Practices #7
▪ Beware of console.log()
▪ Quirky behaviour in some version of IE (8 and under)
▪ Will crash your application when not using developer tools.. DAFUQ?!!!
▪ Monkey patches available
▪ Remove console.log() statements from production code automatically
▪ Using grunt uglify plugin
Best Practices #8
▪ Concatenate your separate JavaScript files
▪ Concatenation = making 1 big file out of multiple smaller ones
▪ Less HTTP requests = less overhead bandwidth
▪ HTTP allows only up to 4 concurrent downloads
▪ Pitfall: has an impact on caching strategies
▪ Make 1 file per module your application uses
▪ Automate using grunt plugin
Best Practices #9
▪ Minify your JavaScript files
▪ Minification = Removing unnecessary chars from .js file
▪ Whitespaces, newlines, comments, ..
▪ Minification essentially removes obsolete bytes from the file
▪ Faster download
▪ More code = more optimization
▪ Great in conjunction with concatenation
▪ Automate using grunt plugin
Best Practices #10
▪ Enable Gzip compression on your server
▪ Often forgotten
▪ Easiest way to compress your files
▪ Save a lot of bandwidth
Best Practices #11
▪ Use lodash
▪ Lodash = fork of underscore with more features
▪ Functional programming library
▪ Abstraction layer for many quirky JavaScript features
▪ Sameness
▪ Collections
▪ ...
▪ Makes code more concise
▪ Write less code, write less bugs
Best Practices #12
▪ Use grunt
▪ Automate building your JavaScript code
▪ 1 Configuration file
▪ Create build workflow
▪ Many plugins
▪ Minify
▪ Obfuscate
▪ Concatenate
Best Practices #13
▪ Use bower
▪ External dependency management tool
▪ Only 1 configuration file
{
"name": "app-name",
"version": "0.0.1",
"dependencies": {
"sass-bootstrap": "~3.0.0",
"modernizr": "~2.6.2",
"jquery": "~1.10.2"
},
"private": true
}
Best Practices #14
▪ Use modernizr
▪ Automatically detect features of the browser used
▪ Detect HTML5 / CSS3 features
▪ Provide fallbacks for older browsers
Sources
▪ Websites
▪ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/JavaScript_Overview
▪ http://www.ecma-international.org/publications/standards/Ecma-262.htm
▪ http://addyosmani.com/blog/
▪ http://dailyjs.com/
▪ http://webcomponents.org/
▪ http://www.quirksmode.org/js/events_order.html
▪ Books
▪ Javascript: The good parts (http://shop.oreilly.com/product/9780596517748.do)
▪ Understanding ECMAScript 6 (https://leanpub.com/understandinges6/read)
▪ Effective JavaScript (http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)
▪ You don’t know JS (http://www.amazon.com/You-Dont-Know-JS-Prototypes-ebook/dp/B00LPUIB9G)
▪ Head First JavaScript (http://www.amazon.com/dp/144934013X)

JavaScript Basics and Best Practices - CC FE & UX

  • 1.
    JavaScript Basics &Best Practices Competence Center Front-end & UX Dennis Jaamann Front-end developer
  • 2.
    Overview ▪ Part 1:Introduction ▪ What is JavaScript? ▪ How a JavaScript engine works ▪ Language features ▪ The future of JavaScript
  • 3.
    Overview ▪ Part 2:The Basics ▪ Types, variables, constants and literals ▪ Expressions and operators ▪ Statements ▪ Functions ▪ Objects ▪ Prototypical inheritance ▪ Equality
  • 4.
    Overview ▪ Part 3:Best Practices for enterprise apps
  • 5.
    JavaScript Basics &Best Practices Part 1: Introduction
  • 6.
    What is JavaScript?According to java devs ▪ Works in all browsers except IE ▪ A crappy version of Java ▪ No type safety ▪ Something to stay miles away from ▪ JavaScript sucks *ss (1) (1) = Actual wording of most Java developers, presenter cannot be held accountable for harshness thereof
  • 7.
    What is JavaScript?Really ▪ Invented by Brendan Eich (1995) ▪ Former CTO / CEO of mozilla ▪ Cross-platform ▪ Object based ▪ Dynamic ▪ Scripting language ▪ Currently ECMA-262 (ECMAScript 5) ▪ Web APIs (DOM, ..)
  • 8.
    How a JavaScriptengine works ▪ Virtual machine ▪ Interpret and execute JavaScript ▪ Most common in browsers ▪ For example: Google V8 engine
  • 9.
    Language features -The bad ▪ Easy to introduce globals = root of all evil ▪ Automatic line termination ▪ Semicolons automatically inserted by interpreter ▪ Can lead to quirky behavior ▪ No warning ▪ Object equality and Object comparison ▪ Error prone due to dynamically typed objects ▪ Type coercion happens automagically (= auto casting)
  • 10.
    Language features -The good ▪ Everything is an Object ▪ Including functions ▪ Objects are loosely typed ▪ Every object can be assigned any value ▪ Objects are dynamic ▪ Can change type @ runtime ▪ Add members on the fly ▪ Object literals
  • 11.
    The future ofJavaScript ▪ ECMAScript 6 ▪ Classes ▪ Modules ▪ Promises ▪ http://kangax.github.io/compat-table/es6/ ▪ WebComponents ▪ Extend HTML with your own components ▪ Already available through usage of Polymer
  • 12.
    JavaScript Basics &Best Practices Part 2: The basics
  • 13.
    Types, variables, constantsand literals - Types ▪ 5 primitive types in JavaScript Type Possible values Number 1337, 3.14 String “JavaScript sucks *ss according to java devs” Boolean true, false null null undefined undefined
  • 14.
    Types, variables, constantsand literals - Types ▪ 2 complex types in JavaScript ▪ Object ▪ Constructor ▪ Members ▪ Inheritance-like behavior through prototypes ▪ Function ▪ Every function is a new instance of the Function object ▪ Block of code designed to perform a specific task
  • 15.
    Types, variables, constantsand literals - Types ▪ null vs. undefined ▪ null: value that can be assigned to a variable to indicate an empty value ▪ undefined: value of a variable that has been declared but has not been assigned a value var someNullifiedVariable = null; console.log(someNullifiedVariable); // null console.log(typeof someNullifiedVariable); // Object var someUndefinedVariable; console.log(someUndefinedVariable); // undefined console.log(typeof someNullifiedVariable); // undefined
  • 16.
    Types, variables, constantsand literals - Variables ▪ Declaring a variable ▪ The good way ▪ Use var keyword ▪ Variable always declared on current scope ▪ The evil way ▪ No keyword ▪ Variable always declared on global scope ▪ Warning in strict mode var someNumber = 42; // The good way someOtherNumber = 42 // The evil way
  • 17.
    Types, variables, constantsand literals - Variables ▪ Variable scope ▪ Global scope ▪ Variable declared outside of any function ▪ Accessible to any other code in the document ▪ Function scope ▪ Variable declared inside of any function ▪ Accessible to function and all inner functions ▪ Block scope ▪ Variable declared within block is local to containing function
  • 18.
    Types, variables, constantsand literals - Variables if(true){ var someGlobalVar = 1337; //global scope, since block is outside of any function } function someFunction(){ var someLocalVar = 9000; // function scope function someInnerFunction(){ console.log(someLocalVar); //9000 someLocalVar = 90210; } someInnerFunction(); console.log(someLocalVar); //90210 } console.log(someGlobalVar); //1337 someFunction(); console.log(someLocalVar); //Uncaught ReferenceError
  • 19.
    Types, variables, constantsand literals - Constants ▪ Defining a constant const myTotallyAwesomeConstant = 3; console.log(myTotallyAwesomeConstant); // 3 const myTotallyAwesomeConstant = 1337; console.log(myTotallyAwesomeConstant); // 3
  • 20.
    Types, variables, constantsand literals - Literals ▪ Defining literals ▪ Represent fixed values, not variables ▪ Literally providing values in code var myAwesomeArray = [1,2,"test",true]; var myAwesomeObject = {firstMember:1,secondMember:2}; var myAwesomeBoolean = true; var myAwesomeNumber = 1337; var myAwesomeString = "Ordina is too awesome"; console.log(myAwesomeArray.toString()); // 1,2,test,true console.log(myAwesomeObject); // Object {firstMember: 1, secondMember: 2} console.log(myAwesomeBoolean); // true console.log(myAwesomeNumber); // 1337 console.log(myAwesomeString); // Ordina is too awesome
  • 21.
    Expressions and operators ▪Expressions and operators very similar to Java ▪ Precedence also similar Assignment Comparison Arithmetic Bitwise Logical String += -= *= /= %= <<= >>= >>>= &= ^= |= == != === !== > >= < <= % ++ -- - & | ^ ~ << >> >>> && || ! + +=
  • 22.
    Statements ▪ Statements alsovery similar to Java Conditional Loops Exceptions if(){}else{} switch(){} while(){}; do{}while(); for(){}; continue; break throw try{}catch(){};
  • 23.
    Functions ▪ Fundamental buildingblocks in JavaScript ▪ Perform a set of statements ▪ Calculate a value ▪ Perform a task ▪ Define on the scope from where you want to call it
  • 24.
    Functions - Arguments ▪Primitive arguments always passed by value (copy) function myAwesomeFunction(somePrimitiveNumber){ console.log(somePrimitiveNumber); // 99 somePrimitiveNumber = 1337; console.log(somePrimitiveNumber); // 1337 } var someNumber = 99; console.log(someNumber)// 99 myAwesomeFunction(someNumber); console.log(someNumber); // 99
  • 25.
    Functions - Arguments ▪Complex arguments always passed by reference ▪ Arrays, Objects, Functions ▪ Changing value of any property => visible outside function scope function myAwesomeFunction(someComplexObject){ console.log(someComplexObject); // Object {member1:"gold",member2:"silver"} someComplexObject.member2 = "wood"; console.log(someComplexObject); // Object {member1:"gold",member2:"wood"} } var someComplexObject = {member1:"gold",member2:"silver"}; console.log(someComplexObject)// Object {member1:"gold",member2:"silver"} myAwesomeFunction(someComplexObject); console.log(someComplexObject); // Object {member1:"gold",member2:"wood"}
  • 26.
    Functions - Arguments ▪Complex arguments always passed by reference ▪ Arrays, Objects, Functions ▪ Changing argument value => NOT visible outside function scope function myAwesomeFunction(someComplexObject){ console.log(someComplexObject); // Object {member1:"gold",member2:"silver"} someComplexObject = {superMember:"Titanium"}; console.log(someComplexObject); // Object {superMember:"Titanium"} } var someComplexObject = {member1:"gold",member2:"silver"}; console.log(someComplexObject)// Object {member1:"gold",member2:"silver"} myAwesomeFunction(someComplexObject); console.log(someComplexObject); // Object {member1:"gold",member2:"silver"}
  • 27.
    Functions - MultipleArguments ▪ Array-like object to iterate through arguments ▪ Can pass any number of arguments (overloading-ish) function myAwesomerFunction(firstNumber){ var result = "" + firstNumber; for(var i = 1; i < arguments.length; i++) { result += "," + arguments[i]; } console.log(result); } var myFirstNumber = 99; myAwesomerFunction(myFirstNumber); // 99 myAwesomerFunction(myFirstNumber,100); // 99,100 myAwesomerFunction(myFirstNumber,100,101); // 99,100,101
  • 28.
    Functions - Closures ▪Powerful JavaScript feature ▪ Closure = nested function ▪ Inner function can access all variables and functions of outer function ▪ Inner function can access scope of outer function ▪ Outer function CANNOT access any variable or function of inner function ▪ Encapsulation of variables and functions of inner function
  • 29.
    Functions - Closures ▪A simple example var outerCarFunction = function(outerMake) { var getInnerMake = function() { return outerMake; //Inner function has access to outer function variables } return getInnerMake; //Expose inner method to outer scope }; var myCar = outerCarFunction("Beamer, Benz or Bentley"); console.log(myCar()); // Beamer, Benz or Bentley
  • 30.
    Functions - Closures ▪A more complex example var createCar = function(manufacturer,model) { return { setManufacturer: function(newManufacturer) { manufacturer = newManufacturer; }, getManufacturer:function(){ return manufacturer; }, setModel: function(newModel) { model = newModel; }, getModel: function(){ return model; }}; }
  • 31.
    Functions - Closures ▪A more complex example (2) var car = createCar("Crappy Co.","Ruster"); console.log(car.getManufacturer());// Crappy Co. console.log(car.getModel()); // Ruster car.setManufacturer("Bugatti"); car.setModel("Veyron"); console.log(car.getManufacturer());// Bugatti console.log(car.getModel()); // Veyron
  • 32.
    Objects ▪ JavaScript isdesigned to be Objects-based ▪ Objects can have properties ▪ Objects can have methods ▪ Use predefined objects or create your own ▪ Objects are also associative arrays (basic maps) var movie = new Object(); // or var movie = {}; movie.title = "Sharknado"; movie.rating = "Utter crap"; var movie = new Object(); // or var movie = {}; movie["title"] = "Sharknado"; movie["rating"] = "Utter crap";
  • 33.
    Objects ▪ Creating objects ▪Using literals ▪ Using a constructor function var movie = {title:”Sharknado”,rating:”Utter crap”}; function Movie(title,rating){ this.title = title; this.rating = rating; }; var sharknado = new Movie("Sharknado","Utter crap");
  • 34.
    Prototypical inheritance ▪ Noclasses in JavaScript ▪ JavaScript uses object linking ▪ Also known as prototypes ▪ Multiple ways to create a prototype ▪ Object.create() ▪ Constructor ▪ Can have a performance impact ▪ Never extend native prototypes. For example Object.prototype
  • 35.
    Prototypical inheritance -Object.create() var baseAnimal = { hasTail:true, numberOfLegs:4, makeSound: function(){ return "Roar"; } }; console.log(baseAnimal.makeSound()); // Roar var spider = Object.create(baseAnimal); spider.hasTail = false; spider.numberOfLegs = 8; spider.makeSound = function(){return "Kill it, with fire!"}; console.log(spider); // Object {hasTail: false, numberOfLegs: 8, makeSound: function, hasTail: true, numberOfLegs: 4…} console.log(spider.makeSound()); // Kill it, with fire!
  • 36.
    Prototypical inheritance -Constructor var baseAnimal = { hasTail:true, numberOfLegs:4, makeSound: function(){ return "Roar";}}; function Spider(){ this.hasTail = false; this.numberOfLegs = 8; this.makeSound = function(){return "Kill it, with fire!"}; }; Spider.prototype = baseAnimal; var spider = new Spider(); console.log(spider); // Object {hasTail: false, numberOfLegs: 8, makeSound: function, hasTail: true, numberOfLegs: 4…} console.log(spider.makeSound()); // Kill it, with fire!
  • 37.
    Equality ▪ 2 waysof determining equality of 2 objects ▪ Abstract equality ▪ Attempts an automatic type conversion, then compare ▪ Error prone, avoid whenever possible ▪ Strict equality ▪ No automatic type conversion, return false when object not of same type x == y x === y
  • 38.
    Equality ▪ Equality onlyworks on primitives & same object references ▪ Does not apply to complex objects, no traversal of properties var developer = {totallyAwesome:true}; var architect = {totallyAwesome:true}; var manager = {totallyAwesome:false}; console.log(developer == manager);// false console.log(developer === manager);// false console.log(developer == architect);// false console.log(developer === architect);// false console.log(developer == developer);// true, same object reference console.log(developer === developer);// true, same object reference
  • 39.
    Equality - Abstractvs. strict equality x y == === undefined undefined true true null null true true true true true true false false true true “0rd1n4 r0ck5” “0rd1n4 r0ck5” true true {member:”one”} x true true 0 0 true true
  • 40.
    Equality - Abstractvs. strict equality (2) x y == === 0 false true false “” false true false “” 0 true false “0” 0 true false “17” 17 true false [1,2] “1,2” true false null undefined true false
  • 41.
    Equality - Abstractvs. strict equality (3) x y == === null false false false undefined false false false {member:”one”} {member:”one”} false false 0 null false false 0 NaN false false “0rd1n4 r0ck5” NaN false false NaN NaN false false
  • 42.
    JavaScript Basics &Best Practices Part 3: Best Practices for enterprise applications
  • 43.
    Best Practices #1 ▪Use JSLint / JSHint ▪ Automatically detect problems in your JavaScript code ▪ Strict equality ▪ Trailing comma ▪ Missing semicolon ▪ Undeclared variables ▪ ... ▪ Available in the better JS IDE ▪ Plugins available for CI environments
  • 44.
    Best Practices #2 ▪Use a code formatter ▪ Code should be easy to read ▪ Team standard ▪ Easy to spot potential problems in your code ▪ Missing semicolon ▪ Trailing comma ▪ Available by default in the better JS IDE
  • 45.
    Best Practices #3 ▪Never use inline <script> ▪ Always use an external .js file ▪ Separation of concerns ▪ Easier to maintain ▪ Reusability ▪ Inline scripts cannot be cached ▪ Inline scripts block the browser while processing JavaScript
  • 46.
    Best Practices #4 ▪Use strict mode ▪ Indicate that code should execute in strict mode ▪ No undeclared variables ▪ No defining a variable multiple times ▪ No duplication of parameters ▪ File or function scope ▪ ECMAScript 5+ only “use strict”
  • 47.
    Best Practices #5 ▪Do not use native Array.sort() ▪ Quirky behaviour in some browsers ▪ Converts all items to strings by default and sorts them alphabetically
  • 48.
    Best Practices #6 ▪eval() is evil ▪ Takes any string containing js code, compiles it and runs it ▪ Usually used for ▪ Serialization of objects ▪ Parsing of user input ▪ Problems ▪ Will try to convert any string into an object ▪ Slow ▪ Difficult to debug
  • 49.
    Best Practices #7 ▪Beware of console.log() ▪ Quirky behaviour in some version of IE (8 and under) ▪ Will crash your application when not using developer tools.. DAFUQ?!!! ▪ Monkey patches available ▪ Remove console.log() statements from production code automatically ▪ Using grunt uglify plugin
  • 50.
    Best Practices #8 ▪Concatenate your separate JavaScript files ▪ Concatenation = making 1 big file out of multiple smaller ones ▪ Less HTTP requests = less overhead bandwidth ▪ HTTP allows only up to 4 concurrent downloads ▪ Pitfall: has an impact on caching strategies ▪ Make 1 file per module your application uses ▪ Automate using grunt plugin
  • 51.
    Best Practices #9 ▪Minify your JavaScript files ▪ Minification = Removing unnecessary chars from .js file ▪ Whitespaces, newlines, comments, .. ▪ Minification essentially removes obsolete bytes from the file ▪ Faster download ▪ More code = more optimization ▪ Great in conjunction with concatenation ▪ Automate using grunt plugin
  • 52.
    Best Practices #10 ▪Enable Gzip compression on your server ▪ Often forgotten ▪ Easiest way to compress your files ▪ Save a lot of bandwidth
  • 53.
    Best Practices #11 ▪Use lodash ▪ Lodash = fork of underscore with more features ▪ Functional programming library ▪ Abstraction layer for many quirky JavaScript features ▪ Sameness ▪ Collections ▪ ... ▪ Makes code more concise ▪ Write less code, write less bugs
  • 54.
    Best Practices #12 ▪Use grunt ▪ Automate building your JavaScript code ▪ 1 Configuration file ▪ Create build workflow ▪ Many plugins ▪ Minify ▪ Obfuscate ▪ Concatenate
  • 55.
    Best Practices #13 ▪Use bower ▪ External dependency management tool ▪ Only 1 configuration file { "name": "app-name", "version": "0.0.1", "dependencies": { "sass-bootstrap": "~3.0.0", "modernizr": "~2.6.2", "jquery": "~1.10.2" }, "private": true }
  • 56.
    Best Practices #14 ▪Use modernizr ▪ Automatically detect features of the browser used ▪ Detect HTML5 / CSS3 features ▪ Provide fallbacks for older browsers
  • 57.
    Sources ▪ Websites ▪ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/JavaScript_Overview ▪http://www.ecma-international.org/publications/standards/Ecma-262.htm ▪ http://addyosmani.com/blog/ ▪ http://dailyjs.com/ ▪ http://webcomponents.org/ ▪ http://www.quirksmode.org/js/events_order.html ▪ Books ▪ Javascript: The good parts (http://shop.oreilly.com/product/9780596517748.do) ▪ Understanding ECMAScript 6 (https://leanpub.com/understandinges6/read) ▪ Effective JavaScript (http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182) ▪ You don’t know JS (http://www.amazon.com/You-Dont-Know-JS-Prototypes-ebook/dp/B00LPUIB9G) ▪ Head First JavaScript (http://www.amazon.com/dp/144934013X)