Yesterday I stopped over to watch a Douglas Crockford talk.
I have spoken here that Douglas is loved and hated in the JavaScript community, and I think there is something wrong in this situation.
As JavaScript developers, we must pay attention to one fact: Crockford knows a lot of JavaScript language. Probably more than all of us.
I say this because the foundation in the theories of Crockford make much sense, and presented by him show that he really understands what he says.
After many years studying JavaScript, i still do not consider myself able to say that I am JavaScript ninja, and taht i know everything.
That is what Crockford does seem to be a ninja and seems to know everything about the language, so the least I can do is listen to the man, pay attention and run back to maybe one day have enough knowledge to question the theories of Douglas.
During the talk Crockford proved by his theories.
- But braces “{“ on right
Ex:block { ... }I always put it on the right. But many programmers put on the left, thus:
block { ... }It doesn’t matter. On the right or left, no matter …
Except in JavaScript.
Yes, this is different for JavaScript, for one simple reason.
look at the code:return { ok : false }This code will fail.
If we want to return an object literal, we must always put the ”{“ on the right, because in this case the JavaScript returns undefined.
A simple change, and your program will not fail:return { ok : false } - Ever use === instead ==
He explained why, and actually makes sense.
== does not work very well in JavaScript. Even Brendan knew this when he created the language.
What happened was that when the language was standardized, Brendan tried to fix this with the committee, but Microsoft insisted that should not be done.
Why the hell? I do not know.
But Brendan could at least implement ===, then this is the reason why always use ===.
Some examples that prove the failure ==:0 == '' //true '' == '0' //false 0 == '0' //true false == 'false' //false false == '0' //true // E o mais bizarro de todos " trn " == 0 //true
- Always declare variables at the top of the function body
Interesting.
Douglas explained in the talk that JavaScript is different from other languages in relation to variable scope.
In other languages, we should always declare variables as close as possible to where we use them. In JavaScript is quite the opposite.
We should always declare variables at the top of the function, because actually is what happens, this is the first thing that is done in the execution flow.
Before the video, a interesting sentence:
“If there is one feature of a language that is sometimes problematic, and it can be replaced by another feature that is more reliable, then ever use the reliable feature”
Makes sense.
Well, I recommend that everyone take a look this video. Even those who do not like Crockford. Especially those who do not like.
Open your mind, listen, study, research.

Achei ele muito simpatico e muito didático.
Infelizmente achei a palestra pouco técnica. Nao sei a que publico foi direcionado, mas gostaria que ele fosse mais a fundo em determinadas questões.
Por exemplo, o “silent error” do return com objeto na linha debaixo não é um erro. As pessoas pensam que é a mesma coisa pois ninguém sabe como usar ponto e vírgula no javascript. (conheco apenas uma pessoa que sabe, e nao sou eu)
Return sempre termina a sua linha como se tivesse um ponto e virgula, daí o objeto abaixo é anônimo sem nenhum propósito programado.
Se comporta da mesma forma que colocar “use strict”. não interfere no programa de forma alguma. (apesar de alguns navegadores reconhecerem o código segundo as especificacoes do ecmascript5).
Quanto ao lance dos == e ===, 2 iguais é mais rápido que 3, os navegadores foram otimizados para o uso mais comum de comparações (ninguém liga para performance, eu sei). Os problemas acontecem porque as pessoas nao entendem como funcionam as conversões de tipo de valor em javascript.
Ex:
O resultado vai ser uma string em:
1 + ’2′ + [0] + false = ’120false’
Mas vai ser um numero em:
(1 + ’2′ + [0])*1 + true = 121
Se o javascript tem essa flexibilidade de tipos em cálculo matematico, não é a toa que isso acontece em condicionais de 2 iguais.
—
Não concordo com algumas coisas que ele prega mas aprendi muito pesquisando sobre o porque ele acha melhor certas formas. Na pior das hipóteses esse esforço é valido.
Alias, sempre que uma string tem .length maior que 0 e contiver caracteres não numéricos (ex: ‘a’, ’1a’) ela nunca será convertida em outros tipos de forma bem sucedida em comparações de 2 iguais.
‘false’, ‘ nr’, ‘undefined’ são texto e vão ser tratados em 2 iguais como tal. Recomendo brincar bastante no console e fazer experiencias a respeito. Vale a pena entender melhor essas conversões mesmo que se decida por usar 3 iguais.
Da mesma forma, o problema mais comum é:
a == 0
0 nesse caso pode ser convertido para quase qualquer tipo e dá muita confusão. Além da sugestão de usar === pode-se usar < 1 entre outras.
Grande Marcelo, comentário tão bem feito e elaborado quanto a palestra.
Realmente a palestra foi bem didática, mas pouco técnica, apesar de eu ter gostado muito dos fatos históricos citados.
E o lance do “The Gut” achei muito legal, mas isso é um gosto pessoal meu por essa área do cérebro e tal. Achei legal o link que ele fez das coisas.
Concordo que muito dos “erros” não são de fato erros, mas concordo com o Douglas quanto a legibilidade do código para outros programadores.
Claro, isso tudo é muito relativo, pois dependendo da equipe onde se trabalha, isso pode ser ignorado, e ser substituído por padrões e convenções da equipe.
JavaScript é uma linguagem dinâmica e o melhor é usar esse dinamismo, e claro, engessar as vezes atrapalha.
E claro, concordo contigo novamente sobre pesquisar o que foi dito pelo Crockford. Isso só nos tras benefícios.
Valeu pelo comentário muito bem elaborado e embasado.