SlideShare a Scribd company logo
1 of 29
JavaScript 201
  Best Practices
  Juergen Fesslmeier
Wakanda Product Manager
       @chinshr
Styling and
  Naming
Form Follows Function
“There are only two hard
things in Computer Science:
   cache invalidation and
      naming things.”
   Tim Bray (quoting Phil Karlton)
Naming things
Variable names should be nouns

Function names should begin with a verb,
E.g. isValid(), hasItems(),
getProduct()

Avoid difficult to understand names,
E.g. arrUqFolders
Logical names
Requires commenting
var resBackup = function(loc) {
  …
});
Improve your function and variables names
var restoreBackupTo =
function(destination) {
  …
});
Add style to your code
• Indent your code correctly

• Comment your code only if it adds value
/**
  * @method getList
  * @param {Object} options
  * @return {Object}
  **/
var getList = function(options) {
}
Use blocks instead of one-liners
When            Becomes
if a()          if a()
  b();            b();
                  c();

It looks like   But really means
if a() {        if a() {
  b();            b();
  c();          }
}               c();
Use of spaces
Nice                  Less readable
if (found) {          if(found) {
  // good               // bad
}                     }

function a() {…}      function a () {…}

app.config.folder;    app. config. folder;
Semicolon insertion
Good                      Bad
var good = function() {   var bad = function ( )
  return {                {
     sum: 12                return
  };                        {
}                              sum: 12
                            };
                          }

> good();                 > bad();
{ sum: 12 }               undefined
Eval twins == and !=
'' == '0'            // false
0 == ''              // true
0 == '0'             // true

false == 'false'     // false
false == '0'         // true

false == undefined   // false
false == null        // false
null == undefined    // true
Faithful triplets === and !==
Always use `===` for equals and `!==` for
not-equals when you do comparisons

if (a === 5 && b !== 10) {
  // feeling much better
}
Friendly parameters
Instead of large parameter lists
var address = build(f, l, c, s);


Use objects
var address = build({
  first: f,
  last: l,
  city: c,
  state: s
});
Augmenting Types
String.prototype.pluralize = function() {
   return this + "s";
};
> "car".pluralize() // "cars"


You don’t own Object, Array, RegExp,
String, Number, Boolean, Date, Function
Scopes and
 Closures
Global Scope
var message = “Wakanda”;

function greet() {
  console.log(message + “ is great!”);
}

> message
“Wakanda”

> greet()
“Wakanda is great!”
Local Scope
function greet(what) {
  var message = what;
  console.log(message + “ is great!”);
}

> message
undefined

> greet(“Wakanda”)
“Wakanda is great!”

> message
undefined
Mixing scope
var outer = function() {
  var a = 4, b = 5;

  var inner = function() {
     var b = 7, c = 11;
     a = b + c;
  };

  console.log(a);
  inner();
  console.log(a);
};
Returning functions
var setup = function() {
  var count = 0;
  return function() {
    return (count += 1);
  }
}

// usage
var next   = setup();
next();    // 1
next();    // 2
count      // undefined
“A closure is a function
defined within another scope
  that has access to all the
 variables within the outer
           scope.”
                Tim Caswell
Consider this example…
/*
 * jsfiddle.net/TnaMW
 */
var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
  var link = document.createElement('a');
  link.setAttribute('href', '#');
  link.innerHTML = i + ' ';
  link.onclick = function() { alert(i); };
  div.appendChild(link);
}

// 0 1 2 3 4 5 6 7 8 9
…works with a Closure
/*
 * jsfiddle.net/kxy5t
 */
var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
  var link = document.createElement('a');
  link.setAttribute('href', '#');
  link.innerHTML = i + ' ';
  link.onclick = function(k) {
    return function() { alert(k); }
  }(i);
  div.appendChild(link);
}

// 0 1 2 3 4 5 6 7 8 9
Self-invoking functions
var person = function() {
  // private
  var name = "Juergen";
 // public
  return {
     getName : function() {return name;},
     setName : function(newName) {name = newName;}
  };
}();

>   person.name              // undefined
>   person.getName();        // ”Juergen"
>   person.setName("Dan");
>   person.getName();        // ”Dan"
Immediate functions

(function() {
  var number = 5;
  alert("number is " + number);
}())

> "number is 5"
> number // undefined
Immediate functions w/
        parameters
(function(input) {
  var number = input;
  alert("number is " + number);
}(5))

> "number is 5”
> number // undefined
Improving Object helpers
(function(root, String) {
  root._ = root._ || {};
  root._ = {
     pluralize: function(str) {
       return str + "s";
     }
  };
})(this, String);

> _.pluralize("car")
"cars"
Class like structures
var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function() {
        return "Hello " + this.greeting + ”!";
    };
    return Greeter;
})();

> var greeter = new Greeter(”world");
> greeter.greet();
"Hello world!"
Dataclass structures in
              Wakanda
model = new DataStoreCatalog();

model.create("Greeter", {extends: "Base"}, function() {

  attribute("name", "string")

  method("greet", function() {
    return "Hello " + this.name + "!";
  });

});

> var greeter = new Greeter({name: "Juergen"});
> greeter.greet(); // Hello Juergen!
JavaScript 201
  Best Practices
  Juergen Fesslmeier
Wakanda Product Manager
       @chinshr

More Related Content

What's hot

LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 

What's hot (20)

EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative js
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 

Similar to Wakanday JS201 Best Practices

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
jhchabran
 

Similar to Wakanday JS201 Best Practices (20)

EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 

Recently uploaded

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Wakanday JS201 Best Practices

  • 1. JavaScript 201 Best Practices Juergen Fesslmeier Wakanda Product Manager @chinshr
  • 2. Styling and Naming
  • 4. “There are only two hard things in Computer Science: cache invalidation and naming things.” Tim Bray (quoting Phil Karlton)
  • 5. Naming things Variable names should be nouns Function names should begin with a verb, E.g. isValid(), hasItems(), getProduct() Avoid difficult to understand names, E.g. arrUqFolders
  • 6. Logical names Requires commenting var resBackup = function(loc) { … }); Improve your function and variables names var restoreBackupTo = function(destination) { … });
  • 7. Add style to your code • Indent your code correctly • Comment your code only if it adds value /** * @method getList * @param {Object} options * @return {Object} **/ var getList = function(options) { }
  • 8. Use blocks instead of one-liners When Becomes if a() if a() b(); b(); c(); It looks like But really means if a() { if a() { b(); b(); c(); } } c();
  • 9. Use of spaces Nice Less readable if (found) { if(found) { // good // bad } } function a() {…} function a () {…} app.config.folder; app. config. folder;
  • 10. Semicolon insertion Good Bad var good = function() { var bad = function ( ) return { { sum: 12 return }; { } sum: 12 }; } > good(); > bad(); { sum: 12 } undefined
  • 11. Eval twins == and != '' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true
  • 12. Faithful triplets === and !== Always use `===` for equals and `!==` for not-equals when you do comparisons if (a === 5 && b !== 10) { // feeling much better }
  • 13. Friendly parameters Instead of large parameter lists var address = build(f, l, c, s); Use objects var address = build({ first: f, last: l, city: c, state: s });
  • 14. Augmenting Types String.prototype.pluralize = function() { return this + "s"; }; > "car".pluralize() // "cars" You don’t own Object, Array, RegExp, String, Number, Boolean, Date, Function
  • 16. Global Scope var message = “Wakanda”; function greet() { console.log(message + “ is great!”); } > message “Wakanda” > greet() “Wakanda is great!”
  • 17. Local Scope function greet(what) { var message = what; console.log(message + “ is great!”); } > message undefined > greet(“Wakanda”) “Wakanda is great!” > message undefined
  • 18. Mixing scope var outer = function() { var a = 4, b = 5; var inner = function() { var b = 7, c = 11; a = b + c; }; console.log(a); inner(); console.log(a); };
  • 19. Returning functions var setup = function() { var count = 0; return function() { return (count += 1); } } // usage var next = setup(); next(); // 1 next(); // 2 count // undefined
  • 20. “A closure is a function defined within another scope that has access to all the variables within the outer scope.” Tim Caswell
  • 21. Consider this example… /* * jsfiddle.net/TnaMW */ var div = document.getElementById('div'); for (var i = 0; i < 10; i++) { var link = document.createElement('a'); link.setAttribute('href', '#'); link.innerHTML = i + ' '; link.onclick = function() { alert(i); }; div.appendChild(link); } // 0 1 2 3 4 5 6 7 8 9
  • 22. …works with a Closure /* * jsfiddle.net/kxy5t */ var div = document.getElementById('div'); for (var i = 0; i < 10; i++) { var link = document.createElement('a'); link.setAttribute('href', '#'); link.innerHTML = i + ' '; link.onclick = function(k) { return function() { alert(k); } }(i); div.appendChild(link); } // 0 1 2 3 4 5 6 7 8 9
  • 23. Self-invoking functions var person = function() { // private var name = "Juergen"; // public return { getName : function() {return name;}, setName : function(newName) {name = newName;} }; }(); > person.name // undefined > person.getName(); // ”Juergen" > person.setName("Dan"); > person.getName(); // ”Dan"
  • 24. Immediate functions (function() { var number = 5; alert("number is " + number); }()) > "number is 5" > number // undefined
  • 25. Immediate functions w/ parameters (function(input) { var number = input; alert("number is " + number); }(5)) > "number is 5” > number // undefined
  • 26. Improving Object helpers (function(root, String) { root._ = root._ || {}; root._ = { pluralize: function(str) { return str + "s"; } }; })(this, String); > _.pluralize("car") "cars"
  • 27. Class like structures var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function() { return "Hello " + this.greeting + ”!"; }; return Greeter; })(); > var greeter = new Greeter(”world"); > greeter.greet(); "Hello world!"
  • 28. Dataclass structures in Wakanda model = new DataStoreCatalog(); model.create("Greeter", {extends: "Base"}, function() { attribute("name", "string") method("greet", function() { return "Hello " + this.name + "!"; }); }); > var greeter = new Greeter({name: "Juergen"}); > greeter.greet(); // Hello Juergen!
  • 29. JavaScript 201 Best Practices Juergen Fesslmeier Wakanda Product Manager @chinshr

Editor's Notes

  1. Form follows function is a principle associated with modern architecture and industrial design in the 20th century. The principle is that the shape of a building or object should be primarily based upon its intended function or purpose.
  2. Imagine you have to come back to your code in a month and you don’t know what the hell you were doing just by reading your code
  3. You should always prefer block quotes instead of using one liners
  4. Use K&amp;R style braces `}` at the end of a structural block, because it matters! Modifying the previous code to use Allman style braces would look like this. The code on the right is broken
  5. What is Git?
  6. Because setup wraps the returned function, it creates a closure, and you can use that closure to store some private data, which is only accessible by the private function but not to the outside code.
  7. http://howtonode.org/why-use-closure
  8. http://howtonode.org/why-use-closure
  9. An example from the underscore library