How to use javascript functions

Javascript have very important role on modern web and mobile technologies. In this tutorial i want to show some javascript functions with samples.

Concat 

Concat function helps us to add array to another array.

Sample Use:

['a','b','c'].concat(['d','e','f']);
//return as a ['a','b','c','d','e','f']


Every

Expecting true answer from user defined function for every member of array.

Sample Use:

[3,5,6].every(function(num){
  return num < 8
});
//Return true because all array members are smaller then 8 
[3,5,6].every(function(num){
  return num < 4
});
//Return false because 3 smaller then 4 but 5 and 6 is not

Filter

We can use filter function to filter array with our conditions.

Sample Use:

[3,5,7].filter(function(num){
 return num < 6j
});
//Return as [3,5]

Foreach

It runs a function for every element in array

[3,5,7].forEach(function(num){
  console.log(num)
});
//Console will show like below
3
5
7

IndexOf

Return given element index number in array.

[1,2,3].indexOf(3); //return 2
["Angular","React","Backbone"].indexOf("Angular") // return 0

Join

Join all elements of array with seperator and return as a string,

["H","A","M","D","I"].join() // return H,A,M,D,I
["H","A","M","D","I"].join("") // return HAMDI
["M","E","A","N"].join(".") // M.E.A.N

LastIndexOf

Returns last index number of given element of an array

[1,2,3,4,4,3,5,6,7,8].lastIndexOf(3) // return 5

Map

Apply function to all array elements

[1,2,3].map(function(num){return num * 2})

// return [2, 4, 6]

Pop

Remove last member from array and return removed element

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

//return 3

Push

Adds a element to array

var array = [1,2,4];
array.push(5);
console.log(array); // return [1,2,4,5]

Reverse 

Reverse array elements

["M","E","A","N"].reverse() // return ["N","A","E","M"]

Shift

Remove first element from array and return removed element

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

//return 1

Slice

Return a part of array

[1,2,3,4].slice(1,3) // return [2,3]

Some

Check all elements of array and expect at least value return to true

[1,2,3,4].some(function(a){ return a > 2 }) // return true

[1,2,3,4].some(function(a){ return a > 5 }) // return false

 

 

Leave a Reply

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