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

AutoHotkey DVDFab script for volume label conversion

From time to time I use free DVDFab HD Decrypter to rip rented movies, so I can watch them later using my Popcorn Hour A210 media streamer. DVDFab is kind enough to pull volume label from DVD disk. However this label has all uppercase letters and words are concatenated by underscores. For example:

THE_LONG_GOODBYE

DVDFab vs AutoHotkey

 

I rename those labels to something like this: The Long Goodbye (1973), where year I lookup on IMDB web site. I don't like tedious repetitive tasks, so one day I decided to write a script for AutoHotkey to automate this process.

It is easy to replace underscores and correct letter case, but year should be retrieved from some kind of database. Google pointed me in a direction of IMDB API.

It might be a little bit challenging to do IMDB API access using just AutoHotkey script engine. Luckily AutoHotkey scripts can load dll libraries and with magic of COM.ahk and CLR.ahk you can load even .NET libraries. However those magic scripts can't properly execute .NET 3.5/4.0 libraries, so I had to use .NET 2.0. As you probably know .NET 2.0 doesn't have native support for JSON deserialization, so I had to use Newtonsoft.Json for this purpose. I also could use XML output from IMDB API, but I prefer to use JSON, since response is smaller in a size. Here is my code for .NET part of it:

public class Server
{
    public string GetMovieTitleWithYear(string volumeLablel)
    {
        var request = WebRequest.Create(new Uri(string.Format("http://www.imdbapi.com/?t={0}", 
            volumeLablel.Replace('_', '+'))));
        request.Method = "GET";
        try
        {
 
            var response = request.GetResponse();                               
            var responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                var reader = new StreamReader(responseStream);
                var responseString = reader.ReadToEnd();
                var movie = JsonConvert.DeserializeObject<Movie>(responseString);
                if (movie != null && !string.IsNullOrEmpty(movie.Title))
                {
                    return string.Format("{0} ({1})", movie.Title, movie.Year);
                }
 
            }
        }
        catch
        { 
        }            
        return UppercaseWords(volumeLablel.Replace('_', ' ').ToLower());
    }               
 
    static string UppercaseWords(string value)
    {
        char[] array = value.ToCharArray();
        // Handle the first letter in the string.
        if (array.Length >= 1)
        {
            if (char.IsLower(array[0]))
            {
                array[0] = char.ToUpper(array[0]);
            }
        }
        // Scan through the letters, checking for spaces.
        // ... Uppercase the lowercase letters following spaces.
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i - 1] == ' ')
            {
                if (char.IsLower(array[i]))
                {
                    array[i] = char.ToUpper(array[i]);
                }
            }
        }
        return new string(array);
    }
}

 

Then using JSON 2 C# Service you get following:

public class Movie
{ 
    public string Title { get; set; }     
    public int Year { get; set; }
    public string Rated { get; set; }
    public string Released { get; set; }
    public string Genre { get; set; }
    public string Director { get; set; }
    public string Writer { get; set; }
    public string Actors { get; set; }
    public string Plot { get; set; }
    public string Poster { get; set; }
    public string Runtime { get; set; }
    public float Rating { get; set; }
    public int Votes { get; set; }
    public string ID { get; set; }
    public string Response { get; set; }        
}

 

Library is ready. Lets plug it into AutoHotkey:

#include c:\Program Files (x86)\Autohotkey\Extras\Scripts\CLR.ahk
#include c:\Program Files (x86)\Autohotkey\Extras\Scripts\COM.ahk

RemoveToolTip:
SetTimer, RemoveToolTip, Off
ToolTip
return

#IfWinActive ahk_class QWidget
~Lbutton::
MouseGetPos, xpos,ypos
if (xpos>306 and ypos>474 and xpos<605 and ypos<495)
{
	ToolTip, Double click in text box below`nto get IMDB title and year,305,430
	SetTimer, RemoveToolTip, 5000
}
If (A_PriorHotKey = A_ThisHotKey and A_TimeSincePriorHotkey < 500) 
{
    CLR_Start()
	imdb := CLR_LoadLibrary("c:\Program Files (x86)\Autohotkey\Extras\Scripts\Karpach.IMDB.dll")
	;Type names must be fully qualified.
	server:= CLR_CreateObject(imdb,"Karpach.IMDB.Server")
	Send ^a
	Sleep 100
	clipboard =   
	Send ^c
	ClipWait
	title:=COM_Invoke(server,"GetMovieTitleWithYear",clipboard)
	COM_Release(imdb)
	COM_Release(server)
	clipboard = %title%
	Send ^v
	return  
}
return

#IfWinActive

 

Now whenever you double click in volume label text box content would be converted into proper movie title.

AutoHotkey scripts and DLLs

IMDB API .NET library source code

Posted on Sunday, December 25, 2011 by | Add Comment

Simple factory pattern based on interfaces

The main purpose of factory design patterns is to separate object creation process from current implementation context. During coding you use factory to create objects. Based on incoming parameters factory decides which object to create. You don't know exact type of the object. Usually you know either base abstract class type that created object was inherited from or interface that created object is implementing. Based on this knowledge you can use object (call abstract class methods or interface methods). I found a lot of factories examples with abstract class connection, but none with interface connection. However interface connection is most common in commercial factory design pattern implementations. Many developers use Unity Framework or Castle Project (example of connection based on interface). Below I'll show how to implement factory with interface connection like it is done in Unity Framework or Castle Project.

Lets build animal fabric, which would create dogs and cats objects. Let's define ICat and IDog interfaces.

public interface ICat
{        
    string Meow();
}

public interface IDog
{
    string Bark();
    string Sit();
}

Now, lets define some Dog and Cat classes that implement ICat and IDog interfaces respectevly.

public class Cat:ICat
{               
    public string Meow()
    {
        return "Meow meow meow ...";
    }     
}

public class Dog: IDog
{        
 
    public string Bark()
    {
        return "Woof woof woof ...";
    }
 
    public string Sit()
    {
        return "I am sitting.";
    }
 
}

Now lets create factory:

public class DefaultFactory
{
    public static T Create<T>()
    {
        if (typeof(T) == typeof(IDog))
        {
            return (T)(IDog)new Dog();
        }
        else
            if (typeof(T) == typeof(ICat))
            {
                return (T)(ICat)new Cat();
            }
            else
            {
                throw new NotImplementedException(String.Format("Creation of {0} interface is not supported yet.", typeof(T)));
            }
    }
}

And here how you can use it:

IDog dog = DefaultFactory.Create<IDog>();
ICat cat = DefaultFactory.Create<ICat>();
Console.WriteLine(dog.Bark());
Console.WriteLine(dog.Sit());
Console.WriteLine(cat.Meow());


Output:

Woof woof woof ...
I am sitting.
Meow meow meow ...

Source code for sample project above.

Posted on Monday, September 05, 2011 by | Comments (1) | Add Comment

Categories

Recent Tweets

Valid HTML5