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

EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
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 2014Phillip Trelford
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript libraryDerek Willian Stavis
 
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 / XSolveXSolve
 
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 ComeCory Forsyth
 
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)James Titcumb
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative jsPivorak MeetUp
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
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 HoursPhillip Trelford
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.Icalia Labs
 

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

EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
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 FunctionsOluwaleke Fakorede
 
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 scriptChristophe Herreman
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
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

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 RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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.pdfUK Journal
 
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...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 BusinessPixlogix Infotech
 
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?Igalia
 
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.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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?
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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