Some javascripts functions that you should know

Some functions of Javascript are very important but some users does not know about them properly. using that function reduces code size and efficiency. we are providing list of some functions that is used on arrays and strings.

Array.isArray()

The Array.isArray() determines whether the passed value is an Array.

Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar'); // false
Array.isArray(undefined); // false

Array.concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

// results in a new array [ "a", "b", "c", "d", "e", "f" ]

Array.copyWithin()

The copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

['alpha', 'bravo', 'charlie', 'delta'].copyWithin(2, 0);

// results in ["alpha", "bravo", "alpha", "bravo"]

Array.prototype.entries()
The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.

var a = ['a', 'b', 'c'];
var iterator = a.entries();

console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
console.log(iterator.next().value); // [2, 'c']

Array.prototype.every()
The every() method tests whether all elements in the array pass the test implemented by the provided function.

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

[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

Array.prototype.fill()
The fill() method fills all the elements of an array from a start index to an end index with a static value.

var numbers = [1, 2, 3]
numbers.fill(1);

// results in [1, 1, 1]

Array.prototype.find()
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

function isBigEnough(element) {
return element >= 15;
}

[12, 5, 8, 130, 44].find(isBigEnough); // 130

Array.prototype.findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

function isBigEnough(element) {
return element >= 15;
}

[12, 5, 8, 130, 44].findIndex(isBigEnough);
// index of 4th element in the Array is returned,
// so this will result in '3'

Array.prototype.forEach()
The forEach() method executes a provided function once for each array element.

var a = ['a', 'b', 'c'];

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

// a
// b
// c

Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false

Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

var a = [2, 9, 9];
a.indexOf(2); // 0
a.indexOf(7); // -1

if (a.indexOf(7) === -1) {
// element doesn't exist in array
}

Array.prototype.join()

The join() method joins all elements of an array (or an array-like object) into a string.

var a = ['Wind', 'Rain', 'Fire'];
a.join(); // 'Wind,Rain,Fire'
a.join('-'); // 'Wind-Rain-Fire'

Array.prototype.keys()

The keys() method returns a new Array Iterator that contains the keys for each index in the array.

var arr = ['a', 'b', 'c'];
var iterator = arr.keys();

console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Array.prototype.lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

var numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1

Array.prototype.map()
The map() method creates a new array with the results of calling a provided function on every element in this array.

var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

Array.prototype.pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

var a = [1, 2, 3];
a.pop();

console.log(a); // [1, 2]

Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.

var numbers = [1, 2, 3];
numbers.push(4);

console.log(numbers); // [1, 2, 3, 4]

numbers.push(5, 6, 7);

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]

Array.prototype.reduce()
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

var sum = [0, 1, 2, 3].reduce(function(acc, val) {
return acc + val;
}, 0);
// sum is 6

var list1 = [[0, 1], [2, 3], [4, 5]];
var list2 = [0, [1, [2, [3, [4, [5]]]]]];

const flatten = arr => arr.reduce(
(acc, val) => acc.concat(
Array.isArray(val) ? flatten(val) : val
),
[]
);
flatten(list1); // returns [0, 1, 2, 3, 4, 5]
flatten(list2); // returns [0, 1, 2, 3, 4, 5]


Array.prototype.reduceRight()

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
return a.concat(b);
}, []);

// flattened is [4, 5, 2, 3, 0, 1]

Array.prototype.reverse()

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

var a = ['one', 'two', 'three'];
a.reverse();

console.log(a); // ['three', 'two', 'one']

Array.prototype.shift()

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

var a = [1, 2, 3];
var b = a.shift();

console.log(a); // [2, 3]
console.log(b); // 1

Array.prototype.slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var a = ['zero', 'one', 'two', 'three'];
var sliced = a.slice(1, 3);

console.log(a); // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['one', 'two']

Array.prototype.some()

The some() method tests whether some 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

Array.prototype.sort()
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']

var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.

var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.

Array.prototype.splice()

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); // insert 'drum' at 2-index position
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); // remove 1 item at 2-index position (that is, "drum")
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Array.prototype.toLocaleString()

The toLocaleString() method returns a string representing the elements of the array. The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma “,”).

var number = 1337;
var date = new Date();
var myArr = [number, date, 'foo'];

var str = myArr.toLocaleString();

console.log(str);
// logs '1337,6.12.2013 19:37:35,foo'
// if run in a German (de-DE) locale with timezone Europe/Berlin

Array.prototype.toSource()

The toSource() method returns a string representing the source code of the array.

The toSource method returns the following values:

For the built-in Array object, toSource returns the following string indicating that the source code is not available:
function Array() {
[native code]
}

Array.prototype.toString()

The toString() method returns a string representing the specified array and its elements.

var months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.toString(); // "Jan,Feb,Mar,Apr"

Leave a Reply

Your email address will not be published. Required fields are marked *

five × 1 =