SlideShare a Scribd company logo
1 of 76
Programming Style
          &


Your Brain
    Douglas Crockford
Head.
   Gut.
Two Systems.
Visual Processing.
    An analogy.
Advertising.
Tobacco.
Computer Programs.
The most complicated things
      people make.
Artificial Intelligence.
Programming Language.
Perfection.
Hunters and Gatherers.
Programming uses
  Head and Gut.
    Tradeoffs.
JavaScript.
 Good Parts.
 Bad Parts.
JSLint.
JSLint defines a professional
    subset of JavaScript.
 http://www.JSLint.com/
WARNING!
JSLint will hurt your
      feelings.
Left or Right?
block          block {
{                   ....
     ....      }
}
Left or Right?
block               block {
{                        ....
     ....           }
}

• Be consistent.    • Everyone should do
Left or Right?
return            return {
{                      ok: true
     ok: false    };
};
• SILENT ERROR!   • Works well in
                    JavaScript.
Prefer forms that are error
         resistant.
switch statement.
The fallthrough hazard.
“That hardly ever happens”
    is another way of saying
          “It happens”.
A good style can help
produce better programs.
  Style is should not be about
 personal preference and self-
           expression.
THEROMANSWROTELATIN
Medieval copyists
introduced lowercase, word

    These innovations helped
      reduce the error rate.
Good use of style can help
 reduce the occurrence of
The Elements of Style


http://www.crockford.com/wrrrld/style.html
Programs must
communicate clearly to
Use elements of good
 composition where
For example, use a space after
     a comma, not before.
Use spaces to disambiguate
• No space between function name and (.
• One space between all other names and (.
• Wrong:
     foo (bar);
     return(a+b);
     if(a=== 0) {…}
     function foo (b) {…}
     function(x) {…}
Immediately Invocable


function () {
       ...
}();         // Syntax error!
Immediately Invocable


(function () {
    ...
})();
Immediately Invocable


(function () {
    ...          Dog balls
})();
Immediately Invocable


(function () {
    ...
}());     // Neatness counts.
The Heartbreak of Automatic

x = y    // <-- Missing semicolon
(function () {
    ...
}());
with statement.
with (o) {           o.foo   = koda;
    foo = koda;      o.foo   = o.koda;
}                    foo =   koda;
                     foo =   o.koda;
with statement.
with (o) {                o.foo   = koda;
    foo = koda;           o.foo   = o.koda;
}                         foo =   koda;
                          foo =   o.koda;

     I am not saying that it isn’t useful.
I am saying that there is never a case where
             it isn’t confusing.
Confusion must be avoided.
Transitivity? What's That?
0 == ''                // true
0 == '0'               // true
'' == '0'              // false
false == 'false'       // false
false == '0'           // true
" trn " == 0        // true
     Always use ===,   never ==.
If there is a feature of a
 language that is sometimes
 problematic, and if it can be
replaced with another feature
  that is more reliable, then
 always use the more reliable
            feature.
Multiline string literals
    var long_line_1 = "This is a 
long line"; // ok


    var long_line_2 = "This is a 
long line"; // syntax error
Avoid forms that are
difficult to distinguish from
       common errors.
if (a = b) {…}

a = b;
if (a) {…}

if (a === b) {…}
Make your programs look
   like what they do.
Scope.
Block scope v function scope.
var statement.
• It gets split into two parts:
       The declaration part gets hoisted to the top of the function, initializing with
       undefined.
       The initialization part turns into an ordinary assignment. So
         function foo() {
              ...
              var myVar = 0, myOtherVar;
•   Expands into
         function foo() {
              var myVar = undefined,
                  myOtherVar = undefined;
              ...
              myVar = 0;
Declare all variables at the
   top of the function.
for (var i …) {…}
Variable i is not scoped to the loop.
Write in the language
 you are writing in.
Let there be let.
Global variables.
• Global variables are evil.
• Avoid global variables.
• When using global variables, be
  explicit.
             UPPER_CASE
• Global variables should be as rare as
  hens teeth and stick out like a sore
  thumb.
new prefix
  Forgetting new causes a
constructor to clobber global
 variables without warning.
     Fixed in ES5/strict.
Constructor functions
should be named with
     InitialCaps.
Nothing else should be named
      with InitialCaps.
var a = b = 0;

var a = 0, b = 0;

     b = 0;
   var a = b;
Write in a way that clearly
communicates your intent.
++
++
x += 1
++
x += 1
 x++
++
x += 1
 x++
 ++x
++x;
++x;
x += 2;
For no cost, by adopting a
more rigorous style, many
 classes of errors can be
  automatically avoided.
if (a) b(); c();
if (a) b(); c();

if (a) {b(); c();}


if (a) {b();} c();
As our processes become
 more agile, our coding
 must be more resilient.
Bad stylists
• Under educated.
• Old school.
• Thrill seeker.
• Exhibitionist.
“That was intentional.”
  “I know what I’m doing.”
Programming is the most
 complicated thing that humans
              do.
Computer programs must be perfect.
  Humans are not good at perfect.
Designing a programming
style demands discipline.
   It is not selecting features
   because they are liked, or
        pretty, or familiar.
The Abyss
The JSLint style was driven
by the need to automatically
       detect defects.
  Forms that can hide defects are
      considered defective.
Language Subsetting.
Only a madman would use all of C++.
There will be bugs.
Do what you can to move the
    odds to your favor.
Good style is good for your
            gut.
The Analytical Language of John Wilkins
                 Jorge Luis Borges
These ambiguities, redundancies and deficiencies remind us of those which doctor
Franz Kuhn attributes to a certain Chinese encyclopedia entitled The Celestial
Emporium of Benevolent Knowledge. In its remote pages it is written that the animals
are divided into
     a. belonging to the Emperor
     b. embalmed
     c. trained
     d. piglets
     e. sirens
     f. fabulous
     g. stray dogs
     h. included in this classification
     i. trembling like crazy
     j. innumerables
     k. drawn with a very fine camelhair brush
     l. et cetera
     m.just broke the vase
     n. from a distance look like flies

More Related Content

Similar to Douglas Crockford - Programming Style and Your Brain

Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
chenge2k
 

Similar to Douglas Crockford - Programming Style and Your Brain (20)

Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
LISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love Parantheses
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
 
F# Eye for the C# Guy
F# Eye for the C# GuyF# Eye for the C# Guy
F# Eye for the C# Guy
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Threequals - Case Equality in Ruby
Threequals - Case Equality in RubyThreequals - Case Equality in Ruby
Threequals - Case Equality in Ruby
 
Dear compiler please don't be my nanny v2
Dear compiler  please don't be my nanny v2Dear compiler  please don't be my nanny v2
Dear compiler please don't be my nanny v2
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 

More from Web Directions

Juliette Melton - Mobile User Experience Research
Juliette Melton - Mobile User Experience ResearchJuliette Melton - Mobile User Experience Research
Juliette Melton - Mobile User Experience Research
Web Directions
 
Lisa Herrod - The Age of Awareness
Lisa Herrod - The Age of AwarenessLisa Herrod - The Age of Awareness
Lisa Herrod - The Age of Awareness
Web Directions
 

More from Web Directions (20)

Kim Heras - So, You've Got an Idea
Kim Heras - So, You've Got an IdeaKim Heras - So, You've Got an Idea
Kim Heras - So, You've Got an Idea
 
Arunan Skanthan - Roll Your own Style Guide
Arunan Skanthan - Roll Your own Style GuideArunan Skanthan - Roll Your own Style Guide
Arunan Skanthan - Roll Your own Style Guide
 
Alan Downie and Matt Milosavljevic - BugHerd, the Incubator Experience
Alan Downie and Matt Milosavljevic - BugHerd, the Incubator ExperienceAlan Downie and Matt Milosavljevic - BugHerd, the Incubator Experience
Alan Downie and Matt Milosavljevic - BugHerd, the Incubator Experience
 
Five things I know about running a digital agency
Five things I know about running a digital agencyFive things I know about running a digital agency
Five things I know about running a digital agency
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5
 
Robby Ingebretsen - Get your game on: HTML5 for game building
Robby Ingebretsen - Get your game on: HTML5 for game buildingRobby Ingebretsen - Get your game on: HTML5 for game building
Robby Ingebretsen - Get your game on: HTML5 for game building
 
Ross Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your appsRoss Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your apps
 
Juliette Melton - Mobile User Experience Research
Juliette Melton - Mobile User Experience ResearchJuliette Melton - Mobile User Experience Research
Juliette Melton - Mobile User Experience Research
 
Lisa Herrod - The Age of Awareness
Lisa Herrod - The Age of AwarenessLisa Herrod - The Age of Awareness
Lisa Herrod - The Age of Awareness
 
Practising Web Standards in the Large
Practising Web Standards in the Large Practising Web Standards in the Large
Practising Web Standards in the Large
 
15 years in - Dan Hill
15 years in - Dan Hill15 years in - Dan Hill
15 years in - Dan Hill
 
WCAG2 - Gian Wild
WCAG2 - Gian WildWCAG2 - Gian Wild
WCAG2 - Gian Wild
 
CSS Frameworks
CSS FrameworksCSS Frameworks
CSS Frameworks
 
Kerry Taylor - Semantics & sensors
Kerry Taylor - Semantics & sensorsKerry Taylor - Semantics & sensors
Kerry Taylor - Semantics & sensors
 
Boosting new media accessibility - Scott Hollier
Boosting new media accessibility - Scott HollierBoosting new media accessibility - Scott Hollier
Boosting new media accessibility - Scott Hollier
 
Opening up social networks - Renato Iannella
Opening up social networks - Renato IannellaOpening up social networks - Renato Iannella
Opening up social networks - Renato Iannella
 
Douglas Crockford - Ajax Security
Douglas Crockford - Ajax SecurityDouglas Crockford - Ajax Security
Douglas Crockford - Ajax Security
 
Jeffrey Veen - Designing our way through data
Jeffrey Veen - Designing our way through dataJeffrey Veen - Designing our way through data
Jeffrey Veen - Designing our way through data
 
Nick Bolton - The evolution and commercialisation of online video
Nick Bolton - The evolution and commercialisation of online videoNick Bolton - The evolution and commercialisation of online video
Nick Bolton - The evolution and commercialisation of online video
 
Designing The User Experience Curve
Designing The User Experience CurveDesigning The User Experience Curve
Designing The User Experience Curve
 

Recently uploaded

+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

+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...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

Douglas Crockford - Programming Style and Your Brain

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n