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

Friday, April 9, 2010

Javascript: Always define variable with 'var'

So today, I found one more unseen behavior of Javascript (at least for me).

I wrote a very simple function in Javascript and forgot to add 'var' in front of variable definition. This function worked first time but for second time I got JS error saying the function does not exist. I was like what the hell, where did my function go? It just worked as expected for first time and suddenly browser is not able to find it.

It took me 20 minutes to find out the reason of my biggest mistake of tonight. Such a waste of precious 20 minutes at 3:00 AM :(

Lesson learned, always define variables in Javascript with 'var' keyword or else stay up till late night ;)

Saturday, November 21, 2009

Less know JavaScript operator 'Delete'

One of the lesser known operators in JavaScript is the 'delete' operator. I came to know about while reading John Resig's blog.

What does it do?
The delete operator deletes an object, an object's property, or an element at a specified index in an array.

More about it at Mozilla Reference Docs.

Small Example:
var array = {
"int": 42,
"float": 12.5,
"string": "hello world",
"foo" : "bar"
}
for(var arr in array) {
alert(arr + " : " + array[arr]);
}
delete array['string']; //Removes the 'string' key of the array

for(var arr in array) {
alert(arr + " : " + array[arr]); //The 'string' key & its value will be removed
}

Wednesday, September 2, 2009

JavaScript Error: Expected Identifier in IE

If you are getting 'Expected Identifier' JavaScript error on IE this means you have some conflict with Mr. Gates :)

Okay to the point, this can happen due to two reasons (as per my knowledge, let me know if you know something else):

1. Some typing mistake in your code

var myVar = {
function1: function() { // some code },
variable1: 'Some value',
variable2: 'Another value',
};

Notice the extra comma after the last variable defined just before } braces, Firefox will ignore this but IE will not. Lets move to second reason.

2. You have used reserved keyword in your code mostly as variable name
Just yesterday, I got this error on IE due to some old written JS code. First I tried to find the code mistake but after looking at the code with a sharp eye I found that some reserved words were used. Following is the code I corrected

obj.class = 'up'; ///this works in Firefox
obj.className = 'up'; ///this is the correct implementation

var onloadstat = 0; //works in FF but in IE its a reserved keyword same as 'class'

At the end, if you get the 'Expected Identifier' JS error in IE first look for these mistakes. You will be able to fix the error quickly.