Javascript wrinkles
Notes for people who think console.log()
is inherently interesting.
Javascript notes and quirks
- The plus operator:
+
- strings containing numbers work in calculations if prefixed with a
+
sign e.g. add these: +"1.1" + +"1.1"
.
- Check existence
var myArray = new Array(); if (!myArray[0]) {console.log("Not defined")}
uses false
to print the statement.
- Variable scope
-
local to the code a block resides within (not block statement scope). They are also 'hoisted' as if at the top of a function/statement.
Try this function Scope() { if (true) { var x = 5 }; alert("x: " + x + ", y: " + y); }; var y = 6;
- Constants
-
Declared with the
const
keyword, e.g. const prefix = '212';z = prefix + 424;alert(prefix);
.
Constants cannot share a name with a function or variable in the same scope, or be called directly e.g. alert(prefix);
.
- Literals
- Array literals (literals have fixed values) use square brackets:
var mynums = ["one", "two", "three"]; alert(mynums[0])
.
- Avoid spaces after
\
in multiline string literals
- Always add a return immediately after
\
as '\
' will produce an error. This multiline string is broken before 'another'.
- Return the entire code for a function
- Simply omit the brackets
alert(IsDefined)
- Retrieving values from an object
-
value by dot notation:
flight.departure.IATA
value by name: flight['number']
(Douglas Crockford: Javascript: the Good Parts, or the video or a series)
value of array element in object: employees.accounting[1].firstName
(from Mastering JSON)
- Using the file api
- HTML5 allows interaction with local files via its File API specification - test your browser's file api here.
Javascript good practice
- Don't use
++
or --
- Use
+=
and -=
instead, as ++
and --
are too tight, too tricky, too cryptic (Crockford)
- Use
===
and !==
for comparison
- This will ensure that:
0, '', undefined, null, false, true
all return the expected result. Both ==
and !=
do type coercion before comparing. This causes \f\r\n\t == 0
to be true. If you want this, use the shorthand (foo)
and (!foo)
instead of (foo != 0)
and (foo == 0)
(Crockford)
- Avoid using
new
- Don't use
new
to create a Boolean
, Number
or String
; and use {}
and []
to create a new Object
or Array
- Use
object.create
, but not for arrays
- because object produced will inherit the array’s values and methods, but lack the length property.
- Declare functions before you call them
- and declare variables at the top of functions, avoiding
for(var i
...
- Name constructor functions with an initial capital
- to help spot instances where they're called without
new
. Better: use object.create
(instead of new
) for a new instance of a specific object.