When writing code in JavaScript, the if(variable)
clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example:
if (list)
for (var k in list) {
...
if (array)
for (var i = array.length; i >= 0; i--) {
...
However, JavaScript syntax allows expressions like
null || []
undefined || {}
This means that code can be shortened by one line while still checking the array or object effectively:
for (var k in obj || {}) {
...
for (var i = (array || {}).length; i >= 0; i--) {
...
One question that arises is whether the expression null/undefined || []/{}
will consistently return the latter option across all browsers.
edit: It has been discovered that using curly brackets instead of square brackets in the for (var k in list || {})
iteration is better because using an array leads to an iteration and may result in an exception being thrown.