Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, September 26, 2010

Javascript Functions for Dummies

A common confusion is when to use "function", "new function" and "new Function"

1. Plain "function" is simply code that does a particular task. It can be called directly or by an event (similar to module/procedure/subroutine in other languages). It typically returns a value.
function AreaOfCircle(r){
return Math.PI*r*r;
}
//Now call the function as:
alert(AreaOfCircle(3));

You can declare an anonymous functions as:
function(){
...
}

You can declare the function and execute it immediately. For example:
alert(
function(){
alert("executing function...");return "done!";
}() //execute function, and alert the returned value
);

Note:
function Foo(){ ... }
is shortcut for:
var Foo = function(){ ... }
//Creates an object with code which can be called as Foo();


Check this out:

var x=function f(){};
console.log(x?true:false)
console.log(x()?true:false)

The first one will return true, as "function" is like an object and returns "truthy". the second one OTOH executes this empty function and returns "undefined", which essentially is "falsy".

2. The "new" keyword basically returns an object based on the code specified inside the function.
var o = new function(){...} is shortcut for:
function Foo()
{
this.x = 1;
this.y = 2;
}
var o = new Foo;

This creates an object "o" with two properties: x and y. Basically this does the exact same thing as the two examples below:
//Object instantiation
var o = new Object();o.x=1;o.y=2;
//A more compact Object Literal Notation:
var o= {x:1,y:2};


3. Finally, there "Function constructor" which allows you to create a function by passing strings for function-parameters and function-code:
var a=new Function("x","y","alert(x+y)"); //last string is the code
a(3,4); //results in "7"

Note the capital "F" in the function constructor. Also note this constructor does not create a closure.

Object-oriented javascript tutorials can be found at: mckoss, javascriptkit, and sitepoint

More javascript essential study material: Douglas Crockford YUI videos on JS reintroduction. And if you are feeling confident, go take the javascript quiz on kourge.net - you'll be humbled pretty quickly!

Monday, July 26, 2010

JS tips - I

Level: Moderate

String to integer conversion (Caution with parseInt):

Remember to always include the base with parseInt, otherwise you can introduce hard to find bugs. If the string has a leading zero, it is evaluated with base 8 (Octal). Therefore "015" will return 13. The correct way is parseInt('015', 10);

A neat way is to achieve the same is to simply put a plus sign in front of the string variable. That forces a type conversion to decimal:
var s="015"
var i= +s + 2;
console.log(typeof i);
console.log(i);
//results in:
// number
// 17

Trim() for strings:

You can extend the String object to include trim, ltrim and rtrim with a little regex to strip off the surrounding white spaces.

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};


Now you can use trim any string variables, input field values, or even string literals. For example:

<input id="firstname" onchange="value=value.trim()" />

Sunday, July 25, 2010

Fun with Javascript Dates III

Level:Moderate

Javascript Date objects can be created with the following parameters:
new Date(year, month, date, hours, minutes, seconds, milliseconds)
If you only specify the first two parameters, all others are assumed to be zero.
This date instantiator has a very interesting feature. The parameters for month, date(i.e. monthday), hours etc do not have the standard upper and lower bound. They can be any integer. For example monthday can be negative or greater than 31.

var d = new Date(2010,0,1) // will yield 1st Jan 2010
var d = new Date(2010,0,-2) // 29 Dec 29 2009 (back 3 days)
var d = new Date(2010,0,-2, 100) //1st Jan 2010, 4am (minus 3 days plus 100 hours)

This was a very cool design decision, because now it becomes very easy to perform date addition.

1. Add/Subtract days and months etc to a date

var d = new Date(); //today's date
var d2=new Date(d.getFullYear()+3,d.getMonth()+4,d.getDate()+5)
//d2 is set to 3 years, 4 months and 5 days in the future

Better still, we can extend the Date Object’s behavior and add this functionality.

Date.prototype.addDays = function(days) {
return new Date(this.getFullYear(),this.getMonth(),this.getDate()+(+days))
}
//See my ParseInt blog if you think the (+days) is odd looking
//Usage:
//var now = new Date();
//var Yesterday = now.addDays(-1);
//alert(Yesterday);

I’ll leave it up to you to implement addMonths() and addYears(), Hours, Minutes, Seconds.

2. Day of the Year: (Julian Day)

Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

3. Week of Year

Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

4. Fiscal Year if your new year starts on October 1st of the previous year.
We can use the addDays() prototype function we just created!

Date.prototype.getFiscalYear = function() {
return this.addDays(92).getFullYear();
}

Datejs library on googlecode, has amazing functionality added on to the Date object. Many other major frameworks have similar libraries.

Friday, July 23, 2010

Fun with Javascript Dates - II

1. Javascript Date object has many differences from .Net DateTime type. Some of the prominent differences are:
  • Month is zero based integer (0 to 11) - this can be a source of many a bug.
  • Weekday (getDay) returns 0-6 for Sunday-Saturday

    To get descriptive weekday, you can extend the date object's functionality like so:

    Date.prototype.getDayShort=function(){
    return ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][this.getDay()];
    }
    //Test it:
    alert((new Date(2010,1,1)).getDayShort())

    This will popup "Mon". Some of you are looking up the calendar and thinking "shouldn't 1st Jan be a Friday". No Siree, the date is 1st Feb -- did you already forget my month's tip above? I will leave it up to you to implement a getLongDay() function.

    The cool trick above is declare a lookup array on the fly. It saves a line of code, and an additional variable, and can be useful for small, one-time-use lookups. You can use the same trick with JSON objects. For example:

    alert({black:"#000000", blue:"0000ff", red:"#ff0000"}["blue"]);

    2. One biggie is the Y2K bug. Javascript and .Net have methods to create date objects from numbers. Javascript's Date(yy,mm,dd) constructor will treat all 2 digit year to be 19th century, while .Net has DateTime.Parse method which assumes years "0" to "29) to be 20th century. To mimic .Net's behavior check for date under 30, and add 2000, as shown below:

    for(var i=0;i<102;i++)
    console.log(new Date(i<30?i+2000:i,1,1));
  • Thursday, July 22, 2010

    Fun with Javascript Dates

    I'm going to start a series on Javascript. I'm gonna post some cool and useful solutions that are not currently available on the internet (as far as I know).

    Let's start small. Here is a function that will truncate the Time component from a date object. This can be useful when doing date comparisons, inadvertent bugs are introduced because of the time component.


    <script type="text/javascript">
    function removeTimeFromDate(inDate){ //i.e. set date to Midnight
    return new Date(Date.parse(inDate.toDateString()));
    }
    //Test it out:
    var now = new Date();
    alert(now);
    alert(removeTimeFromDate(now));
    //Results:
    //Thu Jul 22 2010 23:37:50 GMT-0400 (Eastern Daylight Time)
    //Thu Jul 22 2010 00:00:00 GMT-0400 (Eastern Daylight Time)
    </script>


    Pretty simple, once you see it, yet most people write a ton of code to achieve this functionality. Another way is to return a new Date(inDate.getFullYear(), inDate.getMonth(), inDate.getDate())

    You can add this functionality to the Date object itself, thereby extending it. I will show you how to do this in the next post.

    Tuesday, April 27, 2010

    Clickjacking and (i)frame-based attacks, and how to fight them.

    The web is so choke full of malicious sites, that I have become extremely paranoid. If I suspect even a hint of malicious code on a site I am visiting (such as unwanted popups), I rush to the Alt-F4 key close it and consciously avoid any mouseovers/mouseclicks. If that does not work, I will kill the browser session from the task manager. Firefox has an annoying habit of trying to reload the same site after a crash-recovery. You can change that behavior from going into the about:config and changing the browser.sessionstore.resume_from_crash setting to false.

    Clickjacking is one way the baddies can hijack your clicks or keystrokes by craftily positioning their own content obscure/hide legitimate content you are browsing, and deceive the user into clicking on hidden element. So when you click or type, it gets passed on to the hidden layer beneath which could be the hijacker's form to capture personal information.

    The root of this attack is the bad guy placing your web page in a frame or iframe. He can now manipulate the layers and what is visible to the user since he controls the top level or outer frame.

    The classic way to prevent your content from being framed is to put a "frame-buster" javascript at the top of your page:
    <script>if (top!=self) top.location.href=self.location.href</script>

    Unfortunately, the bad guys can defeat this method in a number of ways:

    1. The attacker can interrogate the onbeforeunload event and redirect the top.location and have their own server respond with a 204. The Wikipedia framekiller article describes this technique so I won't go into the details.
    2. Override the location.href setter (__definesetter__) in webkit family of browsers. Therefore even if your frame busting script runs, the location.href will not do the job.
    3. IE has SECURITY="RESTRICTED" option which can allow the attacker to turn off scripting in the inner frame (where they will put your content, and obviously the frame busting script will not run)

    OK, so how do we combat these "anti-busting" techniques? The best way I have worked out is implementing any one or both of these methods:

    (a) This will thwart the first anti-busting attack, but will fail with 2 and 3.

    <script>if(top!=self){var s=self.location;setInterval(function(){top.location.replace(s);s=null},1)}</script>

    (b). Style the <body> to hide content. Then later unhide with scripting after verifying you are not framed. That way even if the attacker thwarts your frame busting efforts, your content is hidden (as well as the clickjacking content) until you successfully bust out of the frame.

    <body style="visibility:hidden"><script>if(top==self)document.body.style.visibility='visible'</script>

    This method(b) doesn't really stop the attack, But hides the content of the page when framed, so a blank page is displayed, therefore the intent of the attacker is defeated! The downside here is that it will show blank page when scripting is turned off, or security(zone) setting is high. This should not be too much of a concern, as in today's world Javascript is so ubiquitous, that turning off scripting will virtually render virtually every site crippled.

    UPDATE(June 9, 2010): Another solution: All major browsers (latest releases) except FF now support the "X-FRAME-OPTIONS" meta tag. Check out Eric law's post. However, since Firefox does not support it as well as all older browsers (IE 6,7 etc),this is not a very effective solution - instead I would use the above (a) and (b) anti-busting countermeasures.

    Friday, August 22, 2008

    Bookmarklets

    Bookmarklets is a little javascript code you can put directly into your firefox/IE "bookmarks(favorites)". So when you select the bookmark, it will execute the code and enhance your functionality of the browser. Bookmarklets have been around since IE4, and I find them quite handy. There are bookmarklets to autofill forms, to cut-and-paste, to select text and bring up a search engine and several other uses. I recently created a bookmarklet to rid myself of the annoyance when some sites use redirects, which causes either the form to appear as illustrated, or the firewall to block the site entirely.


    The link appears as:
    Notice that the actual link I want to read is a URL parameter and is percent encoded. Now I have to fill out this form every time I need to read an article on LSJ. Clicking on the Bookmarklet helps me grab the actual link which is:

    For IE the easiest to create this bookmarklet is by adding a dummy bookmark (like this web page), then edit its properties:
    Click on "Favorites", then RIGHT-CLICK on the link you added and select "properties" from the context menu.
    In the "properties" window, click on "General" Tab. Now change the name of the bookmark to "UNESCAPE". Next, click on the "Web Document" tab and paste the following code for URL:
    javascript:void(pos=location.href.search("=http%253A"));
    if(pos=-1)void(pos=location.href.search("=http%"));
    if(pos>-1)location.href=
    unescape(unescape(location.href.slice(pos+1)))
    Note the entire code is the url address, so it should be in a single line and without any spaces in between it. Now click on "Apply" and you will see a message:
    "The protocol javascript does not have a registered program".
    Click "Yes" to keep it anyway. Click OK, and then "Yes" again. Congratulations, you just made your first bookmarklet.

    Tuesday, June 24, 2008

    Part 1. Power of a Regular Expressions

    Rather than just posting the slides, I decided to do a series of blog posts on the subject - consider it as a intro or tutorial to Regular Expressions.

    What are Regular Expressions?

    Regular Expressions (or RegEx for short) is a technique to shorten coding by using bunch of letters and symbols (metacharacters). Most modern languages support regular expressions. You can use it in code. But where they are really useful is data cleanup, extraction, converting legacy data, grabbing data from the internet, etc. Regular Expressions can be considered as the SQL for freeform text.

    RegExs are avoided by most people (even experienced programmers shy away from it), because they either don't understand it, haven't taken the time to learn it -- or they think that it is sediment left over from the Unix era.

    At the end of this tutorial you will see that, regular expressions can actually be easier and quicker to code. Once you understand how it works, and some of the tools and techniques, you will see how dramatically it can shorten code, and save you a time with coding and debugging. Also, maintenance can actually be easier!

    Here is a terrific example. Today, I was browsing through the prep book for MCTS Exam 70-528, and came across this example for asp.net custom validator control to validate passwords. The password rules are:

    • 6-14 characters,
    • at least one lowercase letter,
    • at least one uppercase letter
    • at least one number

    Here is the conventional method. (Code directly copied from the book, pg 469 with misspelled "argument" and all)

    <script language="javascript" type="text/javascript">
    function ValidatePassword(source, arguements)
    {
    var data = arguements.Value.split('');
    //start by setting false
    arguements.IsValid=false;
    //check length
    if(data.length < 6 || data.length > 14) return;
    //check for uppercase
    var uc = false;
    for(var c in data)
    {
    if(data[c] >= 'A' && data[c] <= 'Z')
    {
    uc=true; break;
    }
    }
    if(!uc) return;
    //check for lowercase
    var lc = false;
    for(var c in data)
    {
    if(data[c] >= 'a' && data[c] <= 'z')
    {
    lc=true; break;
    }
    }
    if(!lc) return;
    //check for numeric
    var num = false;
    for(var c in data)
    {
    if(data[c] >= '0' && data[c] <= '9')
    {
    num=true; break;
    }
    }
    if(!num) return;
    //must be valid
    arguements.IsValid=true;
    }
    </script>

    Now, with the use of regular expressions, we can shorten this into just ONE line of code:
    <script language="javascript" type="text/javascript">
    function ValidatePassword(src, args)
    {
    args.IsValid =
    args.Value.length>=6 && args.Value.length<=14
    && /[a-z]/.test(args.Value) //find a lowercase
    && /[A-Z]/.test(args.Value) //find a uppercase
    && /\d/.test(args.Value) //find a digit
    }
    </script>

    You've got to love the elegance and compactness of this code. I believe it is actually easier to understand and debug - no messy loops and "if" constructs. And it reads exactly like the password rules specification above. Such is the amazing power of regular expressions. Note: "\d" is the character class for identifying a single digit. We could have just as well said "[0-9]".

    In my next post we will look at a few more easy examples and examine the metacharacters.