Array in Javascript

An array is used to store a collection of data. In javascript, data doesn’t need to have same type.

var arr = [ 1,"sam", true, {"name":"kumar"} ];

Declaration

Array can be declared in several ways,

Syntax Explanation Result
var myArray = new Array() Creates Empty Array [ ]
var myArray = new Array(3) Creates Array with
Length 3
Value all empty
[ ” “,” “,” ” ]
var myArray = [3] Creates Array with
length 1
Value 3
[3]
var myArray = new Array(1,2,3) Creates Array with
length 3
Value 1,2,3
[1,2,3]
var myArray = [“apples”, “bananas”, “oranges”] Creates Array with
length 3
Value “apples”, “bananas”, “oranges”
[“apples”, “bananas”, “oranges”]

Properties

Topics Syntax Explanation Result
Length var arr = [5,6,7];
arr.length;
returns number – Length of the array 3
Prototype Array.prototype.myUcase = function() {
for (i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase();
}
};
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.myUcase();
Prototype is the concept of creating/modifing objects method.

In our case we created a method “Ucase”, which convert all the values in array to uppercase

[BANANA,ORANGE,APPLE,MANGO]

Methods

Topics Syntax Explanation Result
Concat
var a = [1,2,3];
var b = [4,5,6];
var c = a.concat(c);
This method adds two array [1,2,3,4,5,6]
var d = [].concat(a); For coping array to new variable, if we use like ( var var d = a; ) , ‘a’ don’t copy to ‘d’, instead it got refered. which means if u change any one of the array others get the change too.

So can use “Concat” to copy array to other variable.

d = [ 1,2,3 ]
Filter var age = [12,34,56,23];
var voter = age.filter(function(value, index){
return value > 18
});
Filter return a array with value which ever passes the given condition.

Returns array

voter = [34,56,23]
ForEach var a = [2,3,4];
a.forEach(function(val, index){
console.log(index+” : “+val);
});
Its a loop by which we can get all the values of the array one by one 0 : 2
0 : 3
0 : 4
Join var a = [2,3,4,5];
a.join(“/”);
Join convert array to string in which it concatinate all the array value with given symbol

Returns: string

“2/3/4/5”
Map var a = [2,3,4];
var b = a.map(function(val, index){
return val*val;
});
Map can change each value of the array

Returns array

[4,9,16]
Push var a = [2,3,4];
a.push(5);
Insert value to the array at last a = [2,3,4,5]
Pop var a = [2,3,4];
a.pop();
Remove value to the array at last a = [2,3]
UnShift var a = [2,3,4];
a.unshift(5);
Insert value to the array at First a = [5,2,3,4]
Shift var a = [2,3,4];
a.shift();
Remove value to the array at First a = [3, 4]
Splice var a = [1,2,3,4];
a.splice(2,1,7,8);
Splice add & remove value from the array
1st argument – Index – “where to start”.
2nd argument – delete – “how many value to be deleted”
from 3rd to “N” – “values to be added”array.splice( index , howManyToDelete, add1,.., addN)Returns Deleted value as array
Slice var a = [1,2,3,4];
var b = a.slice(1,3);
Slice select part of the array and form new array

Returns array

[2,3]
IndexOf var a = [2,3,4,5,6,4,7];
a.indexOf(4);
a.indexOf(6);
Return the first index value of specified item in the array

If not present returns “-1”

Returns: Number

2 \\ index of 4
-1 \\ since not present
LastIndexOf var a = [2,3,4,5,6,4,7];
a.lastIndexOf(4);
a.lastIndexOf(9);
Return the last index value of specified item in the array

If not present returns “-1”

Returns: Number

5 \\ index of 4
-1 \\ since not present
isArray var a = [1,2,4,3,4];
var b = “sam”;
typeof a;
Array.isArray(a);
Array.isArray(b);
If you try “typeof” for an “array”, it will return “Object”, thats where “isArray” comes. Finds whether the variable is array or not

Returns Boolean

“object” \\ result of “typeof”
true \\ for “a”
false \\ for “b”
Reverse var a = [1,2,3,4];
var b = a.reverse();
Reverse the order of the value in the array

Returns reversed array also changes the original array

[4, 3, 2, 1]
Sort var a = [3,2,4,1];
a.sort(function(a,b){ return a-b; });
a.sort(function(a,b){ return b-a; });
Sorts the array. it changes the original array.

Return the sorted array

[1, 2, 3, 4] \\ ascending
[4, 3, 2, 1] \\ decending
Advertisements

Disable Right Click and Show Div

To do this we need 2 node, One is the div which the right click is to be disabled and the other is the div which going to show instead of “contextmenu”.

 var rClickDisabledDiv = document.getElementsByClassName("rightClickDisabled")[0];
 var showDivNode = document.getElementsByClassName("showDiv")[0];

The key here is how to disable the right click.

  rClickDisabledDiv.addEventListener("contextmenu",function(e){
      showDivNode.style.display = "block";
      showDivNode.style.top = e.pageY+"px";
      showDivNode.style.left = e.pageX+"px";
      e.preventDefault();
  });

Rest will be piece of cake 🙂

function divOnRightClick(rClickDisabledDiv, showDivNode){
  rClickDisabledDiv.addEventListener("contextmenu",function(e){
      showDivNode.style.display = "block";
      showDivNode.style.top = e.pageY+"px";
      showDivNode.style.left = e.pageX+"px";
      e.preventDefault();
  });
  document.body.addEventListener("click",function(){
    showDivNode.style.display = "none";
  });
  showDivNode.addEventListener("click",function(e){
    e.stopImmediatePropagation();
  });
}

Demo

Decalation of Array in Javascript

An array is used to store a collection of data. In javascript, data doesn’t need to have same type.

var arr = [ 1,"sam", true, {"name":"kumar"} ];

Declaration

Array can be declared in several ways,

Syntax Explanation Result
var myArray = new Array() Creates Empty Array [ ]
var myArray = new Array(3) Creates Array with
Length 3
Value all empty
[” “,” “,” “]
var myArray = [3] Creates Array with
length 1
Value 3
[3]
var myArray = new Array(1,2,3) Creates Array with
length 3
Value 1,2,3
[1,2,3]
var myArray = [“apples”, “bananas”, “oranges”] Creates Array with
length 3
Value “apple”, “banana”, “orange”
[“apple”, “banana”, “orange”]

Get Postal code using latitude and longitude

Working Demo.

$(function() {
    var lat = 13.0826802;
    var longt = 80.27071840000008;
    var keyVal = "AIzaSyDm6BvPpVO0Fc2JRcXuRuafyX6mBr31nwM";
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + longt + '&key=' + keyVal,
        type: "GET",
        dataType: 'json',
        async: false,
        success: function(data) {
            var results = data.results;
            var postalCode = getPostalCode(results);

            alert(postalCode);
        }
    });

    function getPostalCode(place) {
        for (var k = 0; k < place.length; k++) {
            for (var i = 0; i < place[k].address_components.length; i++) {
                for (var j = 0; j < place[k].address_components[i].types.length; j++) {
                    if (place[k].address_components[i].types[j] == "postal_code") {
                        return place[k].address_components[i].long_name;
                    }
                }
            }
        }
    }
});

Hoisting in javascript

Hoisting is JavaScript’s default behavior of moving declarations to the top.

function hoistTest(){
   x = 5;            // Assign "5" to x - now x is a global variable
   console.log( x ); // returns "5"
   var x;            // Declare x - now x is a local variable
}
hoistTest();
console.log( x ); // returns undefined

In the above example we assigned value for “x” without declaring it and declared it at last of function. But once javascript runs the declaration moved to top and “x” becomes the local variable. Hence outside the function it becomes undefined. This is how the “x” declaration in hoisted.

If not declared, “x” stays as global variable.

function hoistTest(){
   x = 5;            // Assign 5 to x - now x is a global variable
   console.log( x ); // returns "5"
}
hoistTest();
console.log( x ); // returns "5"

JavaScript Design Patterns

Creational Patterns   Abstract Factory Creates an instance of several families of classes   Builder Separates object construction from its representation   Factory Method Creates an instance of sev…

Source: JavaScript Design Patterns