Common JavaScript Gotchas – Part 1

This is a gotcha. But don’t worry, Noel Edmunds isn’t anywhere nearby.

Pop quiz, hotshot, the image shows a common JavaScript ‘gotcha’ – or inadvertent mistake through incomplete knowledge of something. What exactly is happening here?

You create a simple function called “getPerson”, and it returns you a JSON object with a single property on it, “name”. However! When you come to use the “name” property, it is undefined.

How come?

 

The Amazing Solution!

I prepared this gotcha after a lunchtime discussion with some colleagues turned to the “Python” programming language (yes, we’re geeks, get over it).

One chap made a derogatory comment of Python, something like, “what kind of a programming language uses white-space as flow control?!”

The irony is, ubiquitous JavaScript is happy to use whitespace as flow control too…

JavaScript Uses Whitespace as Flow Control? What on earth are you on about, Richard? You lunatic.

It’s true! The problem with the code above is where the curly brace ‘{‘ is placed after the return statement.

 

JavaScript Gotcha!

Wrong:

<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript Gotchas 1</title>
	</head>
        <body>
		<script type="text/javascript">

              		var getPerson = function () {
				return 
				{
				    name: "Bob"
				};
			}

                        alert(getPerson().name);
                </script>
	</body>

</html>

 

Right:

<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript Gotchas 1</title>
	</head>
        <body>
		<script type="text/javascript">

              		var getPerson = function () {
				return {
				    name: "Bob"
				};
			}

                        alert(getPerson().name);
                </script>
	</body>

</html>

 

As JavaScript doesn’t require you to define the return type of a function (like C# does, for example), you can just simply call “return” at any point and it will end the execution of the function. This is the important part: Semi-colons in JavaScript are sometimes optional! And calling return is one of those cases!

From the JavaScript parser’s point of view, you’ve simply called “return” and then put a line break (return key on your keyboard). The parser assumes you want to return then and there and ends execution. It DOESN’T go looking around on the following lines to see if you’ve specified something to actually return!

So in-fact, the above call to “getPerson()” returns you “undefined”, and “undefined” doesn’t have anything on it called ‘name’.

Bottom line: JavaScript uses whitespace as flow control!

 

Mitigation

You can stop this from happening by always ensuring your curly braces go on the same line as the return statement (as above in the “Right” code example). In fact, in JavaScript you should always try to write your code with the curly brace on the same line as the statement that prefixes it. It’s the “One True Brace Style” after all. (Although I prefer Eric Allman indentation for everything that isn’t JavaScript).

 

    if (expression) {
        // do something
    }

 

    for(var i = 0; i < myArray.length; i++){
        // Enumerate myArray
    }

 

Etc. Etc. Etc.

In the next “Common JavaScript Gotchas” article, I will be delving into the murky depths of Type Coercion! (I bet you’re salivating at the thought.)

 

 

Google Launches Chrome Packaged Apps

Google has announced the release of Chrome version 22 to developers. The exciting thing about this version is Chrome Packaged apps: a mechanism which allows web applications to behave much more like native applications, blurring the lines between the two. Packaged apps are installed for offline use by default and also open up new low-level system APIs, unlocking access to TCP/IP, Bluetooth and USB.

New “typed data” sources also give developers new tools to interact with photos, music and other content.

Here’s more from Erik Kay, Engineering Manager, Chrome Division:

 

Continue Reading “Google Launches Chrome Packaged Apps”

Func<T> vs. Action<T>

Methods…

Although I’ve been using Func<T> and Action<T> for years, I’m embarrassed to say I hadn’t really thought about the differences between them – or more importantly, how they are in fact two sides of the same coin.

Most of the time their use has been a natural reflex action to a coding problem, and the consideration of the other method hasn’t even entered my mind. It’s time I also start using their proper names, which also belies their use:

 

Action<T>

and

Func<TResult>

 

Today’s Problem

I needed a way of enumerating a directory of files and executing a bit of arbitrary code against each one. The code that was to be executed needed the contents of the file. Continue Reading “Func<T> vs. Action<T>”

Introducing…. Meteoric

This has nothing to do with JavaScript. Sorry.

Meteoric (source: http://github.com/richstokoe/Meteoric, documentation: http://richstokoe.github.com) is a JavaScript framework that allows UIs to be built on-the-fly driven by JSON metadata. The JSON metadata is parsed by “writers“, very focussed JavaScript functions which understand the specific requirements of that metadata and spit out HTML to the DOM. Styling is done through CSS.

The idea is that you can build web applications very quickly simply by breaking down your applications into [data] and [renderers for the data].

 

Data

Consider the following JSON object representing a customer:

var customer = {
    "type": "customer",
    "id": "1234",
    "name": "John Smith Ltd.",
    "email": "john@example.com"
}

Continue Reading “Introducing…. Meteoric”

An ASP.NET MVC4 Razor2 Bug? (Updated)

Let’s Get Geeky!! This week I have been updating a project I’m working on from ASP.NET MVC3 to ASP.NET MVC4 (Beta). MVC4 ships with an improved version of the Razor view engine. But “updated” apparently also means “broken”… That is, if you’re using jQuery UI Widgets. Which I am. So it is.

Let’s build a simple MVC app and show you what I mean. The steps are the same for MVC 3 and MVC 4, but the MVC 3 one works while MVC 4 doesn’t. (If you’re lazy, I applaud you. I provide both code samples at the bottom of the page).

Continue Reading “An ASP.NET MVC4 Razor2 Bug? (Updated)”

8 Things Windows 8 Needs to do to Be a Success

Window 8 Metro. Nothing to do with Rome's underground train network...

1. Stop Stealing My Focus!!!

I can’t stress this enough. The single greatest threat to the economic recovery, continuation of the species and integrity of my sanity is the way Windows is completely dense about giving applications focus.

I simply can’t count the number of times I’ve been typing away merrily and Windows switched applications under me. This is a huge security threat!! I have seen people typing passwords into password boxes during demonstrations only to find that just as they typed the first keystroke of their ultratopsecret, high-entropy passphrase Windows switches to an open Word document and the million people in the stadium, and the forty billion people watching the webcast see you’re a fan of obscene passwords. (And immediately, empty your bank accounts).

That’s slightly exaggerated but I have seen my parents suffer this while helping them set up internet banking. While entering a password into IE, Firefox finally loaded after an update, immediately took focus, and Dad ended up putting his password into the address bar and got a list of Google results for the password. This means that now not only do I know the key to my inheritance fund, but so do Larry and Sergey. Continue Reading “8 Things Windows 8 Needs to do to Be a Success”