SlideShare a Scribd company logo
1 of 57
Download to read offline
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)

More Related Content

What's hot

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 

What's hot (20)

Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Js ppt
Js pptJs ppt
Js ppt
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
jQuery
jQueryjQuery
jQuery
 
Php
PhpPhp
Php
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 

Similar to JavaScript Basics and Best Practices - CC FE & UX

JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
Edureka!
 

Similar to JavaScript Basics and Best Practices - CC FE & UX (20)

Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptx
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Lagergren jvmls-2013-final
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-final
 
WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Java script
Java scriptJava script
Java script
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi
 
JavaScript
JavaScriptJavaScript
JavaScript
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 

More from JWORKS powered by Ordina

More from JWORKS powered by Ordina (20)

Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & Web
 
Lagom in Practice
Lagom in PracticeLagom in Practice
Lagom in Practice
 
Netflix OSS and HATEOAS deployed on production - JavaLand
Netflix OSS and HATEOAS deployed on production - JavaLandNetflix OSS and HATEOAS deployed on production - JavaLand
Netflix OSS and HATEOAS deployed on production - JavaLand
 
Cc internet of things @ Thomas More
Cc internet of things @ Thomas MoreCc internet of things @ Thomas More
Cc internet of things @ Thomas More
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
An introduction to Cloud Foundry
An introduction to Cloud FoundryAn introduction to Cloud Foundry
An introduction to Cloud Foundry
 
Cc internet of things LoRa and IoT - Innovation Enablers
Cc internet of things   LoRa and IoT - Innovation Enablers Cc internet of things   LoRa and IoT - Innovation Enablers
Cc internet of things LoRa and IoT - Innovation Enablers
 
Mongodb @ vrt
Mongodb @ vrtMongodb @ vrt
Mongodb @ vrt
 
Mongo db intro.pptx
Mongo db intro.pptxMongo db intro.pptx
Mongo db intro.pptx
 
Big data document and graph d bs - couch-db and orientdb
Big data  document and graph d bs - couch-db and orientdbBig data  document and graph d bs - couch-db and orientdb
Big data document and graph d bs - couch-db and orientdb
 
Big data key-value and column stores redis - cassandra
Big data  key-value and column stores redis - cassandraBig data  key-value and column stores redis - cassandra
Big data key-value and column stores redis - cassandra
 
Hadoop bootcamp getting started
Hadoop bootcamp getting startedHadoop bootcamp getting started
Hadoop bootcamp getting started
 
Big data elasticsearch practical
Big data  elasticsearch practicalBig data  elasticsearch practical
Big data elasticsearch practical
 
Intro to cassandra
Intro to cassandraIntro to cassandra
Intro to cassandra
 
Android wear - CC Mobile
Android wear - CC MobileAndroid wear - CC Mobile
Android wear - CC Mobile
 
Clean Code - A&BP CC
Clean Code - A&BP CCClean Code - A&BP CC
Clean Code - A&BP CC
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 

Recently uploaded

call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
F
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
ayvbos
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
gajnagarg
 

Recently uploaded (20)

Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
 
Leading-edge AI Image Generators of 2024
Leading-edge AI Image Generators of 2024Leading-edge AI Image Generators of 2024
Leading-edge AI Image Generators of 2024
 
一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
💚 Call Girls Bahraich 9332606886 High Profile Call Girls You Can Get The S...
💚 Call Girls Bahraich   9332606886  High Profile Call Girls You Can Get The S...💚 Call Girls Bahraich   9332606886  High Profile Call Girls You Can Get The S...
💚 Call Girls Bahraich 9332606886 High Profile Call Girls You Can Get The S...
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Down bad crying at the gym t shirtsDown bad crying at the gym t shirts
Down bad crying at the gym t shirtsDown bad crying at the gym t shirtsDown bad crying at the gym t shirtsDown bad crying at the gym t shirts
Down bad crying at the gym t shirtsDown bad crying at the gym t shirts
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 

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 JavaScript engine 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 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
  • 12. JavaScript Basics & Best Practices Part 2: The basics
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. Types, variables, constants and literals - Constants ▪ Defining a constant const myTotallyAwesomeConstant = 3; console.log(myTotallyAwesomeConstant); // 3 const myTotallyAwesomeConstant = 1337; console.log(myTotallyAwesomeConstant); // 3
  • 20. 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
  • 21. Expressions and operators ▪ Expressions and operators very similar to Java ▪ Precedence also similar Assignment Comparison Arithmetic Bitwise Logical String += -= *= /= %= <<= >>= >>>= &= ^= |= == != === !== > >= < <= % ++ -- - & | ^ ~ << >> >>> && || ! + +=
  • 22. Statements ▪ Statements also very similar to Java Conditional Loops Exceptions if(){}else{} switch(){} while(){}; do{}while(); for(){}; continue; break throw try{}catch(){};
  • 23. 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
  • 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 - 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
  • 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 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";
  • 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 ▪ 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
  • 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 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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
  • 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)