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

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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 Takeoffsammart93
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
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 WorkerThousandEyes
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Recently uploaded (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

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