Get and Set operators in Javascript

I am C# developer, hence I use C# properties a lot. However I just recently discovered that Javascript has properties as well. Get and Set operators supported by Firefox 2.0+, Safari 3.0+, Chrome, Opera 9.5+. However IE still doesn't support properties. May be Microsoft would introduce support in IE10, but so far no luck. Here is a little example of Get and Set declaration:

var obj = {
 
   get CustomProperty() {
     return 0;
   },
 
   set CustomProperty(s) {
     alert ("It is readonly.");
   }
};

 

Properties can be useful and scary at the same time. A simple variable assignment is not predictable anymore. For example with a little bit of work you can convert your AJAX calls to something like this:

ajax.url = "script.php";
 
alert(ajax.result);

 

Posted on Saturday, February 04, 2012 by | Add Comment

YSlow and ASP.NET: 100 points "A" grade year 2012

Almost three years ago I wrote an original YSlow and ASP.NET: 100 points "A" grade is possible article. Since then I changed couple hosting providers, made numerous updates and converted my blog project to .NET 4.0. Today I decided to revise my blog to see if it still has 100 yslow points with final "A" grade.

First surprise, as of January 29, 2012, YSlow addon doesn't work in FireFox 9. However YSlow is now available for Google Chrome, Opera, Safari. It has bookmarket version and even command line version. I installed Google Chrome Yslow extension and began investigation. Right out of the box most of sections still had A grade. About a week ago I switched from Google App Engine "CDN" to true CDN Amazon CloudFront. Some files were not in CDN, so I had to take care of those. In general I highly recommend Amazon CloudFront. It is easy to setup and cost just a few bucks a month based on your traffic usage. Amazon CloudFront mimics your local file settings, so you need to make sure that you have compression, expire header and Etags taken care of. I use IIS7 compression instead of a compression module recommended by me in my previous article. Out of the box IIS7 compression doesn't work with AWS CloudFront, so you need to modify C:\Windows\System32\inetsrv\config\applicationHost.config file on your server to include following:

<serverRuntime enabled="true" frequentHitThreshold="1" frequentHitTimePeriod="00:00:20"/>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" noCompressionForHttp10="False" noCompressionForProxies="False">
  <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
  <dynamicTypes>
    <add mimeType="text/*" enabled="true" />
    <add mimeType="message/*" enabled="true" />
    <add mimeType="application/x-javascript" enabled="true" />
    <add mimeType="*/*" enabled="false" />
  </dynamicTypes>
  <staticTypes>
    <add mimeType="text/*" enabled="true" />
    <add mimeType="message/*" enabled="true" />
    <add mimeType="application/javascript" enabled="true" />
    <add mimeType="*/*" enabled="false" />
  </staticTypes>
</httpCompression>

 

Also I modified my cache module to have ETags clean up:

public void Init(HttpApplication context)
{   
    ...                 
    context.PostReleaseRequestState += new EventHandler(application_PostReleaseRequestState);
}
 
void application_PostReleaseRequestState(object sender, EventArgs e)
{
    HttpContext.Current.Response.Headers.Remove("Server");
    HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
    HttpContext.Current.Response.Headers.Remove("ETag");
}

 

YSlow added new section "Use Cookie-free Domains". My blog completely failed this one, since google analytics left cookies in top level karpach.com domain. I modified google analytics init script to have: _gaq.push(['_setDomainName', 'www.karpach.com']), so google cookies set for www.karpach.com instead of top level karpach.com. Then subdomain cdn.karpach.com, which points to Amazon CloudFront, became cookieless. Finally I am back to 100 YSlow points. Run Yslow on no externals version of karpach.com to see it yourself.

Posted on Sunday, January 29, 2012 by | Add Comment

How to check if a javascript variable is undefined?

How to check if a javascript variable is undefined? This is actually a tricky question. There are three cases:

  1. A variable is declared using var keyword, but were never assigned any value.
  2. A variable is declared as function parameter, but when function were invoked parameter was not supplied.
  3. A variable is never declared or assigned a value and you are trying to access it.

First two cases lead to undefined value of variable. Here is an example of first case:

var v; // Value not defined
if (v) {
    console.log("v=" + v);
}
else {
    console.log("v has undefined value");
}
v = "some value";
if (v) {
    console.log("v = " + v);
}


Output:
v has undefined value
v = some value

The second case is similar and you can use if statement as in above code or:

function Add(p1, p2) {
    p1 = p1 || 0; // set value to 0 if value is undefined
    p2 = p2 || 0; // set value to 0 if value is undefined
    return p1 + p2; // would always work
}
 
console.log(Add(1, 2));
console.log(Add(1));
console.log(Add());


Output:
3
1
0

The third case when a variable is never declared. If you try to use such variable you get exception. If statement or default value assignment won't help.

if(typeof neverDeclared == "undefined") {
    console.log("There is something really wrong!");
}


You would ask, what kind of sick people try to use a variable that was never declared or assigned a value? However I bet this is one of the most frequent javascript exceptions. Yes, simple variables are usually declared, but exception usually happens when you try to pass complex object with undeclared property. Javascript objects can be easily extended with additional properties and this comes at price of frequent undefined variable exceptions. Let me give you an example:

var obj = { FirstName: "Viktar", LastName: "Karpach" };
console.log(obj.FirstName);
console.log(obj.LastName);
console.log(obj.City); // Will give exception
 
var obj = { FirstName: "Viktar", LastName: "Karpach" };
obj.City = "Chicago";
console.log(obj.City); // Works!
 
if (typeof obj.State == "undefined") {
    console.log("State is undefined.");
}

Undefined variable exception very often happens when you try to consume objects received from third party API or from AJAX requests, always be careful what you consume from partially unreliable resource.

Posted on Thursday, January 12, 2012 by | Add Comment

Categories

Recent Tweets

Valid HTML5