Transcript
Page 1: JavaScript Basics and Best Practices - CC FE & UX

JavaScript Basics & Best Practices

Competence Center Front-end & UX

Dennis JaamannFront-end developer

Page 2: JavaScript Basics and Best Practices - CC FE & UX

Overview

▪ Part 1: Introduction

▪ What is JavaScript?

▪ How a JavaScript engine works

▪ Language features

▪ The future of JavaScript

Page 3: JavaScript Basics and Best Practices - CC FE & UX

Overview

▪ Part 2: The Basics

▪ Types, variables, constants and literals

▪ Expressions and operators

▪ Statements

▪ Functions

▪ Objects

▪ Prototypical inheritance

▪ Equality

Page 4: JavaScript Basics and Best Practices - CC FE & UX

Overview

▪ Part 3: Best Practices for enterprise apps

Page 5: JavaScript Basics and Best Practices - CC FE & UX

JavaScript Basics & Best Practices

Part 1: Introduction

Page 6: JavaScript Basics and Best Practices - CC FE & UX

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

Page 7: JavaScript Basics and Best Practices - CC FE & UX

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, ..)

Page 8: JavaScript Basics and Best Practices - CC FE & UX

How a JavaScript engine works

▪ Virtual machine▪ Interpret and execute JavaScript▪ Most common in browsers▪ For example: Google V8 engine

Page 9: JavaScript Basics and Best Practices - CC FE & UX

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)

Page 10: JavaScript Basics and Best Practices - CC FE & UX

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

Page 11: JavaScript Basics and Best Practices - CC FE & UX

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

Page 12: JavaScript Basics and Best Practices - CC FE & UX

JavaScript Basics & Best Practices

Part 2: The basics

Page 13: JavaScript Basics and Best Practices - CC FE & UX

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

Page 14: JavaScript Basics and Best Practices - CC FE & UX

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

Page 15: JavaScript Basics and Best Practices - CC FE & UX

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); // nullconsole.log(typeof someNullifiedVariable); // Object

var someUndefinedVariable;console.log(someUndefinedVariable); // undefinedconsole.log(typeof someNullifiedVariable); // undefined

Page 16: JavaScript Basics and Best Practices - CC FE & UX

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 waysomeOtherNumber = 42 // The evil way

Page 17: JavaScript Basics and Best Practices - CC FE & UX

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

Page 18: JavaScript Basics and Best Practices - CC FE & UX

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

Page 19: JavaScript Basics and Best Practices - CC FE & UX

Types, variables, constants and literals - Constants

▪ Defining a constant

const myTotallyAwesomeConstant = 3;console.log(myTotallyAwesomeConstant); // 3

const myTotallyAwesomeConstant = 1337;console.log(myTotallyAwesomeConstant); // 3

Page 20: JavaScript Basics and Best Practices - CC FE & UX

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

Page 21: JavaScript Basics and Best Practices - CC FE & UX

Expressions and operators

▪ Expressions and operators very similar to Java▪ Precedence also similar

Assignment Comparison Arithmetic Bitwise Logical String

+=-=*=/=%=<<=>>=>>>=&=^=|=

==!====!==>>=<<=

%++---

&|^~<<>>>>>

&&||!

++=

Page 22: JavaScript Basics and Best Practices - CC FE & UX

Statements

▪ Statements also very similar to Java

Conditional Loops Exceptions

if(){}else{}

switch(){}

while(){};

do{}while();

for(){};

continue;

break

throw

try{}catch(){};

Page 23: JavaScript Basics and Best Practices - CC FE & UX

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

Page 24: JavaScript Basics and Best Practices - CC FE & UX

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

Page 25: JavaScript Basics and Best Practices - CC FE & UX

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"}

Page 26: JavaScript Basics and Best Practices - CC FE & UX

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"}

Page 27: JavaScript Basics and Best Practices - CC FE & UX

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

Page 28: JavaScript Basics and Best Practices - CC FE & UX

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

Page 29: JavaScript Basics and Best Practices - CC FE & UX

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

Page 30: JavaScript Basics and Best Practices - CC FE & UX

Functions - Closures

▪ A more complex examplevar createCar = function(manufacturer,model) { return {

setManufacturer: function(newManufacturer) { manufacturer = newManufacturer;

}, getManufacturer:function(){ return manufacturer; },

setModel: function(newModel) { model = newModel;

}, getModel: function(){ return model; }};}

Page 31: JavaScript Basics and Best Practices - CC FE & UX

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());// Bugatticonsole.log(car.getModel()); // Veyron

Page 32: JavaScript Basics and Best Practices - CC FE & UX

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";

Page 33: JavaScript Basics and Best Practices - CC FE & UX

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");

Page 34: JavaScript Basics and Best Practices - CC FE & UX

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

Page 35: JavaScript Basics and Best Practices - CC FE & UX

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!

Page 36: JavaScript Basics and Best Practices - CC FE & UX

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!

Page 37: JavaScript Basics and Best Practices - CC FE & UX

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

Page 38: JavaScript Basics and Best Practices - CC FE & UX

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);// falseconsole.log(developer === manager);// falseconsole.log(developer == architect);// falseconsole.log(developer === architect);// falseconsole.log(developer == developer);// true, same object referenceconsole.log(developer === developer);// true, same object reference

Page 39: JavaScript Basics and Best Practices - CC FE & UX

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

Page 40: JavaScript Basics and Best Practices - CC FE & UX

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

Page 41: JavaScript Basics and Best Practices - CC FE & UX

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

Page 42: JavaScript Basics and Best Practices - CC FE & UX

JavaScript Basics & Best Practices

Part 3: Best Practices for enterprise applications

Page 43: JavaScript Basics and Best Practices - CC FE & UX

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

Page 44: JavaScript Basics and Best Practices - CC FE & UX

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

Page 45: JavaScript Basics and Best Practices - CC FE & UX

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

Page 46: JavaScript Basics and Best Practices - CC FE & UX

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”

Page 47: JavaScript Basics and Best Practices - CC FE & UX

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

Page 48: JavaScript Basics and Best Practices - CC FE & UX

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

Page 49: JavaScript Basics and Best Practices - CC FE & UX

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

Page 50: JavaScript Basics and Best Practices - CC FE & UX

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

Page 51: JavaScript Basics and Best Practices - CC FE & UX

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

Page 52: JavaScript Basics and Best Practices - CC FE & UX

Best Practices #10

▪ Enable Gzip compression on your server

▪ Often forgotten

▪ Easiest way to compress your files

▪ Save a lot of bandwidth

Page 53: JavaScript Basics and Best Practices - CC FE & UX

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

Page 54: JavaScript Basics and Best Practices - CC FE & UX

Best Practices #12

▪ Use grunt

▪ Automate building your JavaScript code

▪ 1 Configuration file

▪ Create build workflow

▪ Many plugins

▪ Minify

▪ Obfuscate

▪ Concatenate

Page 55: JavaScript Basics and Best Practices - CC FE & UX

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}

Page 56: JavaScript Basics and Best Practices - CC FE & UX

Best Practices #14

▪ Use modernizr

▪ Automatically detect features of the browser used

▪ Detect HTML5 / CSS3 features

▪ Provide fallbacks for older browsers

Page 57: JavaScript Basics and Best Practices - CC FE & UX

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)


Top Related