Wiki

Clone wiki

DevFecta Public Repository / JavaScript

Loops

forEach() for Arrays

array.forEach(function(element) {
    console.log(element);
});

push()

Add items to an array with push().

array1.forEach(function(item){
    array2.push(item);
});

every()

Returns true if every value is below 40.

function isBelowThreshold(currentValue) {
   return currentValue < 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

array1.every(isBelowThreshold);

some()

Tests whether at least one element in the array passes the test implemented by the provided function.

function isBiggerThan10(element, index, array) {
    return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

// Shorthand
[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

// OR
function checkAvailability(array, passedValue) {
  return arr.some(arrayValue=> passedValue === arrayValue);
}

checkAvailability(array, 'kela');   // false
checkAvailability(array, 'banana'); // true

find()

Returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

var array = [5, 12, 8, 130, 44];

var found = array.find(function(element) {
    return element > 10;
});
// Returns 12

findIndex()

Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating no element passed the test.

var array = [5, 12, 8, 130, 44];

function isLargeNumber(element) {
  return element > 13;
}

// Returns the index of 3

Updated