Simple javascript ECMA 6 lambda examples

Lets create an index.html file with below content

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <script src="main.js"></script>
       <h6>ECMA 6 Javasscript</h6>
    </body>
</html>

The main.js script file will hold the example

//declare an array with some values
const numArray = [12,23,45,23,34,11,00,09,78,66,01,05,83,45,64,49];

// Filter the numbers that are greater than 20
const numsGrtThan20 = numArray.filter( num => num > 20);

console.log(numsGrtThan20);

const numMapsqrt = numArray
.filter( num => (num > 10 && num < 50))
.map(n => n*2).map(m => Math.sqrt(m));

console.log(numMapsqrt);

const mapReduce = numArray.filter(n => n < 10).reduce((total,num)=>(total+num),0);
console.log("map reduce : "+mapReduce);

//Without functional approach
const sum = numArray.reduce(function(total,num){
  return total + age;
  },0);

In order to execute the above, we can use 200 OK a web sever plugin available in Chrome.

  • Load the index.html file to the plugin and start the server. The index.html file should be loaded.
  • Enable the console using Developer Tools, to see the console message from script file.