Keep it hidden. You shouldn't pollute the global scope unless necessary.
(function(){
var your_script;
})();
Using the same 'immediately invoked function' you can get a hold of an undefined variable which is `undefined`
(function(undefined){
var your_script;
// now you compare for `undefined` using:
if (your_script === undefined){
// ...
}
})();
Map and Reduce
var l = [21,49,80,43,59];
var doubled = l.map(function(d){
return d*2;
});
var max_value = doubled.reduce(function(a,b){
return a > b ? a : b;
}, 0);
Filter
var l = [
{id: 5, username: 'bill', age: 32},
{id: 6, username: 'john', age: 24},
{id: 7, username: 'brad', age: 17}
];
var adults = l.filter(function(o){
return o.age >= 18;
});
Augmenting an array of elements with forEach
var l = [
{id: 3, first_name: 'john', last_name: 'doe'},
{id: 4, first_name: 'bill', last_name: 'masset'}
];
l.forEach(function(o){
o.full_name = o.first_name + ' ' + o.last_name;
});
Objects, the right way
var object_factory = function(params){
var hidden_property = 42;
var built_with_params,
etc;
var hidden_func = function(m,n){
return m > n;
};
return {
public_method: function(){
return hidden_property;
},
another: function(m,n){
hidden_func(m,n);
}
}
};
Arrays are objects, too
var l = [1,2,3,4,5];
l.total = l.reduce(function(a,b){ return a + b; }, 0);
So comparing equality also acts like objects, not primitive lists
> [] == []
false
> ['a'] == ['a']
false