ES6 for C# developers

ES6 came with a lot of new functionality, and finally I've found some time to go through them!
I must admit - Javascript from "must" has evolved to something that can be called flexible and usable language! So let's start with side-by-side comparison of C# and ES6!

Class declaration

Simple C# class:

public class Foo  
{
  private int _property;
  public int Property { get { return _property; } }
  public Foo(int property){
    _property = property;
  }
  public BarMethod(){
    _property*=2;
  }
}

and ES6:

class Foo {  
    constructor (property) {
        this.property = property;
    }
    Property(){
      return this.property;
    }
    BarMethod () {
        this.property*=2;
    }
}

Neat! No prototypes, factories, anything! Real class declaration.

Class inheritance

Sample Bar class inherited from Foo...

public class Bar : Foo  
{
  public Bar(int property) : base(property+1) { }
}

...looks just like we would expect!

class Bar extends Foo {  
    constructor (property) {
        super(property+1);
    }
}

But that is just the beginning. Features that made me feel like at home are coming!

Generator functions

In C# we've got methods that returns IEnumerable. We can use yield return inside to create a sequence:

...
public IEnumerable<int> ConsNumbers(int start){  
  for(;;)
  {
    yield return start++;
  }
}
...

We don't have to explicitly define, when the sequence will be over. The caller will specify how many elements it wants.
Now it is possible as well in ES.

function* consNumbers (start, end, step) {  
    for(;;){
        yield start++;
    }
}

Or using iterator protocol:

let consNumbers = {  
    *[Symbol.iterator]() {
        let start = 0;
        for (;;) {
            yield start++;
        }
    }
}
//and print some numbers:
for (let n of consNumbers) {  
    if (n > 1000)
        break;
    console.log(n);
}

These constructs are really similar!

Arrow functions

Lambdas in Javascript? Yes, please.
This:

odds  = evens.map(v => v + 1);  

and this:

nums.forEach(v => {  
   if (v % 5 === 0)
       fives.push(v);
})

Look pretty much the same as:

odds = evens.Select(even => even+1);  

and:

// ToList() maybe needed if enumerable
nums.ForEach(v => {  
    if(v % 5 == 0) fives.Push(v);
  });

Thanks to array functions and generators, functional-like code can be easily written in very readable manner.
I've started thinking about switching to ES6 and Node.js right now.

Check all those handy features here