home ~ previous

Underscore.js

There is a lot of huff and puff about this Javascript library or that Javascript library. None more-so than Backbone.js. Now I am fond of this MVC take on Javascript, but I am more taken with one of its dependencies:

Underscore.js.

Although popular, it doesn’t seem to get anywhere near the same amount of press as Backbone.

This is a shame. This little library, takes away all of the 'awfulness' of Javascript.

As time passes, I intend to use this library every opportunity I can.

Here are some examples (for these, I am using the rather fab JSBIN, by the equally fab Remy Sharp. Make sure you add the _.js library in the preferences and output to the consol).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var Fruit = { 
  Apple : 'Quite good', 
  Pear : 'Fairly good',
  Mango : 'Mega fab'
           };
var keys = _.keys(Fruit);
var values = _.values(Fruit);
console.log(keys + values);
console.log(keys[1]);
console.log(values[2]);
console.log(keys[1] + " " + values[1]);

Now we can use the Underscore.js excellent extend function to extend the object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var Fruit = { 
  Apple : 'Quite good', 
  Pear : 'Fairly good',
  Mango : 'Mega fab '
};
var keys = _.keys(Fruit);
var values = _.values(Fruit);
// here we use underscore to extend the object to a new object: MoreFruit
var MoreFruit = _.extend((Fruit), {
   Banana : 'pretty fab'
});
// output all of the values
console.log ("These are Fruit " + keys + values);
// place it in a variable and access it as an array
var ckeys = _.keys(MoreFruit);
var cvalues = _.values(MoreFruit);

console.log (ckeys[1]);
console.log (cvalues[3]);

// or we can declare them like we would in vanilla JS
var xxx = (Fruit.Apple + " " + MoreFruit.Banana + " " + (10*10));

console.log (xxx);

home ~ previous

Rohan Leach .... thoughtful