Sunday, March 19, 2017

Dynamic function

var dinner = {
    menu: {
        getMenu: function (type) {
            var menu = 'menu: ', list = dinner.menu.items.list, items = dinner.menu.items;
            function defaultMenu(type) {
                var item = "continental" == type ? "Batter Fish" : "Rice";
                console.log("From defaultMenu " + item);
                return item;
            };

            for (var i = 0; i < list.length; i++) {
                console.log("Get menu for " + list[i] + "/" + type);
                menu += (items[list[i]].getMenu || defaultMenu)(type);
                if (i < list.length - 1) {
                    menu += ",";
                }
            }
            return menu;
        },

        items: {
            list: ['starter', 'maincourse'],

            starter: {
                getMenu: function (type) {
                    var item;
                    if ("continental" == type) {
                        item = "Baked Mushrooms";
                    } else if ("chinese") {
                        item = "Spring Rolls";
                    } else {
                        item = "Baked Potatoes";
                    }
                    console.log("From starter menu " + item);
                    return item;
                }
            },

            maincourse: {
                getCustomizedMenu: function (ingredients) {

                }
            }
        }
    }
}

console.log(dinner.menu.getMenu("continental"));
console.log(dinner.menu.getMenu('chinese'));
Output:
Get menu for starter/continental
From starter menu Baked Mushrooms
Get menu for maincourse/continental
From defaultMenu Batter Fish
menu: Baked Mushrooms,Batter Fish
Get menu for starter/chinese
From starter menu Spring Rolls
Get menu for maincourse/chinese
From defaultMenu Rice
menu: Spring Rolls,Rice

Wednesday, March 15, 2017

Arguments example

The arguments object is a local variable available within all functions. It contains the arguments passed into the function.
var f = function()
{
    var list = arguments;
    for (var i = 0; i < arguments.length; i++) {
        console.log("argument: " + list[i]);
    }
}
f("one");
f("one", "two");
Output:
argument: one
argument: one
argument: two

Anonymous function

Below is an expression where the anonymous function is evaluated and result is assigned to variable x.
var x = function() { 
console.log("Function ran");
}();
If we don't assign it to a variable, there will be a syntax error.
function() { 
console.log("Function ran");
}();
You'd get a syntax error, because the JS parser thinks it is a statement. Below will work:
function f() { 
console.log("Function ran");
};
f();
If you notice the above worked as the function has now a name and then we called the function. But then how do we make the parser know that we want an anonymous function as an expression? would see the 'function' keyword and assume you're starting a function statement of the form: If an entire javascript is about execution of a function then the function need to be an anonymous function with parenthesis around it.
(
function() { 
console.log("Function ran");
}
)();
Output:
Function ran

Sunday, March 12, 2017

Array push Example

function toArray(source)
{
 var result = [];
 
 for (var i = 0; i < source.length; i++) 
  result.push(source[i]);
  
 return result;
};
console.log(toArray("Hello").toString());
Output:
H,e,l,l,o

Saturday, March 11, 2017

Object Example

Run the below snippet in chrome's developer tools.
function fullName(initial,firstName) {
 return initial + "." + firstName;
}
var person =  [{
        firstName:"Sam",
  initial:"M",
        age:42,
        address:{nbr:10, street:"Street1", place:"Oakland"},
  name:fullName(person[0].firstName,person[0].initial)
    },
    {
        firstName:"Shyam",
  initial:"N",
        age:42,
        address:{nbr:10, street:"Street1", place:"Oakland"},
  name:function(){return this.initial + "." + this.firstName;}
    },
    {
        "first-name":"Ryan",
  initial:"S"  
 }
  ];
console.log(person[0].name);
console.log(person[1].name());
console.log(person[1].name);
console.log(person[1].address.place);
console.log(person[2]["first-name"]);
If the object key has a hyphen in it, you won't be able to use it directly but will work if is surrounded with quotes. As you can see from above object literal person declared has key first-name surrounded with quotes. In order to refer to the property, you will use:
person[2]["first-name"];
Output:
M.Sam
N.Shyam
function (){return this.initial + "." + this.firstName;}
Oakland
Ryan

Array Example

array.html:
<html>
<head>
<script type="text/javascript">
    function printPersons() {
        var persons = new Array();

  persons[0] = ["Sam", 41, [10, "street1", "Oakland"]];
  persons[1] = ["Shyam", 21, [1, "street2", "Mumbai"]];
  persons[2] = ["Rob", 32, [12, "street3", "Rotterdam"]];
 
        var msg = "";
        document.open();
   
        for (var i = 0; i < persons.length; i++) {
            msg = msg + persons[i][0] + "-" + persons[i][1] + "-" + 
                        persons[i][2][0] + "-" + persons[i][2][1] + "-" + 
                        persons[i][2][2] + "<br/>";
        }  
  
        document.write(msg);
        document.close();
    } 
</script>
</head>
<body onload="printPersons()">
Array example
</body>
Output:
Sam-41-10-street1-Oakland
Shyam-21-1-street2-Mumbai
Rob-32-12-street3-Rotterdam

Friday, March 10, 2017

Alert Example

Alert

As soon as the javascript block is loaded, an alert pops up.
<html>
<head>
<script type="text/javascript">
alert("Hello, World!");
</script>
</head>
<body>
Alert example
</body>