Friday, 25 November 2016

Javascript: every, some, arrow function

Array.every() returns true when all the items meet certain condition

var nums = [5,7,10,17,20];
var nums2 = [11,17,20,23];

var allBig = nums.every(function(element){
    return element > 10;
});

console.log(allBig); //false

//ES6 arrow function
allBig = nums.every(element => element > 10);

console.log(allBig); //false

allBig = nums2.every(function(element){
    return element > 10;
});

console.log(allBig); //true

//ES6 arrow function
allBig = nums2.every(element => element > 10);

console.log(allBig); //true

Array.some() returns true when any item meets certain condition.
var nums = [5,7,10,17,20];
var nums2 = [11,17,20,23];

var allBig = nums.some(function(element){
    return element > 10;
});

console.log(allBig); //true

//ES6 arrow function
allBig = nums.some(element => element > 10);

console.log(allBig); //true

allBig = nums2.some(function(element){
    return element > 30;
});

console.log(allBig); //false

//ES6 arrow function
allBig = nums2.some(element => element > 30);

console.log(allBig); //false

No comments:

Post a Comment