Google News
logo
CoffeeScript - Interview Questions
What about Objects and Arrays in CoffeeScript?
The CoffeeScript literals for objects and arrays look very similar to their JavaScript cousins. When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to YAML.
song = ["do", "re", "mi", "fa", "so"]
​
singers = {Jagger: "Rock", Elvis: "Roll"}
​
bitlist = [
  1, 0, 1
  0, 0, 1
  1, 1, 0
]
​
kids =
  brother:
    name: "Max"
    age:  11
  sister:
    name: "Ida"
    age:  9
var bitlist, kids, singers, song;
​
song = ["do", "re", "mi", "fa", "so"];
​
singers = {
  Jagger: "Rock",
  Elvis: "Roll"
};
​
bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
​
kids = {
  brother: {
    name: "Max",
    age: 11
  },
  sister: {
    name: "Ida",
    age: 9
  }
};
​
CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name. Note that the { and } are required for this shorthand.
name = "Michelangelo"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
var mask, name, output, turtle, weapon;
​
name = "Michelangelo";
​
mask = "orange";
​
weapon = "nunchuks";
​
turtle = {name, mask, weapon};
​
output = `${turtle.name} wears an ${turtle.mask} mask. Watch out for his ${turtle.weapon}!`;
Advertisement