10 Interesting JavaScript Features

I’ve been doing some more reading on JavaScript recently and decided to note down some of what were interesting features for me. If you’ve been doing JavaScript for a while then please let me know if anything looks a bit off, otherwise I hope you find the list an interesting read!

1. There is only one number type in JavaScript

All JavaScript numbers are internally represented as 64 bit floating point values. There is no separate integer type.

a = 1;
b = 1.0;
console.log(a === b); // true

We need to take care with floating point arithmetic as it may not always produce the exact answer you were expecting. For example:

var a = 0.1;
var b = 0.2;
var c = a + b;
 
console.log(c === 0.3); // false
console.log(c === 0.30000000000000004); // true

2. Blocks in JavaScript do not create a new scope

In some languages (like Java) new variables created within blocks such as if, while and for only exist within that block. JavaScript does not have a block scope.

var s = "foo";
if (true) {
	// This overwrites the value in s
	var s = "bar";
}
console.log(s === "bar") // true;

3. You can create anonymous self executing functions

An anonymous self executing function is just a function that has no name and is executed immediately. It can be useful to induce a block scope and can be useful when dealing with closures within loops.

var s = "foo";
if (true) {
	(function() {
		// This does not overwrite the value in s
		var s = "bar";
	})();
}
console.log(s == "foo") // true;

If you haven’t seen a function like this before, it’s built up like this:

// 1. Create the anonymous function
function() {
    // Do something
}
 
// 2. Wrap it in parentheses
(function() {
    // Do something
})
 
// 3. Put () on the end to execute it, just like any normal function call.
(function() {
    // Do something
})();

Not very pretty but is an important concept.

4. You can throw objects for exceptions

If you need to throw an exception, rather than just throwing a message string, throw an object that contains a name and a message.

if (!accountFound) {
	throw {
		name: 'AccountFetchFailed',
		message: 'Sorry, there was a problem fetching the account details'
	}
}

When catching the error you can then test which kind of exception occurred and react accordingly.

5. JavaScript’s try catch has a finally clause

A finally clause in a JavaScript exception will always execute, whether or not an exception was caught. The finally clause will still execute even if there is an error or a break in program flow within the catch clause (such as by a return or break statement).

function testTryCatch(hasError) {
	try {
		console.log("In the try clause");
		console.log("Has Error: " + hasError);
		if (hasError) {
			console.log("Throwing an exception");
			throw "Oops!";
		}			
	}
	catch(e) {
		console.log("In the catch clause: " + e);
		// This return only occurs *after* the finally clause has executed
		return;
	}
	finally {
		console.log("In the finally clause");
	}
}

Testing with no error:

testTryCatch(false);
 
// Output:
//   In the try clause
//   Has Error: false
//   In the finally clause

Testing with an error:

testTryCatch(true);
 
// Output:
//   In the try clause
//   Has Error: true
//   Throwing an exception
//   In the catch clause: Oops!
//   In the finally clause

6. You can explicitly set an array’s length property

Increasing the length causes any missing elements to have an undefined value. Reducing the length deletes elements beyond that length.

var arr = ["one", "two", "three", "four", "five"];
console.log( arr ); // ["one", "two", "three", "four", "five"]
console.log( arr.length ); // 5
 
arr.length = 8;
console.log( arr ); // ["one", "two", "three", "four", "five", undefined, undefined, undefined]
console.log( arr.length ); // 8
 
arr.length = 3;
console.log( arr ); // ["one", "two", "three"]
console.log( arr.length ); // 3

7. There are two equality operators in JavaScript

Javascript has two equality operators; the regular equality operator == and the strict equality operator ===. These have corresponding inequality operators != and !==.

The regular equality operators == and != attempt to convert the operand types when they are not the same type. For example:

( null == false      ); // false
( 0 == false         ); // true
( "" == false        ); // true
( false == false     ); // true
( NaN == false       ); // false
( undefined == false ); // false

The strict equality operators === and !== does not attempt to convert the operand types. If the types are different then they are not the same. For example:

( null === false      ); // false
( 0 === false         ); // false
( "" === false        ); // false
( false === false     ); // true
( NaN === false       ); // false
( undefined === false ); // false

You should generally use the strict equality operator.

For more info see the Comparison operators docs.

8. Falsy, Truthy and boolean values

As you saw in the previous feature, within JavaScript there are several non boolean values that evaluate to false or true. This seems to have led to the terms falsy and truthy.

Falsy values are

  • 0
  • NaN (not a number)
  • ” (empty string)
  • false
  • null
  • undefined

Everything else, including numbers, non empty strings, boolean true, arrays, objects and functions are truthy.

If you have a situation where you must have a real boolean true or false value then you can convert the value using a double negative operator !!.

function makeBool(thing) {
	return !!thing;
}
 
// These are all true
console.log( makeBool(99) );
console.log( makeBool("hello") );
console.log( makeBool(true) );
console.log( makeBool(Number.POSITIVE_INFINITY) );
console.log( makeBool(Number.NEGATIVE_INFINITY) );
console.log( makeBool([]) );
console.log( makeBool({}) );
console.log( makeBool(function(){}) );
 
// These are all false
console.log( makeBool(null) );
console.log( makeBool(0) );
console.log( makeBool("") );
console.log( makeBool(false) );
console.log( makeBool(NaN) );
console.log( makeBool(undefined) );

More details about Falsy and Truthy

9. Parentheses are optional when creating new objects

The parenthesis are optional when creating new objects that require no initial parameters.

function User() {
}
 
var u = new User;

10. Hidden JavaScript features

I started compiling this list as a few interesting things I found as I was reading through JavaScript: The Good Parts and doing a bit of research.

Along the way I found a great set of hidden JavaScript features on Stack Overflow. So check out the list for more interesting JavaScript features.

This entry was posted in JavaScript and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

4 Comments

  1. Posted January 7, 2011 at 3:37 pm | Permalink

    As always, good stuff.

  2. Gary F
    Posted January 7, 2011 at 8:04 pm | Permalink

    Interesting post. I do like Javascript. Someone should invent a way to use it as a server side language. Oh wait.

  3. Ben B
    Posted January 28, 2011 at 7:12 pm | Permalink

    Another pair of issues to watch out for with the equality operators and truthiness/falsiness:


    // objects are truthy, even if their primitive value would be falsy
    console.log(!! 0 ); // false
    console.log(!!(new Number(0))); // true
    console.log(!! "" ); // false
    console.log(!!(new String(""))); // true

    // objects are not strictly equal to their equivalent primitive
    console.log( 0 == new Number(0)); // true
    console.log( 0 === new Number(0)); // false
    console.log("" == new String("")); // true
    console.log("" === new String("")); // false

  4. Posted January 29, 2011 at 6:23 am | Permalink

    @Ben, thanks for the note.