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”]
Advertisements

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"