10 Small Things You May Not Know About Javascript

»Samuli Hakoniemi, in Web Development

It doesn’t matter how many years I’ve been dealing with Javascript – it contains many little things that surprises me almost every week. For me, Javascript means a constant learning process.

In this article, I’ll provide ten small Javascript tips, mainly aimed for beginner and intermediate Javascript developers. Hopefully there’s at least one useful tip for every reader :).

1. Variables conversions

This sounds quite obvious, but as far I’ve seen, using object constructors, like Array() or Number() for converting variables is quite common practice.

Always use primitive data types (sometimes referred as literals) for converting variables. These won’t do any extra tricks and they usually have better performance.

var myVar	= "3.14159",
	str		= ""+ myVar,//	to string
	int		= ~~myVar,	//	to integer
	float	= 1*myVar,	//	to float
	bool	= !!myVar,	/*	to boolean - any string with length
							and any number except 0 are true */
	array	= [myVar];	//	to array

Converting to dates (new Date(myVar)) and regular expressions (new RegExp(myVar)) must be done with constructors. However, always use /pattern/flags when creating regular expressions.

2. Converting decimals to hex or octals and vice versa

Are you writing separate functions for hex (or octal) conversios? Stop. This can be easily done with existing methods:

(int).toString(16);	// converts int to hex, eg 12 => "C"
(int).toString(8);	// converts int to octal, eg. 12 => "14"
parseInt(string, 16) // converts hex to int, eg. "FF" => 255
parseInt(string, 8) // converts octal to int, eg. "20" => 16

3. More playing with numbers

In addition to previous section, here are some more small tricks with when dealing with numbers.

0xFF; // Hex declaration, returns 255
020; // Octal declaration, returns 16
1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000
(1000).toExponential(); // Opposite with previous, returns 1e3
(3.1415).toFixed(3); // Rounding the number, returns "3.142"

4. Javascript Version Detection

Are you aware which version of Javascript your browser supports? If not, check Javascript Versions sheet from Wikipedia.

For some reason, features in Javascript version 1.7 are not widely supported. However, most browsers released within a year support features in version 1.8 (and in 1.8.1).

Note: all the versions of Internet Explorer (8 and older) supports only Javascript version 1.5.

Here’s a tiny script both for detecting the version of Javascript via feature detection. It also allows checking support for specific version of Javascript:

var JS_ver	= [];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports	= function()
{
	if (arguments[0])
		return (!!~this.join().indexOf(arguments[0] +",") +",");
	else
		return (this[this.length-1]);
}

alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

5. window.name for simple session handling

This one is something I really like. You can assign values as a string for window.name property and it preserves the values until you close the tab or window.

Although I’m not providing any script, I strongly suggest you to take full advantage from it. For instance, it’s very useful for toggling between debugging and (perfomance) testing modes, when building a website or an application.

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:

// BAD: This will cause an error in code when foo is undefined
if (foo) {
	doSomething();
} 

// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
	doSomething();
}

// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
	doSomething();
}

However, there may be situations, when we have deeper structure and proper checking would look like this:

// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
	doSomething();
}

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:

function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}

doSomething('', 'foo', 5, [], false);

It’s always easier to pass only one object instead of several arguments:

function doSomething() {
	// Leaves the function if nothing is passed
	if (!arguments[0]) {
		return false;
	}

	var oArgs	= arguments[0]
		arg0	= oArgs.arg0 || "",
		arg1	= oArgs.arg1 || "",
		arg2	= oArgs.arg2 || 0,
		arg3	= oArgs.arg3 || [],
		arg4	= oArgs.arg4 || false;
}

doSomething({
	arg1	: "foo",
	arg2	: 5,
	arg4	: false
});

This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:

function createList() {
	var aLI	= ["first item", "second item", "third item",
		"fourth item", "fith item"];

	// Creates the fragment
	var oFrag	= document.createDocumentFragment();

	while (aLI.length) {
		var oLI	= document.createElement("li");

		// Removes the first item from array and appends it
		// as a text node to LI element
		oLI.appendChild(document.createTextNode(aLI.shift()));
		oFrag.appendChild(oLI);
	}

	document.getElementById('myUL').appendChild(oFrag);
}

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace().

Following example is a rough implementation of making a more verbose output from a single deal in online poker:

var sFlop	= "Flop: [Ah] [Ks] [7c]";
var aValues	= {"A":"Ace","K":"King",7:"Seven"};
var aSuits	= {"h":"Hearts","s":"Spades",
			"d":"Diamonds","c":"Clubs"};

sFlop	= sFlop.replace(/\[\w+\]/gi, function(match) {
	match	= match.replace(match[2], aSuits[match[2]]);
	match	= match.replace(match[1], aValues[match[1]] +" of ");

	return match;
});

// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:

outerloop:
for (var iI=0;iI<5;iI++) {
	if (somethingIsTrue()) {
		// Breaks the outer loop iteration
		break outerloop;
	}

	innerloop:
	for (var iA=0;iA<5;iA++) {
		if (somethingElseIsTrue()) {
			// Breaks the inner loop iteration
			break innerloop;
		}

	}
}

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript.

And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

Comments

  1. - Harri Kauhanen | #1

    Nice! Your post indeed had some small things I did not know about Javascript.

  2. - Nick Parsons | #2

    Great post! I think all developers love finding out neat little hacks and trivia like this because it’s cool – and it might come in handy some day ;)

    Thanks for posting.

  3. - JavascriptBank.com | #3

    very cool & good things to know more about JS, thank you very much for sharing.

    Can I share this post on my JavaScript library?

    Awaiting your response. Thank

  4. - Samuli Hakoniemi | #4

    Yes. Go ahead an share. My articles can always be shared, no problem with that :).

  5. - Danial | #5

    Great article. some stuff I still didn’t know, now I do ;)
    thanks!

  6. - Bill | #6

    #7 Was a new idea for me. Thanks

  7. - Cory Schires | #7

    Using window.name for simple sessions – that’s very smart.

    This would be useful not only for toggling between environments (as you mentioned) but more generally any session-based feature would otherwise require server-side interaction.

    Sure. You wouldn’t want to use this from something important like authentication. But I can think lots of situations where this would have been useful – like adding localization to an otherwise small, simple, static site.

  8. - Java developer | #8

    Useful article. Big thanks!

  9. - Honey Singh | #9

    I usually ignore the deep into javascript but the your post have many things that i should know about :)

  10. - hubeRsen | #10

    Thats nice stuff, something i doesn’t know before. Thanks.

  11. - Manmohanjit | #11

    Good stuff!

  12. - Tidy Design | #12

    Very TIDY… I will need to sit down and read through this several times! Awesome work!

  13. - Ian Devlin | #13

    Hmm, there’s a lot there that I didn’t know, many thanks indeed for sharing.

    I may reproduce this post (with credits to you naturally) on my own blog, or I might just link to it. Thanks again!

  14. - Martin R. | #14

    Great post! Thank you

  15. - Naveen | #15

    Nice Tutorial..Good job

  16. - SM | #16

    Great collection. Thanks

  17. - Jeff K | #17

    Nice tips. I like #7, but I use it like this:
    Pastebin: function doSomething(options) #1

    If you are using jQuery, it has a neat util function for merging objects, which would allow you to have defaults:
    Pastebin: function doSomething(options) #2

    (admin): functions moved to Pastebin.com. Thank you for the examples.

  18. - Howard Charles Best | #18

    Concerning “1. Variables conversions,” I didn’t know about lines 3 and 5. Thank you very much for teaching me. I added them to one of my instructive web pages:

    http://llbest.com/MathCalculator.htm?SI=64

  19. - Shankar | #19

    Great, got to know very useful points..

  20. - Robin Nixon | #20

    Great post. There are definitely a few tricks here I will use in future!

  21. - Jon Raasch | #21

    Hey I keep digging this post up from my Delicious links, because it is solid gold. This is one the most helpful things I’ve ever read about Javascript (especially the variable conversion stuff). Thanks!

  22. - Matt | #22

    Very interesting post. Thanks.

Trackbacks

  1. February 18th, 2010 at 02:11 | #1
  2. February 18th, 2010 at 07:53 | #2
  3. February 18th, 2010 at 11:28 | #3
  4. February 18th, 2010 at 22:28 | #4
  5. February 19th, 2010 at 08:42 | #5
  6. February 21st, 2010 at 21:15 | #6
  7. February 23rd, 2010 at 01:14 | #7
  8. February 28th, 2010 at 06:54 | #8
  9. March 2nd, 2010 at 22:33 | #9
  10. March 11th, 2010 at 19:10 | #10
  11. March 14th, 2010 at 15:52 | #11
  12. March 22nd, 2010 at 15:00 | #12
  13. May 7th, 2010 at 20:26 | #13