Este documento resume 8 cosas importantes sobre JavaScript: 1) la coerción y sus usos, 2) los operadores bit a bit y alternativas más seguras, 3) el hoisting de variables y funciones, 4) los scopes y buenas prácticas, 5) las funciones bind, call y apply, 6) el prototype y la herencia, 7) que JavaScript usa UCS-2 para caracteres, y 8) que los puntos y comas son opcionales pero su uso evita errores.
8. Cuando verificas si una
variable existe
if( variable ){}
// JavaScript lo coerce a booleano
// es equivalente a:
if( Boolean(variable) ){}
// o...
if( !!variable ){}
9. Cuando accedes una
propiedad sin string
myObj[ 3 ];
// JavaScript lo coerce a string
myObj[ '3' ]
// Yep, arreglos tambien aplican
[ 1, 2, 3 ][ '2' ] // 3
16. Cuando concatenas...
var edad = 20;
console.log( "Tu edad es: " +
edad );
// JavaScript coerce edad<number>
a string
console.log( "Tu edad es: " +
"20" )
17. Cuando usas un contructor
de tipo core como función,
es decir, sin new
Boolean( 19 ) // true
String( 19 ) // '19'
Number( '19' ) // 19
Number( true ) // 1
18. ej: coerción de fechas
var date = new Date()
date.getTime() // 1367795189000
date.valueOf() // 1367795189000
+ date // 1367795189000
date.toString() // "Sun May 05
2013 ..."
date + '' // "Sun May 05 2013
..."
19.
20. ej: coerción de strings
var text = '123'
parseInt( text ) // 123
Number( text ) // 123
+ text // 123
21. Coerción de strings (2)
var text = '34.5%'
Number( text ) // NaN
+ text // NaN
parseInt( text ) // 34 <- yeah!
parseFloat( text ) // 34.5 <-
yeeeah!
35. ejemplo
var i = 1,
j = 2
function hoisting(){
console.log( i )
console.log( j )
var i = 3
console.log( i )
}
hoisting()
36.
37. lo que realmente imprime
var i = 1,
j = 2
function hoisting(){
console.log( i ) // undefined
console.log( j ) // 2
var i = 3
console.log( i ) // 3
}
hoisting()
38.
39. lo que pasa
var i = 1,
j = 2
function hoisting(){
var i
console.log( i )
console.log( j )
i = 3
console.log( i )
}
hoisting()