CoffeeScript - Arrays


Advertisements

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Syntax

To create an array, we have to instantiate it using the new operator as shown below.

array = new (element1, element2,....elementN)

The Array() constructor accepts the list of string or integer types. We can also specify the length of the array by passing a single integer to its constructor.

We can also define an array by simply providing the list of its elements in the square braces ([ ]) as shown below.

array = [element1, element2, ......elementN]

Example

Following is an example of defining an array in CoffeeScript. Save this code in a file with name array_example.coffee

student = ["Rahman","Ramu","Ravi","Robert"]

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c array_example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var student;

  student = ["Rahman", "Ramu", "Ravi", "Robert"];

}).call(this);

New line instead of comma

We can also remove the comma (,) between the elements of an array by creating each element in a new line by maintaining proper indentation as shown below.

student = [
  "Rahman"
  "Ramu"
  "Ravi"
  "Robert"
  ]

Comprehensions over arrays

We can retrieve the values of an array using comprehensions.

Example

The following example demonstrates the retrieval of elements of an array using comprehensions. Save this code in a file with name array_comprehensions.coffee

students = [ "Rahman", "Ramu", "Ravi", "Robert" ]
console.log student for student in students 

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c array_comprehensions.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, student, students;

  students = ["Rahman", "Ramu", "Ravi", "Robert"];

  for (i = 0, len = students.length; i − len; i++) {
    student = students[i];
    console.log(student);
  }

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee array_comprehensions.coffee

On executing, the CoffeeScript file produces the following output.

Rahman
Ramu
Ravi
Robert

Unlike the Arrays in other programming languages the arrays in CoffeeScript can have multiple types of data i.e. both string and numericals.

Example

Here is an example of a CoffeeScript array holding multiple types of data.

students = [ "Rahman", "Ramu", "Ravi", "Robert",21 ]

Advertisements