SlideShare uma empresa Scribd logo
1 de 57
Baixar para ler 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)

Mais conteúdo relacionado

Mais procurados (20)

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Jquery
JqueryJquery
Jquery
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
React js
React jsReact js
React js
 

Semelhante a JavaScript Basics and Best Practices - CC FE & UX

Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptxlekhacce
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxsandeshshahapur
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Lagergren jvmls-2013-final
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-finalMarcus Lagergren
 
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)Igor Khotin
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v22x026
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topicsRajesh Verma
 
"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 SemenistyiBinary Studio
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 

Semelhante a 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
 

Mais de JWORKS powered by Ordina

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 & WebJWORKS powered by Ordina
 
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 - JavaLandJWORKS powered by Ordina
 
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 JWORKS powered by Ordina
 
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 orientdbJWORKS powered by Ordina
 
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 - cassandraJWORKS powered by Ordina
 
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 2014JWORKS powered by Ordina
 

Mais de 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
 

Último

Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.CarlotaBedoya1
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.soniya singh
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Servicegwenoracqe6
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.soniya singh
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 

Último (20)

Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
INDIVIDUAL ASSIGNMENT #3 CBG, PRESENTATION.
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
 
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 

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)