SlideShare a Scribd company logo
Tamas Rev,
April, 2015
Contact: tamas.rev@gmail.com
Blog: http://tamasrev.wordpress.com/
Twitter: https://twitter.com/tamasrev
Github: https://github.com/rev-tomi/
Surviving javascript
What’s wrong with javascript?
What’s wrong with javascript?
• Wrong
– Scope
– Implicit globals
– Equality
– …
Scopes
demo.scopes = function() {
var a = 0;
for (var i = 0; i < 10; i++) {
var j = i;
a += i;
}
this.appendText('i, after loop: ' + i + '<br>'); // i: 10
this.appendText('j, after loop: ' + j + '<br>'); // j: 9
};
demo.scopes();
Implicit Globals
demo.globals = function() {
var a = 0;
for (i = 0; i < 10; i++) { // oops: no var
a += i;
}
};
demo.globals();
demo.appendText('i: ' + i + '<br>'); // 10
Equality 1
The confusing ones:
"'' == '0'" => false
"0 == ''" => true
"0 == '0'" => true
"false == 'false'" => false
"false == '0'" => true
"false == undefined" => false
"false == null" => false
"null == 'undefined'" => false
What’s wrong with javascript?
• Controversial
– Dynamic typing
– Prototype-based inheritance
Overcoming issues
• Overcoming scope issues
– Using var
– Immediately invoked functions
• Overcoming equality issues
– Using ===
• Overcoming unknown issues
– Using static analyzers
Dealing with scope issues
var demo = function() {
var // var definitions below:
// accessible only from the actual function
sandbox = document.getElementById("sandbox"),
appendText = function(txt) {
sandbox.innerHTML = sandbox.innerHTML + txt;
};
return {
'appendText' : appendText
};
}(); // immediately invoked function expression
// effectively: var demo = { 'appendText' : appendText };
Immediately invoked functions
// how it works
var demo = function () {
…
return {...};
} ();// watch out for ();
// expanded:
var demoCreator = function () {
…
return {...};
};
var demo = demoCreator(); // invoking the function later
Equality 2
The clear ones:
"'' === '0'" => false
"0 === ''" => false
"0 === '0'" => false
"false === 'false'" => false
"false === '0'" => false
"false === undefined" => false
"false === null" => false
"null === 'undefined'" => false
Static analyzers: jshint and jslint
• Both installable with npm. Example package.json:
"dependencies" : {
"jshint" : "2.6.x",
"jslint": ">=0.3.4"
}
• jslint: very strict
• jshint: needs configuration
• Comparison: http://www.smashingmagazine.com/2015/02/18/avoid-javascript-mistakes-
with-static-code-analyzer/
Static analyzer: jshint
• jslint: very strict. Example output:
#3 Missing 'use strict' statement.
var a = 0; // Line 2, Pos 3
#4 Expected 'for' at column 5, not column 3.
for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 3
#5 'i' was used before it was defined.
for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 8
#6 'i' was used before it was defined.
for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 15
• Line #3: warns to use “use strict”
• Line #4: warns about styling issues
• Line #5 and #6: warns about actual problems.
Static analyzer: jshint
• This needs lots of configuration. E.g.:
{
"undef": true,
"unused": true,
"predef": [ "demo", "document" ]
}
• "undef": true // warns you about accidentally defining globals
• This so basic that this should be default
• "unused": true // warns you about things that you can delete
• This is useful. This should be default too
• “predef: ”// lets you to configure vars the come someplace else
• This is actually very useful
Unit test frameworks
• Use unit tests! They’ll catch the majority of subtle bugs
• QUnit - written by the junit team.
• You can run it in your browser
• https://qunitjs.com/
• Mocha - written for node.js
• Comes with various flavors, like TDD, BDD
• You can run it from commandline
• https://qunitjs.com/
• Mocking
• Faking is easy: with dynamic typing you can easily creating fakes
• There are tools for spies, like JsMockito
• http://jsmockito.org/
What’s good about javascript?
• Functional
– Demo: js-list-lazy
• Compact syntax, e.g. inline maps
• Property based => easy to extend
– Demo: tapestry js validations
• Metaprogramming
– Demo: 3.times() …
js-list-lazy
• https://github.com/dankogai/js-list-lazy/ is a list comprehension framework written by Dan Kogai
• Fibonacci example from project page:
var fib = {
0:0,
1:1,
n:1,
get:function(n) {
if (n in this) return this[n];
while(this.n < n)
this[++this.n] = this[this.n-1] + this[this.n-2];
return this[n];
}
},
fb = List.Lazy(fib);
fb.get(22); // 17711
fb.take(10) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Tapestry’s modular validator
• Tapestry is a java web framework with lots of magic
• Extending js validations with custom routines is, however, simple javascript.
• You just add a new property to the Tapestry.Validators object:
Tapestry.Validator.letters = function(field, message) {
field.addValidator(function(value) {
if (value != null) {
if (value.match('[A-Za-z]+') != value) {
throw message;
}
}
});
};
• Source of example: http://jumpstart.doublenegative.com.
au/jumpstart/examples/input/contributingvalidators
Metaprogramming
• This is how you can add a method to numbers:
Number.prototype.times = function(func) {
var i;
for (i = 0; i < this; i++) {
func();
}
};
5['times'](function() {
demo.appendText('hello<br>');
});
Metaprogramming: Mixins 1
• A mixin adds function to another object. E.g. this is how you can add a counter:
var addCounterMixin = function(obj) {
var counter = 0; // state of the mixin
obj.increment = function() {
counter++;
}
obj.getCount = function() {
return counter;
}
}
• And this is how you can use it:
var frici = demo.createCat("Frici");
frici.increment();
demo.appendText(frici.getCount());
Metaprogramming: Mixins 2
• This is the famous comparable mixin:
var addComparableMixin = function(obj) {
obj.smaller = function(other) {
return obj.compareTo(other) === -1; // depending on compareTo
};
obj.greater = function(other) {
return obj.compareTo(other) === 1; // depending on compareTo
};
// ... more operators
}
Further learning
• Douglas Crockford: Javascript, the good parts
Wrapping up
• Easy syntax
• Easy pitfalls
• Static analyzers
• Unit tests
• Raw access to pure magic
• Source of the examples:
https://github.com/rev-tomi/survive-javascript
FAQ
• Can you write mocks with QUnit?
• I don’t think so
• However, you can use JsMockito
• What IDE do you use?
• For java I use eclipse. For js I use editors
like notepad++
• Can you integrate jslint / jshint to eclipse?
• Yes, there are plugins for that
• No, I haven’t tried to do it

More Related Content

What's hot

Re-analysis of Umbraco code
Re-analysis of Umbraco codeRe-analysis of Umbraco code
Re-analysis of Umbraco code
PVS-Studio
 
Checking OpenCV with PVS-Studio
Checking OpenCV with PVS-StudioChecking OpenCV with PVS-Studio
Checking OpenCV with PVS-Studio
PVS-Studio
 
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseCppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
Andrey Karpov
 
OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs
CocoaHeads France
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
Andrey Karpov
 
Khan Academy Computer Science
Khan Academy Computer ScienceKhan Academy Computer Science
Khan Academy Computer Science
jeresig
 
Javascript Styles and some tips
Javascript Styles and some tipsJavascript Styles and some tips
Javascript Styles and some tips
Vítor Baptista
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC
 
node.js errors
node.js errorsnode.js errors
node.js errors
LearningTech
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
Amos Wenger
 
TYPO3 Scheduler
TYPO3 SchedulerTYPO3 Scheduler
TYPO3 Scheduler
Krystian Szymukowicz
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
CocoaHeads France
 
Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
Arthur Puthin
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScript
John Hann
 
A Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCatA Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCat
Andrey Karpov
 
Scaling Cairngorms
Scaling CairngormsScaling Cairngorms
Scaling Cairngorms
Glenn Goodrich
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
Mohamed Krar
 
Firefox Easily Analyzed by PVS-Studio Standalone
Firefox Easily Analyzed by PVS-Studio StandaloneFirefox Easily Analyzed by PVS-Studio Standalone
Firefox Easily Analyzed by PVS-Studio Standalone
Andrey Karpov
 

What's hot (18)

Re-analysis of Umbraco code
Re-analysis of Umbraco codeRe-analysis of Umbraco code
Re-analysis of Umbraco code
 
Checking OpenCV with PVS-Studio
Checking OpenCV with PVS-StudioChecking OpenCV with PVS-Studio
Checking OpenCV with PVS-Studio
 
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseCppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
 
OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
 
Khan Academy Computer Science
Khan Academy Computer ScienceKhan Academy Computer Science
Khan Academy Computer Science
 
Javascript Styles and some tips
Javascript Styles and some tipsJavascript Styles and some tips
Javascript Styles and some tips
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 
TYPO3 Scheduler
TYPO3 SchedulerTYPO3 Scheduler
TYPO3 Scheduler
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScript
 
A Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCatA Spin-off: CryEngine 3 SDK Checked with CppCat
A Spin-off: CryEngine 3 SDK Checked with CppCat
 
Scaling Cairngorms
Scaling CairngormsScaling Cairngorms
Scaling Cairngorms
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
 
Firefox Easily Analyzed by PVS-Studio Standalone
Firefox Easily Analyzed by PVS-Studio StandaloneFirefox Easily Analyzed by PVS-Studio Standalone
Firefox Easily Analyzed by PVS-Studio Standalone
 

Viewers also liked

Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
Christian Heilmann
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injection
Tamas Rev
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
Kürşad Gülseven
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
Doeun KOCH
 
HTML5 - now or later
HTML5 - now or laterHTML5 - now or later
HTML5 - now or later
Kasia Drzyzga
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
Robert Pearce
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
Kasia Drzyzga
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
Kumar
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
poojanov04
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
Kang-min Liu
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
IIPM JAIPUR
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
Mindy McAdams
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
Scott Becker
 
Unix commands
Unix commandsUnix commands
Unix commands
BhaskarBalapuram
 
Shell Script Tutorial
Shell Script TutorialShell Script Tutorial
Shell Script Tutorial
Quang Minh Đoàn
 

Viewers also liked (20)

Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injection
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
HTML5 - now or later
HTML5 - now or laterHTML5 - now or later
HTML5 - now or later
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
 
Javascript Tutorial
Javascript TutorialJavascript Tutorial
Javascript Tutorial
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
Unix commands
Unix commandsUnix commands
Unix commands
 
Shell Script Tutorial
Shell Script TutorialShell Script Tutorial
Shell Script Tutorial
 

Similar to Surviving javascript.pptx

Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
Andrey Karpov
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
No Hugging, No Learning
No Hugging, No LearningNo Hugging, No Learning
No Hugging, No Learning
Olaf Alders
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Holger Grosse-Plankermann
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
thomas alisi
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
Denis Voituron
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
Tomek Kaczanowski
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 

Similar to Surviving javascript.pptx (20)

Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
No Hugging, No Learning
No Hugging, No LearningNo Hugging, No Learning
No Hugging, No Learning
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 

Recently uploaded

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 

Recently uploaded (20)

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 

Surviving javascript.pptx

  • 1. Tamas Rev, April, 2015 Contact: tamas.rev@gmail.com Blog: http://tamasrev.wordpress.com/ Twitter: https://twitter.com/tamasrev Github: https://github.com/rev-tomi/
  • 3. What’s wrong with javascript?
  • 4. What’s wrong with javascript? • Wrong – Scope – Implicit globals – Equality – …
  • 5. Scopes demo.scopes = function() { var a = 0; for (var i = 0; i < 10; i++) { var j = i; a += i; } this.appendText('i, after loop: ' + i + '<br>'); // i: 10 this.appendText('j, after loop: ' + j + '<br>'); // j: 9 }; demo.scopes();
  • 6. Implicit Globals demo.globals = function() { var a = 0; for (i = 0; i < 10; i++) { // oops: no var a += i; } }; demo.globals(); demo.appendText('i: ' + i + '<br>'); // 10
  • 7. Equality 1 The confusing ones: "'' == '0'" => false "0 == ''" => true "0 == '0'" => true "false == 'false'" => false "false == '0'" => true "false == undefined" => false "false == null" => false "null == 'undefined'" => false
  • 8. What’s wrong with javascript? • Controversial – Dynamic typing – Prototype-based inheritance
  • 9. Overcoming issues • Overcoming scope issues – Using var – Immediately invoked functions • Overcoming equality issues – Using === • Overcoming unknown issues – Using static analyzers
  • 10. Dealing with scope issues var demo = function() { var // var definitions below: // accessible only from the actual function sandbox = document.getElementById("sandbox"), appendText = function(txt) { sandbox.innerHTML = sandbox.innerHTML + txt; }; return { 'appendText' : appendText }; }(); // immediately invoked function expression // effectively: var demo = { 'appendText' : appendText };
  • 11. Immediately invoked functions // how it works var demo = function () { … return {...}; } ();// watch out for (); // expanded: var demoCreator = function () { … return {...}; }; var demo = demoCreator(); // invoking the function later
  • 12. Equality 2 The clear ones: "'' === '0'" => false "0 === ''" => false "0 === '0'" => false "false === 'false'" => false "false === '0'" => false "false === undefined" => false "false === null" => false "null === 'undefined'" => false
  • 13. Static analyzers: jshint and jslint • Both installable with npm. Example package.json: "dependencies" : { "jshint" : "2.6.x", "jslint": ">=0.3.4" } • jslint: very strict • jshint: needs configuration • Comparison: http://www.smashingmagazine.com/2015/02/18/avoid-javascript-mistakes- with-static-code-analyzer/
  • 14. Static analyzer: jshint • jslint: very strict. Example output: #3 Missing 'use strict' statement. var a = 0; // Line 2, Pos 3 #4 Expected 'for' at column 5, not column 3. for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 3 #5 'i' was used before it was defined. for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 8 #6 'i' was used before it was defined. for (i = 0; i < 10; i++) { // oops: no var // Line 3, Pos 15 • Line #3: warns to use “use strict” • Line #4: warns about styling issues • Line #5 and #6: warns about actual problems.
  • 15. Static analyzer: jshint • This needs lots of configuration. E.g.: { "undef": true, "unused": true, "predef": [ "demo", "document" ] } • "undef": true // warns you about accidentally defining globals • This so basic that this should be default • "unused": true // warns you about things that you can delete • This is useful. This should be default too • “predef: ”// lets you to configure vars the come someplace else • This is actually very useful
  • 16. Unit test frameworks • Use unit tests! They’ll catch the majority of subtle bugs • QUnit - written by the junit team. • You can run it in your browser • https://qunitjs.com/ • Mocha - written for node.js • Comes with various flavors, like TDD, BDD • You can run it from commandline • https://qunitjs.com/ • Mocking • Faking is easy: with dynamic typing you can easily creating fakes • There are tools for spies, like JsMockito • http://jsmockito.org/
  • 17. What’s good about javascript? • Functional – Demo: js-list-lazy • Compact syntax, e.g. inline maps • Property based => easy to extend – Demo: tapestry js validations • Metaprogramming – Demo: 3.times() …
  • 18. js-list-lazy • https://github.com/dankogai/js-list-lazy/ is a list comprehension framework written by Dan Kogai • Fibonacci example from project page: var fib = { 0:0, 1:1, n:1, get:function(n) { if (n in this) return this[n]; while(this.n < n) this[++this.n] = this[this.n-1] + this[this.n-2]; return this[n]; } }, fb = List.Lazy(fib); fb.get(22); // 17711 fb.take(10) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  • 19. Tapestry’s modular validator • Tapestry is a java web framework with lots of magic • Extending js validations with custom routines is, however, simple javascript. • You just add a new property to the Tapestry.Validators object: Tapestry.Validator.letters = function(field, message) { field.addValidator(function(value) { if (value != null) { if (value.match('[A-Za-z]+') != value) { throw message; } } }); }; • Source of example: http://jumpstart.doublenegative.com. au/jumpstart/examples/input/contributingvalidators
  • 20. Metaprogramming • This is how you can add a method to numbers: Number.prototype.times = function(func) { var i; for (i = 0; i < this; i++) { func(); } }; 5['times'](function() { demo.appendText('hello<br>'); });
  • 21. Metaprogramming: Mixins 1 • A mixin adds function to another object. E.g. this is how you can add a counter: var addCounterMixin = function(obj) { var counter = 0; // state of the mixin obj.increment = function() { counter++; } obj.getCount = function() { return counter; } } • And this is how you can use it: var frici = demo.createCat("Frici"); frici.increment(); demo.appendText(frici.getCount());
  • 22. Metaprogramming: Mixins 2 • This is the famous comparable mixin: var addComparableMixin = function(obj) { obj.smaller = function(other) { return obj.compareTo(other) === -1; // depending on compareTo }; obj.greater = function(other) { return obj.compareTo(other) === 1; // depending on compareTo }; // ... more operators }
  • 23. Further learning • Douglas Crockford: Javascript, the good parts
  • 24. Wrapping up • Easy syntax • Easy pitfalls • Static analyzers • Unit tests • Raw access to pure magic • Source of the examples: https://github.com/rev-tomi/survive-javascript
  • 25. FAQ • Can you write mocks with QUnit? • I don’t think so • However, you can use JsMockito • What IDE do you use? • For java I use eclipse. For js I use editors like notepad++ • Can you integrate jslint / jshint to eclipse? • Yes, there are plugins for that • No, I haven’t tried to do it