Tag Archives: Javascript

When to declare a Javascirpt variable using the var keyword

Today I watched The jQuery Divide: By Rebecca Murphey. I don’t consider myself a Javascript noob, but the talk did make me question my reliance on a Javascript library and whether I knew enough about Javascript to actually wield a library efficiently. So I decided to review my knowledge of Javascript from the ground up and make sure I understood how and why things work they way they do.

First stop: variable declaration

Consider this bit of a script:

// Global scope
var someVariable = 'Levi Jackson';
anotherVariable = 'John Doe';

function assignName(){
   someVariable = 'Jackson Levi'; // Global scope
   var anotherVariable = 'Doe John'; // Local scope

   alert(someVariable); // Jackson Levi
   alert(anotherVariable); // Doe John
}

assignName(); // call the function
alert(someVariable); // Jackson Levi
alert(anotherVariable); // John Doe

The output of the above starts to show you the difference in scope. When you use the var keyword it declares the variable in only the current scope you are working within. Not using the var keyword means Javascript will cascade up until it finds a variable by that name and assigns the value. If it does not find the variable it will create the variable and assign the value to the global object. Consider the following example:

// Global scope
		var someVariable = 'Levi Jackson';
		anotherVariable = 'John Doe';
		
		function assignName(){
		    someVariable = 'Jackson Levi'; // Global scope
		    var anotherVariable = 'Doe John'; // Local scope
		
		    alert(someVariable); // Jackson Levi
		    alert(anotherVariable); // Doe John
		   
		    function assignNames2(){
		   		someVariable = 'LJ';
		   		anotherVariable = 'JD';
	 	  	}
		    assignNames2();
	   		
	   		alert(someVariable); // LJ
	   		alert(anotherVariable); // JD
		}
		
		
		assignName();
		alert(someVariable); // LJ
		alert(anotherVariable); // John Doe

That is a better example of exactly how variable assignment cascades upwards. When a variable is set in assignNames2(), it first checks to see if there was a local variable of the same name set in the parent function assignName(). anotherVariable is the only local variable in assignName() and so the value is overwritten with ‘JD’. someVariable on the other hand was not local and so it continues upward to the global scope and sets the variable to ‘LJ’. That is precisely why the end result is that someVariable == ‘LJ’ and anotherVariable == ‘John Dow’.

How to select input names that contain square brackets

Array of checkboxes.

I was working on a site where I needed to validate that at least one value from a set of checkboxes was checked. They were set like so:

<input type="checkbox" name="subCat[]" class="subCat[]" value="1" /> One
<input type="checkbox" name="subCat[]" class="subCat[]" value="2" /> Two 
<input type="checkbox" name="subCat[]" class="subCat[]" value="3" /> Three

I tried checking each of the inputs with a class of subCat[] by using the nice handy .each function in jQuery.

	$('.subCat[]').each(function(){
		alert('hey');
	});

The error.

When I ran the page I was greeted with a nice error within Firefox’s error console.

Error: uncaught exception: Syntax error, unrecognized expression: ]

The solution?

My first thought was that the square brackets needed to be escaped. So I tried escaping it like I do with PHP:

	$('.subCat[]').each(function(){
		alert('hey');
	});

Nope.

Still the same error. So I did some Googling and for the given error message I was told that the “@” was removed from jQuery 1.3 when referencing an attribute… A completely irrelevant answer for this situation. So I gave up searching and was about to post a question on Stackoverflow when I decided to keep trying to figure it out.

That is when I made one last search on Google and came up with this magnificent page.

The real solution

Turns out the solution is what I thought it was, to escape the square brackets. I just didn’t realize I needed to also escape the forward slash. So the final code that iterates through the input is:

	$('.subCat\[\]').each(function(){
		alert('hey');
	});

I hope I spared someone the time it took me to figure this one out.

Arrays and cookies in javascript

So I was just working on a web project involving cookies. The site had a couple categories of pages that each had their own ‘tips’ for the user. The ‘tips’ can be hidden or shown by clicking on a button. So I figured rather than creating a page specific function to tell whether to keep the tip open or closed I would write one for all the pages. It started out rather easy, making the array, setting the cookie, reading the cookie, took less than an half an hour (I had previously created a set,get,and delete cookie functions in javascipt).

The Problem

I went to test it out and it worked on the first test. I saw ,,,0, meaning the first 3 pages had not been visited and the 4th had the ‘tips’ window closed. I was pumped, ready to move onto another task. I went to test another page and when I clicked the button guess what happened? Yeah I figured you would know what, but in case you didn’t, the array/cookie now looked like this ,,,,0,,,

I puttered around for an hour or so trying various things, I kept focusing on where I pulled the info from the cookie and set it to the new array.

showCookie= getCookie('showCookie');
showArray = new Array();
if(showCookie!= ''){
	for(i=0;i<=3;i++){
		showArray[i] = showCookie[i];
	}
}

It looked right to me. So I spent the next half hour digging around looking for what else it could have been. I looked at where I set the array, the length of the array before and after setting it. It always came out as what it was supposed to.

The Conclusion

Then it hit me. What if the array was no longer an array? What if when you set an array as a cookie value it becomes a string? Maybe the explanation for the cookie having these extra commas was that in fact when I was looping through the cookie ‘array’ I was actually appending a string of 4 commas into my new array. I tested this theory out by revising my code.

showCookie = getCookie('showCookie');

//When pulling the cookie array back in, it is a string not an array.
showCookieSplit = showCookie.split(",");

showArray = new Array();

if(showCookie!= ''){
	for(i=0;i<=3;i++){
		showArray[i] = showCookieSplit[i];
	}
}

It worked! Long story short, now I know that I should test everything, even the things I think to be true.