Friday, June 15, 2012

Back to quality education with Udacity and KhanAcademy

A slight deviation from my usual posts and this time I am reflecting on the state of education, when I was a school student and the new digital era being revolutionized by the likes of Udacity, KhanAcademy and Coursera.

Every child goes through this phase, and its the decision that he makes, at that point, that may change the future course of his life.

Every child has a dream and every dream has some limitations, which are constrained by our imaginations and most of which are self created.  As a child I always wanted to study and understand mathematics and its applications, but was never able to.

I never understood what my teacher was teaching, as it was a pure mechanical process.  Put a formula, here and a formula there and you get the solution.  They never made us ponder why things work the way it does.

For me mathematics was one of most dreaded subjects and also one which I loved most, for being one of the subject on my top hate list.  Pretty contradictions, and that's what thoughts are.

I always wanted to master this beautiful subject, but never found a teacher. There were many teachers who used to teach, but none to educate. The most shattering thing for me with my math experience was when I was in my 5th grade, and I scored  of  1 point out of  100 in my preliminary exams, because I never ever studied what was taught, because I never understood anything, and things never interested me.

And that 1 point, I guess could be because my handwriting was good at that point in time. That's what I thought (though that was not the case, because at that time my handwriting was terrible).  So, you could now imagine the state of mind of a 5th grader and his hope with his further math education.  (Hope my kid won't be reading this blog after couple of years).

Teachers are not bad, but their teaching experience faired very badly at that time.  It's not there fault. There weren't simply any  finishing school where teachers could polish their teaching skills based on different students needs. There are some good teachers who go out of the way to explain things, but my math teacher when I was in  5th grade was not one of them.  Though, it may not be teacher's fault  and they were doing a good job, as other students were passing the exams and also the students to teachers ratio was something like 1/65.  May be I didn't had a mathematical bent of mind.

Somehow I passed these school exams, and luckily while I was in my 7th grade we moved to another city Kalyan (remote location in Mumbai).

Parents thought with a change in place, my attitude towards education might change.  And to some extent they were right, though I was not very good at math, until when I was in 10th grade.

It was during my study in 10th grade, that I realized that math is a beautiful subject again and special thanks goes to my tuition teacher, Joy Sir (of St. Mary's classes, Kalyan), for beautifully explaining the subjects.  And I did pretty well with math, from thereon.

The only problem and mistake I did was in my 11th and 12th high college , I skipped math and took up a useless secretarial course (as I thought during that time secretarial course for commerce student was more useful that math and all my friends opted for this subject) and that was one of my biggest educational decision mistake that I committed.  From thereon, I lost interest in math, and somehow passed my mandatory first year math college course and was fully involved more than hundred percent devoting my time to computer applications.  But somehow, this lack of mathematical education, always haunted and interested me.

And then came KhanAcademy.org.  After about 15 years from graduating from college, I again fall in love with Math, but this time with a purpose.  I don't want my kids, to go through the same process of lack of understanding and lack of awareness on the purpose of education and the role it can play to shape their future.

I want them to appreciate the subject not only math, but science, economics, history, law and others.  I rather want them to experience the subject rather than learning by rote.  And I am very thankful to these wonderful online academies who are doing a great job.

Now coming back to Udacity, they are special to me.  Two new courses on statistics and discrete math is being shortly offered in the coming weeks.

http://www.udacity.com/overview/Course/st101/CourseRev/1
http://www.udacity.com/overview/Course/cs221/CourseRev/1

What better opportunity will I get to test and brush up my math skill (which is very negligible) from the finest professors in the world.

I have committed myself to complete both the courses in the next 7 weeks after it starts no matter what it takes me to complete and to get permanently rid of this math phobia.  At least I will try.

I have tried many Udacity courses in the past couple of months, but never completed any.  My purpose then was to learn things which I wanted and selectively watch courses that I like.  And I am glad I did that.  Almost all of Udacity's courses are simply great and 100 percent educational.

You want  to learn programming, take CS101 and build a search engine.  You are an intermediate programmer take CS253- Web Application Engineering and build a blog engine and wiki in the process, understand caching and other useful aspects of computer science.  You want some advanced stuff, take CS387 - Applied Cryptography.

I guarantee you will love these courses.  Even though the language of programming used is Python, but that is of least concerned as what matters most is the concept and ideas that you learn during this course.

Also, its always better to know yet another language apart from the language you program for your bread and butter.

Also, there are many more courses that are coming up and I am sure you will find your choice of course.

I will highly encourage other people who are on the same state of mind like me to try these courses out.  Not only for yourself but for others around you, who may require genuine quality guidance from someone who has gone through this phase of life.

Hopefully education will not be the same again. Learnings will be fun and enjoyable.  And that may be the precise reason  why I like teaching and taking up some professional training activity from time to time, because I want people to understand the crux of the matter.

The key thing is to understand the foundation of any subject , polish your basic skills, learn to communicate effectively , write better, and you will grow into a exceptional professional in any field which you may choose to study.

Another thing  that I will do is to blog all my learnings from this courses, as micro books on my upcoming website http://www.ownabook.org/

I hope my mistakes could be a learning points for the kids around me.

Happy learning!

P.S:  This post in no way is trying to undermine the importance of teacher nor is addressed to any specific person.  These are just my thoughts and my perception based on what I have experienced and thought of sharing.  No hard feelings for any one.  I love and respect my teachers and it was because of the support of some great teachers who had given me opportunity to try and work out things going out of their way that enabled me to get confident in my area of study.

Monday, June 11, 2012

Quickly build a jQuery watermark plugin with HTML5 and modenizr support

In this edition of blog post, we will quickly build a jQuery watermark pluigin for input controls.  This is an adapted post from  http://uniquemethod.com/html5-placeholder-text-jquery-fallback-with-modernizr.  I have quickly refactored the code as a jQuery plugin.  The author in the above blog post has done a great job of summarizing the concept.

A watermark or placeholder text is an indicator by input controls as to what data could be enter in the field.  It's kind of a hint to user entering the data.

HTML5 has native support for watermark in the form of "placeholder" attribute.  Any text that you put in the placeholder attribute will show as watermark in modern browsers.

For browsers that doesn't yet support HTML5, jQuery comes to the rescue.  Also, we are using Modernizr for feature detection.

Modernizr is an excellent feature detection library, with which we can detect for support of modern standard by browsers.


You can see a working version here


You can use this plugin, in the following manner.

$(".placeholder").watermark();

The above jQuery code finds all elements with a class of "placeholder" and applies the watermark() function to it.

The sample input element is shown below.

 <label>Namelabel>
 <input class="placeholder" placeholder="Enter your full name." type="text" />

Do note the above input element has a class of  "placeholder" and also a placeholder attribute which is set to "Enter you full name".  This placeholder text will be shown as watermark in the input element.  Also, HTML5 browser directly understands and render this placeholder attribute appropriately.

Rather than bloating this post, I have added appropriate comment in the jsfiddle.  In case anyone needs further clarifications, please drop a comment.

Enjoy~!.

Friday, June 08, 2012

A new startup initiative: Ownabook.org - A community site

Lately there has been a traction from my usual work, and was thinking about starting something very different and helpful to the community.  Various ideas where jumping in my mind, but as usual ideas are ideas and of no use unless it sees the light of the day.   Did tried attempt at various small open source projects, in PHP, rails, MVC, jQuery, but never completed any of them fully.  Something always stopped me at the last moment.

But the good thing is there was tremendous learning in all these activities.  Learned a ton.  But one thing always hounded my mind, my incomplete OSS projects.

So, this time, didn't thought much,  just jumped straight in, took the code editor and begin designing my ideas as code.  One of the outcome is http://ownabook.org, a community initiative were some lucky bookwormers may get cool books, absolutely free.  That's not all, once the site is up, there will be unique features and opportunities to grab.

The idea behind this is to keep the reading habits alive in people, and doing my bit in the way.  It's not about winning a free, book, its about what you do with it.  It's about sharing.  As time goes by, there will be intelligent quizzes, tips, puzzles, which keeps your brain tickle.  Keep it alive, and in the process win a book.  Those things are still in my head, but will soon come out in the form of code.

I will definitely release this as OSS, once I get all basic things done correctly, as I don't want to share bad code.   Believe me there will be some real gems in the code, in terms of design, coding pattern and much more, which definitely I have learned from the ever helping communities in the internet.

Also, planning to setup up a place in the site to offer books to needy students, children, in remote places, but don't have any idea about how go about doing that.

If anyone reads this post, and knows something in this direction, then do leave a comment.

Enough ranting.... regular post will resume soon.  Plan to finish Javascript series and then start with MVC 4.

Enjoy reading!

Monday, April 09, 2012

Building a jQuery PPT like presentation - Part 1

This is more a video post and it covers how to build a simple PPT like presentation using jQuery. This is very elementary at this stage and we will incrementally add features to this.

The first version is a very rough one and cover elementary ideas and proof of concept.

Hope you like this. Do please note the video doesn't have any voice as I am still improving my recording skills (and also having a bad throat since couple of days). In any case, I do think action speaks louder that words.. (though this is just an excuse).

The URL for the source code is at http://jsbin.com/ovaxop/edit#source

Wednesday, March 28, 2012

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern.


Problems with Function Spaghetti Code

  • Variables/ functions are added to the global scope

  • The code is not modular

  • There's potential for duplicate function names

  • Difficult to maintain

  • No namespace sense.

Let's take for example the following set of functions and check whats the issue with them.
// file1.js

function saveState(obj) {
    // write code here to saveState of some object
    alert('file1 saveState');
}

// file2.js (remote team or some third party scripts)
function saveState(obj, obj2) {
     // further code...
    alert('file2 saveState");
}

Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script.
For e.g.

If this script is references as
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

Then the function defined in file2.js will be overriding the one defined in file1.js. If you change the order the order of overriding changes. So, you can see this is a cause of concern if you have a n application which depends of javascripts both internal and from third party. One way to solve this problem is with closures.

Closure

...an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. ~ Douglas Crockford
In JavaScript yo can nest function and the nested function has access to all the variables and functions defined by its parent. This seems very simple and straightforward, but this is a very complex concept under the hood. Its like a function still holds the variables around its environment even after the function seems out of scope. Let us quickly go through an example.

// The getDate() function returns a nested function which refers the 'date' variable defined 
// by outer function getDate()
function getDate() {
   var date = new Date();    // This variable stays around even after function returns

   // nested function
   return function () {
      return date.getMilliseconds();
   }
}

Now if you call this function as shown below, you will see that the inner function holds on 
the the date variable.

// Once getDate() is executed the variable date should be out of scope and it is, but since 
// the inner function
// referenes date, this value is available to the inner function.
var dt = getDate();

alert(dt());
alert(dt());


The output of the above alert will be the same value of date.getMilliseconds();

Let's take another look at closure and use a module kind of pattern..

var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    }
}

var dt = new MyDate();

alert(dt.getMilliSeconds());  // This will throw error as getMilliSeconds is not accessible.

Make the following changes
var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    };
    return {
        getMs : getMilliSeconds
    }
}

What you are doing above is encapsulating all your logic in a namespace, in this case MyDate, and only
returning public methods to the outside world as an object literal.

You can use this as shown below..

var dt = new MyDate();
alert(dt.getMs());  // This should work.

The above construct is very similar to "The Revealing Module Pattern", which we will cover in
subsequent posts.

Now let's solve the original problem of saveState.

function App() {
    var save = function (o) {
        // write code to save state here..
        // you have acces to 'o' here...
        alert(o);
    };
    
    return {
        saveState: save
    };
}

var app = new App();

app.saveState({ name: "rajesh"});

Your application can use this as follows, without worrying about other saveStates floating around...

var app = new App();
app.saveState({ name: "rajesh"});

To conclude, we had look at why function spaghetti coding is bad and how to avoid this by using closure and module pattern.

In subsequent post we will look at how to create namespace and dig into deeper of the module pattern.

Hopefully you will find this useful.

Friday, March 23, 2012

JavaScript - The this keyword

"this" is one of the most misunderstood construct in JavaScript.  To understand this first lets go through how to create a construction function in JavaScript.  A constructor function is a function which is used to create instances of objects in JavaScript.

You define a constructor function using the same notation that you use to define a normal JavaScript function.  The convention to follow is to capitalize the first letter of the function name.

This requirement is not enforced by the JavaScript language but it is a generally accepted practice and there are many benefits which we will shortly discuss.

Let's define a constructor function to hold our menu information.

function Menu() {

}

So, in the above snippet you have a constructor function named Menu defined. At present this function doesn't do anything good.

Let's see how to invoke this function

var menu = new Menu();

Let's add some public properties to this function.
function Menu() {
    this.menuName = "File";
}

Let's create an instance and see how we can use this.

var menu = new Menu();
alert(menu.menuName);

If you run the above code, you should get an alert with a value "File".  This is not so interesting.

Let's pass, in the name information to the function.

function Menu (name) {
    this.menuName = name;
}

Now you can call this function as shown below.

var menu = new Menu("file");
alert (menu.menuName);  // You will still get an alert with a value 'file'

Isn't this interesting now.   Now the point to remember is that nothing in JavaScript prevents you from invoking this function directly.

For e.g.

var menu = Menu("file");

What do you think the output of the above will be if you do an
alert(menu.menuName);

You will get an error similar to "Uncaught TypeError: Cannot read property 'menuName' of undefined".

You can see this in action here




Why?  Any idea?  Also, there is a side effect to this.   You accidentally created a global variable "menuName".

You don't believe me.  Try doing an

alert(menuName);   // OR
alert(window.menuName);

Ok. Lets get a bit deeper into how this thing work.  By default a constructor functions always returns an instance of the function object  on which the "new" is called upon.

If you directly invoke a constructor function without creating a new instance, then that function is executed rather than an object being constructed. So, the return value of that function invocation will be undefined as you are not explicitly returning any value from the function.

So, all assignment to "this". goes to the global window object and you accidentally create globals.
Always name your constructor function starting with an uppercase.
The primary reason why this is an issue is because JavaScript don't force you to construct object of constructor function as for JavaScript execution engine there is no difference between the two.

This is where naming convention plays an important role. Name all your constructor function starting with an uppercase letter. This way it will be very easy for you to detect if there is any unintentional misuse of the constructor function. Besides there are certain tools like "jslint" which warns you if you directly invoke a constructor function which has a name starting with uppercase.

Ok, so how to avoid this problem.  What we want is whenever the user uses the Menu function either as direct function call or as a constructor function we need the function to return a menu object to the user.

A simple solution is to return an anonymous object from the constructor function with required properties attached to it.

function Menu(name) {
    return {
        menuName : name
    };
}

We can use this function either by direct call, or through constructor invocation, we will always get the correct object, without creating globals.

Why this works is because constructor function by default returns the instance of the object on which it is invoked.  The other interesting thing is we can return any thing from this constructor function.  We will use this feature to return correct object back to the caller.

var menu = Menu("file");  / called directly
alert(menu.menuName);  // alerts 'file'

var menu1 = new Menu("Help");  // call with new
alert(menu1.menuName); // alerts 'Help'

// alert(menuName);  // See no, globals

this Gets tricky


Take this example below. We have a simple function which returns stock quote. Pretty simple example in this case.

function StockQuote() {
    this.quote= "12,13,343,343";
    this.getQuote= function() {
         //this is expected to be a reference to the current instance
         return this.quote; 
    }
}

Now lets' say we need to get the quote in the next 3 seconds..

var quote = new StockQuote();
// call the getQuote function in 3 seconds.
setTimeout(quote.getQuote, 3000);

Many beginner JS dev may think this may work, but it won't. It'll give an error saying that quote is undefined. This is because there is no binding of functions to instances in JavaScript. Whenever the instance isn't explicitly stated, then "this" becomes windows object (at least in the browser, as js runs in other environment as well). Writing quote.getQuote() indicates that you want "this" to belong to quote, so it will work correctly. However, the setTimeout function only has a reference to that function. When it calls it, after 3 seconds, it is not aware of "quote", so JavaScript sets this to window.

"Fixing" this

There are several ways of forcing this to be what you intend to be and many of them uses some unique features of JavaScript.

The two important ones are
  • apply

  • call

apply is a member of every function. It says "invoke this function on this object (change the context of the object).

An example is shown below.

// These two are same..
quote.getQuote();
// "quote" is the this context you are passing
quote.getQuote.apply(quote);

// you can also do this.
var myQuote = new Quote();
myQuote.getQuote.apply(myQuote);

// The above line does the same thing as
myQuote.getQuote();

Before solving the setTimeout problem lets briefly have a discussion on Lexical Scroping in JavaScript.

Lexical scoping allows you to access local variables in a parent function by the child functions. i.e. if a function is defined withing another function, it can access its own local variables as well as those of the function it was defined within.

Now let's solve the setTimeout problem with Lexical scoping.

var myQuote = new Quote();
setTimeout( function() {
    myQuote.getQuote();
}, 3000);

We created a new anonymous function which we are passing to the setTimeout. Our new function can access myQuote, so it just applies it to the getQuote function.

Solving setTimeout problem using "apply".

var myQuote = new Quote();
setTimeout(myQuote.getQuote.apply(myQuote), 3000);

The difference between call and apply is subtle and only varies in the way parameters are passed. apply requires the second parameter to be array which represents the parameters to the function , and call accepts an argument list...

Let's quickly look at the syntax of both the functions.
fun.call(object, arg1, arg2, ....);

fun.apply(object, [argsArray]);

Hope you have enjoyed this post.

In subsequent post we will look at how to avoid this edge cases by using various well known pattern and practices.

JavaScript Scope

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers.

Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily)

Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service.

Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code.
public void Main () {
int a = 5;
if (true) {
int b = 10;
}
// This will throw compile time error as b is not defined
// and not within the scope of function Main();
Console.WriteLine(b);
}

If you write the same code in JavaScript, then the value of 'b' will be available outside the 'if' block. The reason for this is JavaScript does not have block level scope. Scopes works at the function level and because of a feature called 'hoisting' all variable declaration in JavaScript is moved to the top of the function.

You can read more about hoisting here http://rajeshpillai.tekacademy.com/hoisting/
function scopeDemo() {
var a = 5;
if (true) {
var b = 10;
}
// This will work even though 'b' is defined inside if block because of 'hoisting'
alert(b);
}

scopeDemo(); // Invoke the function

Remember, Scope in JavaScript is at function level and not block level.

So, contrary to popular guidelines of most programming lanaguage to declare variables as late as possible, in JavaScript it is recommended to declare all your variables as early as possible.


Happy Scoping !!!


You can try out the demo here

Thursday, March 22, 2012

Hoisting

Hoisting is one of the feature in JavaScript that puzzles many beginners and intermediate developers.  Hoisting is a feature wherein all the variables are moved to the outermost scope, which is function, in JavaScript.  This may sometimes result in seemingly strange behavior.

Before and after hoisting





The output of the above program is an alert with a value of 10.  Traditional logic would have lead us to believe that the value of alert should be undefined.  But because of hoisting the variable is moved to the top of function declaration.  Its important to realize that only the variable declaration is moved and not the initialization.
Recommendation: Always declare your variables at the top of the function scope.

Similar to variable hoisting we also have function hoisting.  Function hoisting has different behaviors based on the fact if the function is an expression or a declaration.

A function is an expression if it is assigned to a variable.  The assignment may also hold an anonymous or named function.   A function declaration is fully hoisted whereas a function expression has the hoisting behaviour of the variables as seen above.

Checkout the jsfiddle demo for a running application.


Watch out for next post where we will be demystifying "scope" in JavaScript.

JavaScript for Web and Library Developers

This is my first blog post on my home domain and in this series of posts I will explore various facets of JavaScript language that will help us become better programmers.  The idea is tear apart the language and understand how to use the features and build libraries like jquery, knockoutjs, backbonejs.

The idea is not to replicate this libraries, but understand the inner workings using better JavaScript coding practices, design principles and thereby make the web a better place to visit..

We will be covering the following topics, though not in order and there may be addition to this list.

  • Foundations

  • Patterns

  • Closure

  • this keyword

  • Hoisting

  • Anonymous function

  • Currying

  • Server side JavaScript

  • Canvas

  • etc.


Hope you will enjoy this journey with me!