SlideShare a Scribd company logo
Programming Style
          &


Your Brain
    Douglas Crockford
Douglas Crockford - Programming Style and Your Brain
Head.
   Gut.
Two Systems.
Visual Processing.
    An analogy.
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your Brain
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.
Douglas Crockford - Programming Style and Your Brain
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

PDF
Section 8 Programming Style and Your Brain: Douglas Crockford
PDF
Little lessons learned from Swift
PDF
Immersive - Sydney July 2017
PDF
ISMAR17 - Augmenting, Mixing & Extending Reality on the web
PDF
Immersive Computing @ #YOWConnected 2017
PPT
Goodparts
PPT
Douglas Crockford Presentation Goodparts
PPTX
JS Fest 2018. Douglas Crockford. The Better Parts
Section 8 Programming Style and Your Brain: Douglas Crockford
Little lessons learned from Swift
Immersive - Sydney July 2017
ISMAR17 - Augmenting, Mixing & Extending Reality on the web
Immersive Computing @ #YOWConnected 2017
Goodparts
Douglas Crockford Presentation Goodparts
JS Fest 2018. Douglas Crockford. The Better Parts

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

PPTX
Intro to Functional Programming
PDF
Go Beyond Higher Order Functions: A Journey into Functional Programming
KEY
LISP: How I Learned To Stop Worrying And Love Parantheses
PPTX
A brief introduction to C Language
PDF
A Quick Taste of C
PPT
F# Eye for the C# Guy
PPT
Haskell retrospective
PDF
Threequals - Case Equality in Ruby
PPTX
Dear compiler please don't be my nanny v2
PPT
Ruby for Perl Programmers
PPT
name name2 n2
PPT
name name2 n
PPT
ppt21
PPT
name name2 n
PPT
ppt17
PPT
ppt7
PPT
ppt9
PPT
test ppt
PPT
name name2 n2.ppt
PPT
ppt2
Intro to Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
LISP: How I Learned To Stop Worrying And Love Parantheses
A brief introduction to C Language
A Quick Taste of C
F# Eye for the C# Guy
Haskell retrospective
Threequals - Case Equality in Ruby
Dear compiler please don't be my nanny v2
Ruby for Perl Programmers
name name2 n2
name name2 n
ppt21
name name2 n
ppt17
ppt7
ppt9
test ppt
name name2 n2.ppt
ppt2
Ad

More from Web Directions (20)

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

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
1 - Historical Antecedents, Social Consideration.pdf
PPTX
1. Introduction to Computer Programming.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
Encapsulation theory and applications.pdf
A comparative study of natural language inference in Swahili using monolingua...
WOOl fibre morphology and structure.pdf for textiles
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
cloud_computing_Infrastucture_as_cloud_p
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
DP Operators-handbook-extract for the Mautical Institute
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
1 - Historical Antecedents, Social Consideration.pdf
1. Introduction to Computer Programming.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Web App vs Mobile App What Should You Build First.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Zenith AI: Advanced Artificial Intelligence
gpt5_lecture_notes_comprehensive_20250812015547.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
A comparative analysis of optical character recognition models for extracting...

Douglas Crockford - Programming Style and Your Brain

Editor's Notes