'x' things I didn't know about JavaScript
I’ve been watching the Douglas Crockford Javascript Programming Language videos at http://developer.yahoo.com/yui/theater/. Here’s some bits that I didn’t know. I recommend these videos to anyone starting out with Javascript and coming from another development language.
- Javascript has falsy values and truthy values which are used with the boolean operators.
Falsy values are : false, null, undefined, “” (empty string), 0 (Zero) and NaN (Not a Number)
All other values, including objects are truthy (including “0″ and “false” as they are non zero length strings)
- The + operator either adds or concatenates. if both operands are numbers it will add them else it concatenates them.
Note: ‘$’ + 3 + 4 = ‘$34′ not $7
- All numbers are stored as 64bit floating point. Bitwise operators convert the number to a 32bit integer apply the bitwise operator and convert back to a floating point number. Therefore x << 1 is not faster than x * 2.
- Using == and != can use type coercion, so use === and !== for true equality checking of value and type and it’s therefore faster.
- The && and || operators don’t return a boolean value.
&& -> If the first operand is Truthy then the result is the second operand else the result is the first operand.
|| -> If the first operand is Truthy then the result is the first operand else the result is the second operand
- ! operator -> if the operand is Truthy the result is false else the result is true
- Avoid the with statement:
1: with (o) {2: foo = null;
3: }does the above code set o.foo to null or a global variable foo to null. By all accounts it depends on the object ‘o’. I guess if o does not have a foo variable then it would set the global foo. Either way it’s recommended to avoid with.
- { } Blocks do not have scope. The scope is at function level.
- If you forget to add a var before the variable definition, javascript assumes you meant it to be global. Do this in two places with the same name and they will refer to the same global variable!
- Items can be removed from an array by using delete myArray[index], however this leaves sets the item at index to undefined. To physically remove it splice(index,count) is used:
1: myArray = ['a', 'b', 'c', 'd'];
2: delete myArray[1];3: // myArray is now ['a', undefined, 'c', 'd']
4: myArray.splice(1, 1);5: // myArray is now ['a', 'c', 'd']
- How do you determine if a variable is an array or an object ?
1: value.constructor === Array2: // or
3: value instanceof Array - If you re concatenating more than 10 string elements, due a compound string being created at every stage of concatenation, add the strings to an array, then call .join to concatenate the strings in one go (by all accounts this concatenation causes less string allocations).