ecma6 in 30 minutes
TRANSCRIPT
AboutMe• TechnicalLeaderandAgileCoach• Front-endDeveloper(testfirst!)• MobileDeveloper(HybridwithCordova,iOS,Android)• TechnologyEnthusiast• [email protected]• GSDguy
McGrawHillEducationisHiring
http://www.mheducation.com/careers
What'sNext?
ScotchStreamingandScaling11Feb2015www.meetup.com/mobiletea
Agenda• UsingECMA6today• ECMA6modules• VariablesscopingwithECMA6• ECMA6newcorefeatures(Array,String,Numbers,etc.)• HandlingdatawithMapsandSets• DestructuringArraysandObjects• HandlignexternaldatausingPromisesandDeferred
IspeakEcmaScript!https://github.com/GiorgioNatili/es6
SharpentheWeapons
WhereisJavaScript?
ModularJavaScript• Selfcontained• Avoidglobalscopepollution(globalscopeisnotevil!)• Keeptheprojectorganized• Improvecodereusability• HighlytestableandwelldefinedAPI
WhichOptions?
AMD
CommonJS
AMDModule(1/3)Simplereturnobjectasacollectionofname/valuepairs
define({color:"black",size:"unisize"});
AMD(2/3)Returnobjectwith"privacy"implementation
define(function(){//Dosetupworkherereturn{color:"black",size:"unisize"}});
AMD(3/3)Returnobjectwith"privacy"implementationanddependenciesmanagement
define(["./inventory","./currencies"],function(inventory,currencies){varcode="ye76hg";vargetPrice=function(){returncurrencies.getPrice(code);};
CommonJSModule(1/2)
Simpleplainfilethat"exports"featuresusingthe"module"variable(client.js)
varrest,mime,client;
rest=require('rest');mime=require('rest/interceptor/mime');
CommonJSModule(1/2)
Simpleplainfilethat"imports"features
importclientfromcollections;
client.doStuff();
Whowins?
idgafanimatedGIF
idgafanimatedGIF
idgafanimatedGIF
AMDtoCommonJSdefine(function(require,exports,module){
//PuttraditionalCommonJSmodulecontenthere
exports.randomize=function(input){returnshuffler.shuffle(input);
}
});
CommonJStoAMDConvertthecommonJSformattoabrowsercompatibleoneusing
browserify
$npminstall-gbrowserify
$browserifymain.js-obundle.js
ECMA6Modules• export,functionsandvariables
exportfunctionarea(radius){returnMath.PI*radius*radius;}exportPI=Math.PI;
• import,modules
Advantages• Compact,synchronoussyntax• Asynchronousloading• Conditionalmoduleinclusion• Promotecodemodularization• APIstyledevelopment
CanIusethemtoday?Kindaof...
wowanimatedGIF
ExperimentalEnvironments
LocalEnvironment• InstallNodeJSusingbrew
$ruby-e"$(curl-fsSLhttps://raw.github.com/Homebrew/homebrew/go/install)"$brewinstallnode
• Verifythatnpmininstalled
$npm
DevEnvironment(opt1)• Installyeomanglobally
$npminstallyo-g
• Installthees6nextyeomangenerator
DevEnvironment(opt2)
• Install6to5atranspilerabletoproducereadableECMA5codeECMA6
$npminstall-g6to5
DevEnvironment(opt3)
• Cloneaboilerplate
$gitclonehttps://github.com/davidjnelson/es6-boilerplate.git
• Installthedependencies
$npminstall
RunYourFirstTranspilation
excitedanimatedGIF
d
BrowsersSupport
GuessIE?
GuessIE?internetanimatedGIF
internetanimatedGIF
NewCoreFeatures
TheFutureof
TheFutureofJavaScript
fightanimatedGIF
fightanimatedGIF
Object.assingCopythebehaviorofanobjecttoanotherobjectwithoutusing
classesorprototypesinheritance.
varworker={};
varcanEat={food:'nothing',eat:function(){console.log(`eats$this.food`);//templatestring(partofES6)}};
Object.isObjectmethodtodeterminewhethertwovaluesarethesamevalue
likethestrictequalityoperator.
Object.is("foo","foo");//trueObject.is(window,window);//true
Object.is("foo","bar");//falseObject.is([],[]);//false
vartest={a:1};Object.is(test,test);//true
__proto__inobjectliterals
Changetheprototypeofanobjectliteral
varobj={__proto__:Array.prototype};
String.prototype.containsSearchforastringcontainedinastringfromaspecificposition
(optional)
varstr="TobeinBostonwiththesnowiscool.";
console.log(str.contains("Tobe"));//trueconsole.log(str.contains("question"));//falseconsole.log(str.contains("Chicago"));//falseconsole.log(str.contains("Tobe",1));//false
String.prototype.startsWithCheckfromaspecificindex(optional)ifastringstartswithaspecific
string
varstr="TobeinMiamiwhenthereisthesnowinBostonisbetter.";
console.log(str.startsWith("Tobe"));//trueconsole.log(str.startsWith("Tobe",2));//false
String.prototype.repeatRepeatandconcatenateastringaspecificamountoftimes.
varstr="ECMA6isprettycool.";
console.log(str.repeat(2));//ECMA6isprettycool.ECMA6isprettycool.
Array.prototype.fromCreateanArrayfromanarray-likeobjectoraniterableobject.
vartest=(function(){varargs=Array.from(arguments);returnargs;}(1,2,3));
console.log(test);//[1,2,3]
Array.prototype.findReturnthefirstoccurrenceinanArraythatsatisfiestheconditions
describedbythecallbackargument.
functionisPrime(element,index,array){varstart=2;while(start<=Math.sqrt(element)){if(element%start++<1)returnfalse;}return(element>1);}
IteratorsAniteratorhasamethodcallednext,thismethodreturnsanobject
withtwoproperties:valueanddone.
varit=['yo','ya','yes','now','then'].keys();
console.log(it.next().value,it.next().done);console.log(it.next().value,it.next().done);console.log(it.next().value,it.next().done);
console.log(it.next().value,it.next().done);//???
Array.prototype.keysReturnsaniterableobjectfromanArray.
varsequence=[1,4,5,8,2,6];
console.log(sequence.keys());//Iterator{}
Aniterableobjecthasanext()methodthatreturnanobjectwiththethevalueanddoneproperties.
Array.prototype.entriesReturnsanewArrayIteratorobjectthatcontainsthekey/valuepairs
foreachindexinthearray
vararr=['a','b','c'];vareArr=arr.entries();
varobj=eArr.next();while(!obj.done){console.log(obj.value);obj=eArr.next();
NumberConstantsUsefulconstantstodeterminethesmallestintervalbetweentwo
numbersandtheminimumandmaximumsafeintegers.
console.log(Number.EPSILON);console.log(Number.MAX_SAFE_INTEGER);console.log(Number.MIN_SAFE_INTEGER);
Number(static)Methods
CheckifanumberisNaN,infinite,integer,etc.
varnum=456;
console.log(Number.isFinite(num));//trueconsole.log(Number.isInteger(num));//trueconsole.log(Number.isNaN(num));//false
for...ofIteratesoveriterableobjects(includingArray,Map,Set,arguments
objectandsoon)ignoringinstanceandprototypeproperties
letarr=[3,5,7];arr.foo="hello";
for(variinarr){console.log(i);//"0","1","2","foo"}
for(variofarr){
Set+MapASetisasetofarbitraryvalues,aMapisakey/valuepairsbased
object;aSetdoesn’tallowduplicates//Setsvars=newSet();s.add("hello").add("goodbye").add("hello");
console.log(s.size);//2console.log(s.has("hello"));//true
console.dir(s);//add(),clear(),delete(),entries(),values(),forEach(),etc.
//Maps
ProxyProxiesenablecreationofobjectswiththefullrangeofbehaviors
availabletohostobjects
vartarget={age:1};varhandler={get:function(receiver,name){console.log(receiver)return`Hello,${name}!`;}};
varp=newProxy(target,handler);
TemplateStringsTemplatestringsaredefinedusingbackticks`,inside,youcanusea
dollarsignwithbracketstoinsertexecutablecodeorvariables.
varname='Giorgio',surname='Natili';vartemplate=`Hello!Mynameis${name}${surname}!`;console.log(template);//Hello!MynameisGiorgioNatili!
GeneratorsGeneratorsarefunctionsthatcanbeexitedandthenre-entered,eachcalltothenext()methodwillrunthebodyofthefunction.
function*idGenerator(){varindex=0,val='';while(true){index++;yieldval='UID'+index;}}
VariablesScopingFinallytheletkeywordallowustocreatescopesvariable.
for(leti=0;i<10;i++){console.log(i);}console.log(i);//iisnotdefined
if(true){(function(){varscoped='test';})();console.log(scoped);//scopedisnotdefined
DestructuringItreferstoakindofassignmentthatallowsyoutoassignthepropertiesofanarrayorobjecttovariablestoeffectively
matchvaluestovariablesorproperties.
var[x,y,z]=[1,2,3];//isequivalentto...varx=1,y=2,z=3;
let[x,y]=[1,2];console.log(x,y);//1,2
[x,y]=[y,x];//Swapthevaluesofxandy
SpreadsOperatorsRestparametersallowtoclearlydefinefunctionsthataccepta
variablenumberofarguments,the...constructorisusedtoprovidespreadstoarrays.
functionlogEach(...things){things.forEach(function(thing){console.log(thing);//"a""b""c"});}logEach("a","b","c");
functionexample(a,b,c){
LoadingExternalData
Promises
PromisesthesimpsonsanimatedGIF
thesimpsonsanimatedGIF
WhatisaPromise• Iwantyoutoburnthisphraseinyourmind:Apromiseisanasynchronousvalue
• ThePromiseobjectisusedfordeferredandasynchronouscomputations
• APromiseisaplaceholderforafuturepossiblevalue
PromisesinActionAttheirmostbasic,promisesareabitlikeeventlistenersexcept:
varpromise=newPromise(function(resolve,reject){//doathing,possiblyasync,then…
if(/*everythingturnedoutfine*/){
• Apromisecanonlysucceedorfailonce• Ifapromisehassucceededorfailedandyoulateraddasuccess/failurecallback,thecorrectcallbackwillbecalled,eventhoughtheeventtookplaceearlier
UsingaPromiseApromisecanbeusedbyinvokingthethen()method,itacceptsa
successandafailurehandlerasarguments.
varpromise=Promise.resolve($.ajax('/whatever.json'));
promise.then(function(result){console.log(result);//"Stuffworked!"},function(err){console.log(err);//Error:"Itbroke"});
Promises
PromisesImplementations
• Qhttps://github.com/kriskowal/q• YUIhttp://yuilibrary.com/yui/docs/promise/• es6-promisehttps://github.com/jakearchibald/es6-promise• JQueryhttp://api.jquery.com/promise/• Angularhttps://docs.angularjs.org/api/ng/service/$q• RSVP(ember)https://github.com/tildeio/rsvp.js/
Resources
Links• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources• https://developer.mozilla.org/en-US/docs/Web/JavaScript/ECMAScript_6_support_in_Mozilla• https://github.com/google/traceur-compiler• https://github.com/jmcriffey/grunt-traceur-compiler• http://pointedears.de/scripts/test/es-matrix/• http://kangax.github.io/compat-table/es6• https://people.mozilla.org/~jorendorff/es6-draft.html
@giorgionatili#mobiletea#javascript#swift#wearable#agile#android#tdd
Thanks!Grazie!Graçias!Danke!Merci!��!
skyanimatedGIF