Wednesday, April 25, 2012

Naked JavaScript - Function Access And Invocation

In part 3 of the series Naked Javascript , we are going to talk a little more about functions in Javascript. In the previous article, we just got a basic introduction to JavaScript functions. In this part and the parts that follow, we are going to rip them apart.

Ok, the first thing that you need to know is that - Functions are Awesome. And thats with a capital A(and a capital F!).




In Javascript, functions are first class objects. A function is an object with a special ability - the ablility to be invoked. There are basically 4 ways in which you can invoke a function.

1) The usual way


function boring(msg){
 console.log('oh, this is so so conventional '+ msg);
};

boring('You are killing me!');


2) The unusual way - anonymously


(function cool(msg){
 cool('Do you think that I am cool? ' + );
})('Totally!');


3) Using the Call method


function callMe(msg){
 console.log('Thanks for calling us ' + msg);
}

callMe.call(this, 'Yea, right..');

The syntax for the call is pretty straightforward. The first argument is the context in which the function is to be invoked. The remanining arguments, that you provide as comma separated values is are sent as arguments to the function.


4) Using the Apply method


function applyMe(msg){
 console.log('Do you want me to apply something? ' + msg);
}

applyMe.apply(this,['yes']);

This syntax is similar to the call syntax. The only difference being the fact that you need to pass an array as the parameter to the function instead of a comma separated list as you did in the syntax for call.




We saw the first two techniques in the previous post. But what makes the last 2 techniques so awesome? The answer lies in understanding the concept of a function context and a better understanding of the syntax of accessing properties in Javascript.

Lets talk about the object syntax first. As we saw earlier, functions can be declared on objects as if they are normal properties. In fact, they are normal properties(albeit on steroids, but thats a secret...). Now, the world and its mother knows that one can access properties of objects using the dot operator. But thats convetional and not to mention, dead booring(because we do it all the time). Javascript to the rescue! Javascripts makes things a bit more interesting for us by allowing you to access objects using a different syntax, like a map. For example, check out the code below

var bingo = {name:'xyx', desc:'I am Mr Bingo'};

//The uncool way of accessing a property of an object
console.log(bingo.name);
//The cool way of accessing a property of an object
console.log(bingo['desc']);


Note the special syntax that we used to access the desc property. We simply used the property name as a string in inside the brackets and were able to access the value of the property. This means that objects can be accessed as if they are key-value maps. This is a really cool feature when it comes to functions because functions are objects too. And that means that even they can be accessed via the same technique. This makes it possible to write something like this

var bingo={};
bingo.sayHello=function(){
 console.log('hello');
};

bingo.shout=function(){
 console.log('Scream at the top of my lungs');
};

function doAsISay(funcName){
 bingo[funcName]();
}

doAsISay('sayHello');
doAsISay('shout');


Did you see that!! You can dyanmically pass the function name as a parameter. So you can invoke a function at runtime and not even need to know its name. The doAsISay function acts as a function invoker and invokes any function that is available on the bingo object.




An advantage of using the map syntax for accesing object properties is that it lets you use reserved keywords as keys without the runtime complaining about it. Althouth, I dont think it makes good sense to use keywords as object properties since no matter what programming background you come from, watching a keyword being used anywhere always tends to trigger a train of thought that may not be on the same track of the program that you are working on. However, in a few corner cases, if you do find the need to use reserved keywords as object keys, you are more than free to do so.

We are still not done with functions. Functions are the heart of Javascript, and like all matters of the heart, this one will take its time too. In the next article, I am going to contine with functions and give them another shot to exhibit their awesomeness.

Happy Fungramming!
Ryan

Wednesday, April 18, 2012

Naked JavaScript - Function Basics

After talking about the basics of objects in the previous article, in part 2 of this series - Naked Javascript, we will discuss a little more about objects, their properties and take a sneak peak at functions in javascript.

As we learnt in the previous post, in Javascript you can create objects of the same class but each object can have a different set or properties. Properties can be defined on javascript objects even after they have been declared and used any number of times. For example, you can do this in javascript.

var bingo = {name:'xyz'};
bingo.says = 'hello';
bingo.volume = 5;


As you see, you can add properties to a javascript object even after the object has been declared and initialzied. This is something that cannot be done in Java because each object in Java MUST confirm to the structure of the class of which it is an instance. This feature of being able to dynamically create new properties for existing objects in javascript is called expandos.

If javascript allows you to create expando properties, it also lets you delete them dynamically. Here's how you would delete a property from a javascript object.

delete bingo.volume;


The above statement will delete the volume property on the bingo object thereby clearing the memory occpied by the object's value.

Not only can you declare properties on javascript objects, but you can also declare functions. It would'nt be too far fetched to say that functions are the actual building blocks of javascript.





Functions can be defined in Javascript in a couple of ways.

1) The not so cool way

function doSomethingCool(){
 console.log('I do something mindblowingly cool');
}


2) The cool way - Anonymous functions

function (){
 console.log('My parents forgot to name me!');
};


As you see, an anonymous function has no name(and hence the name 'anonymous' functions! Now that kinda reminds me of the saying - those that have nobody have god). There are many ways in which you can use anonymous functions. But before you start using functions - anonymous or non anonymous, you need to make a clear mental note of one point - Like everything else in javascript, functions are objects too! which means that you can assign it to a variable(huh?).

Lets try to build upon the above 2 examples annd try to assign these functions to variables.

function doSomethingCool(){
 console.log('I do something cool');
}

var makeSomeNoise = doSomethingCool;


Oh! Scary! Well, if you've ever worked with Java, then it might be. However there are some similarities between the two languages. When you assign the function doSomethingCool to the variable makeSomeNoise, you are simply creating another reference to the function. Now both the objects - makeSomeNoise and doSomethingCool refer to the same function. That is why, if we wished to, we could rewrite the first Method of function declaration using the second syntax! See the code below

var doSomethingCool = function(){
 console.log('I do something cool');
}


This way of declaring the function doSomethingCool is exactly equal to the Method 1, the only difference being the syntax. The point to be noted here is that a function name is actually nothing but a variable declared in the local scope.

Although the 'not so cool way' of defining functions is extremely convenient to use, the above syntax in which you assign a variable to an anonymous function makes it extremely easy to always remember that a method name is nothig but a javascript object, albeit not an ordinary one. I will elaborate more about that in the upcoming articles.





Now that you know that function names are actually objects, you can do some weird stuff with it. Something that you could have never do using Java. For example, take a look at the code below

//Define the function
function doSomethingCool(){
 console.log('I do something cool');
}

//Invoke the function
doSomethigCool();

//Assign the function name to point to a different function
doSomethingCool = function(){
 console.log('I do something hot');
}

//Invoke the function again
//This time the function will print a different message
doSomethingCool();


Check your browser's console to verify the output. (Just in case you dont know, if you are using Google Chrome you can press F12 or Ctrl+Shift+I to open the chrome developer tools and click on the "console" tab. If you are using Firefox, you need to install the Firebug extension and then you can press F12 to get the firebug console and then select the "console" tab to view the console messages)

Another cool thing that you might want to know about functions is the way in which it is invoked. In the above examples, we created a few functions and assigned names to them. After that we were able to invoke them using the ordinary function invocation syntax. But what do we do if we want to invoke an anonymous function? The solution is simple(and interesting!)

(function(){
 console.log('I am anonymous');
}) ();


Notice the braces that enclose the anonymous function definition and the bracecs that follow the function name. Using the above syntax, you can invoke not only an anonymous function, but any function. lets see an example.

var usefulStuff = (function makeUsefulStuff(){
 var bingo={desc:'My name is Bingo'};
 return bingo;
})();


Observe the syntax closely. I have simply created a function and invoked it. Inside the function, I created a local variable in the function called 'bingo' and that's what I returned from the function. The immediate function invocation causes the return statement to execute. So, now, the variable usefulStuff and the variable bingo point to the same object. Note that in this case, just because we invoked the function immediately, usefulStuff does not reference a function, instead it references an ordinary object that was returned by the function. Its is quite possible that when reading someone else's code you might forget to read the braces. After all, they are so tiny and close together. But, just in case you find yourself expecting one object and actually getting another, remember to look for a sneaky pair of braces somwhere after the function defintion and you might just save yourself a buttload of hair.





Coming back to the topic of declaring functions as object properties, the sytnax is pretty simple. Check out the sample code below

//Create an object;
var coolObject ={};

//Declare a function on the object
coolObject.doSomethingCool=function(){
 console.log('Do something cool');
};


Although we say that we are declaring a function on an object, we are actually doing nothing but creating a new property on the object that refers to a function definition. Which means that you can even do the following.

var coolObject ={};

//Declare a function on the object
coolObject.doSomethingCool=function(){
 console.log('Do something cool');
};

coolObject.doSomethingCool();

//What!! You can even make it a string now! No way!
//But apparently you can!
coolObject.doSomethingCool = 'I am a string';

console.log(coolObject.doSomethingCool);


This seems to work because the property 'doSomethingCool' was nothing but a reference to a function. We can reassign it to anything that we wish to at any point of time.





Well, that covers a few nuances of functions. But there is a lot more cool stuff that we will uncover in the upcoming articles! Stay tuned!

Happy Fungramming!
Ryan

Wednesday, April 11, 2012

Naked JavaScript - Object Basics

In this series- Naked JavaScript, we are going to delve into the gory details of javascript and extensively elaborate on its features like objects, functions, classes, inheritance, prototypes and closures.

In part 1 of this series, I am going to talk about objects in javascript. And since almost everything in javascript is an object, maybe I can say that I am practically talking about the basic fundamentals of the language. In one way, this part is just a foundation for all the rest of the articles that follow in this series.

Javascript deals heavily with objects. It deals with them at so many levels that sometimes its unfathomable if you are used to writing code in 'conventional' languages like Java or C or C#. Everything from functions to inheritance to arrays take on a completely different perspective in Javascript and this makes the language  unpredictable for a to programmers from a different programming background.

Before we begin, there is one important statement that I want to start with. And that is 'Almost everything in javascript is an object.'



That said, lets see how we can create objects.
There are mainly 2 ways in which you can create objects
  1. Using the new keyword.
  2. Literal declaration.


Using The New Keyword

This is something that programmers from conventional languages are quite used to. The syntax is simple and elegant. You just create a new object and assign it to a variable.

var bingo = new Object();


Since I have worked extensively in Java before, I can say that this seems quite straightforward. In Java, the Object class is the parent class of all the classes. In the same way, the Object class in javascript is the main class from which all Objects inherit features. And because everything is an object, the fact that javascipt does not have predefined types seems to be a misnomer. There is in fact one master type, and that type is Object. No matter who you are or what you do, remember that the almighty Object is watching you!

If you are not sure of my previous statement, try this.


var bingo = new Object();
console.log(typeof bingo);
bingo=10;

console.log(typeof bingo);


As you can see above, we used the typeof operator to determine the type of an object. What you also would have noted is that even though bingo is an object, it was perfectly ok for us to assign a numeric value to it. And when we printed out the type of the variable bingo, we got the type as number. There is a very interesting story of inheritance in javascript that makes this possible. Its something that we will be discussing in absolute details in another article. For now, just be happy with the fact that you dont need to worry about the type of an object before assigning a value to it.



Literal declaration

This is perhaps the most common way to declare objects. The reason being, that its so easy that sometimes its baffling that you can even do this.

var bingo2 = {};


This is very easy on the fingers because it saves you a few keystrokes but it is practically equivalent to

var bingo = new Object();


If you are not used to this syntax, you better get used to it. Because to be honest, its not such a bad thing. In fact its pretty cool!



Declaring Properties On Objects

Objects are objects. And objects are meant to store information. However there is is a slight deviation from conventional languages here. When you create objects, you can directly declare new properties on those objects and assign values to them. Unlike Java, where you must have a predefined class where you first define the properties and the methods of the objects that you create, Javascript lets you do things differently. Lets see that with an example.


var bingo1 = {}; //Create an object of type Object
var bingo2 = {}; //Create another object of type Object
bingo1.shouts = 'hey!';
bingo2.says = 'hello';


Observe carefully. In the above examples, although the type of the objects bingo1 and bingo2 are the same, the language permits you to dynamically declare new properties on each of these objects and those properties dont even need to be same. Although the objects seem to be different because the contain different information, the typeof operator returns the same value for each of these variables.

(typeof bingo1==typeof bingo2) //This returns true


This is something that cannot be done in Java where you can have two objects with a completely different set of properties but still belong to the same class. You dont have the blueprint of a class in Javascript.But that does not mean that you cant have classes in Javascript. It just means that the concept of classes works a bit differently in Javascript.



This makes a short introduction to what is meant by objects in Javascript. That said, in this series, we will explore many more amazing features of the Javascript language such as functions, closures, prototypes and the different ways in which all of these ideas intertwine to create the web as we know it.

Happy Fungramming!

Ryan

Sunday, April 8, 2012

How to clear the javascript console in google chrome or firebug programmatically

Just a quick tip.

If  you are extensively working with the console in the chrome developer tools and the console in Firefox/firebug and you find the need to clear the console many times while you are testing your code, both Chrome and Firefox have a feature that lets you do that programmatically.


Chrome
clear()

Firefox
console.clear()


I feel that the Firefox version of the command makes more sense. I have absolutely no idea why the Chrome guys chose to do it differently.

If you are a mouse person, in chrome, you can use the context menu and select Clear Console. If you are using firefox instead, you can use the clear button on top of the firebug console. But I guess you know that already.

There are a few gocha's though.


  • While you can invoke console.clear() in Firefox from within your own JavaScript to clear the console, you cannot use the clear() function in chrome to clear the console from your own JavaScript.
  • Another point to be noted is that in case you are getting an "undefined" message upon typing the clear() function in chrome, you need to disable the option to preserve logs upon navigation for the console. You can do that by right clicking on the console and unticking the "preserve log upon navigation".
If you are a fan of typing, chrome also lets you clear the console via a longer api command - console._inspectorCommandLineAPI.clear(). IMO, the shorter version should be sufficient if you want to save typing time.


Happy Programming :) 
Signing Off 

Ryan Sukale

Sunday, April 1, 2012

jdeveloper out of memory heap space error


Occasionally while working with jDeveloper you may get an OutOfMemory heap space error due to lack of heap space available for the jdeveloper ide itself. The following steps should help.

If you have installed jdeveloper on a windows machine you can
  • Go to C:\Program Files\jdeveloper\ide\bin\
    NOTE : The path marked in bold should be your jdeveloper installation directory
  • Edit the file ide.conf
  • Set the AddVMOption  property to be around -Xmx1024M
  • In case after making these changes, jdev doesn't start up, you probably need to decrease the  AddVMOption  to a lower value and restart jdeveloper again

Happy Programming :)
Signing Off

Ryan