Leave a Comment

A primer on CSS colors

December 29th, 2009

Color keywords

Example usage:

// Example
body { color: red; }

// Generalization (not actual code)
body { color: color_name; }

Because color names are easy to remember, they’re handy for getting quick results, especially while doing rapid prototyping.

W3C’s CSS1 recommendation first mentioned 16 color keywords that you can use: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow:

Color Hexadecimal Color Hexadecimal Color Hexadecimal Color Hexadecimal
aqua / cyan #00FFFF gray #808080 navy #000080 silver #C0C0C0
black #000000 green #008000 olive #808000 teal #008080
blue #0000FF lime #00FF00 purple #800080 white #FFFFFF
fuchsia / magenta #FF00FF maroon #800000 red #FF0000 yellow #FFFF00

(color table from Wikipedia)

CSS2 officially mapped the colors to recommended hex values and also added the color orange. CSS3 removed orange, presumably because having 17 colors was aesthetically unpleasing in a binary world?

In addition to these 16 “official” colors, there’s even more unofficial color names you can use that appear to be supported in all the major browsers.

RGB values

Example usage:

// Example
body { color: rgb(255,0,0); }

// Generalization (not actual code)
body { color: rgb(red [integer 0-255], green [integer 0-255], blue [integer 0-255]); }

For this section it’s very handy to know a bit about color theory, particularly these facts:

  • all colors can be made from a combination of red, green, and blue (RGB) as the primary colors
  • in light (additive color mixing), the absence of all color results in the color black
  • in light (additive color mixing), the mixing of red, green, and blue in equal amounts results in the color white

With the rgb attribute, we specify the amount of each color we want with an integer from 0 to 255. Here we can see both black and white expressed as rgb values:

Black:
rgb(0,0,0)

White:
rgb(255,255,255)

Also note that if all three values are equal, there is no color that predominates and the result is a shade of gray.

Dark gray:

rgb(30,30,30)

A lighter shade of gray:

rgb(200,200,200)

And of course we can favor only one color, which in this case gives us a full red, with no green or blue:

rgb(255,0,0)

You may have guessed that we can also use percentage values to represent the same color:

rgb(100%, 0%, 0%)

RGBA values

// Example
body { color: rgba(255,0,0,0.5); }

// Generalization (not actual code)
body { color: rgb(red [integer 0-255], green [integer 0-255], blue [integer 0-255], alpha transparency [float 0-1]); }

CSS3 introduced rgba, which is in every way similar to rgb, except for the addition of a fourth value, alpha opacity, which gives us control over the transparency of the color.

So the equivalent full red we have above would look like this (no transparency):

rgba(255, 0, 0, 1)

rgba(100%, 0%, 0%, 1)

And the same color, only now semitransparent:

rgba(255, 0, 0, 0.5)

rgba(100%, 0%, 0%, 0.5)

Hex values

Example usage:

// Example
body { color: #ff0000; }

// Generalization (not actual code)
body { color: #rrggbb; }

Hex values are probably the most common out of all of the ways to represent colors in CSS. But I included them last – what gives? It seems to me that the rgb value should logically be explained first. The hex value is just a hex version (and thus slightly more confusing version) of expressing rgb values.

For this section you ought to know the basics of hexadecimal numbers. In particular, the fact that hexadecimals are base 16 and use letters a-f to represent numbers beyond our conventional base 10 range.

The hex value starts with a hash (#) and is followed by six numbers and/or letters. This is simply our three color values again: red, green, blue, with each color allowed two digits.

We express our solid red color like this:

#ff0000

As long as you can convert between decimal and hexadecimal (there’s a few free tools online), it’s relatively easy to convert between rgb and hex color values. Just keep in mind that the first 16 hex values are preceded by a zero (0 becomes 00, 1 becomes 01, 10 becomes 0a, 11 becomes 0b, etc.)

Shorthand hex

Example usage:

// Example
body { color: #f00; }

// Generalization (not actual code)
body { color: #rgb; }

Last but not least, if each rgb value has a repeating value, you can simply omit the repeating value. In the case above each of our color values was repeating (red = ff, green = 00, blue = 00), so we simply drop the repeating digit from each color and cut three bytes from our code:

#f00

A note on web-safe colors

Web safe colors were a recommended subset of about 256 colors with which to design websites. The rationale for solely using them for web design was for rendering consistency, so even users with very limited displays could see the page as it was intended to be displayed.

The concept of a “web safe” color was becoming obsolete even in 1997 or so, when I started making my personal website on AOL. It’s safe to say that the vast majority of users today are now able to view webpages with at least 16 million colors (256*256*256).

But this doesn’t mean we shouldn’t be concerned about colors. Apart from pure aesthetics, in the area of accessibility it’s often mentioned that users with colorblindness find certain combinations of colors difficult to see. So keep this in the back of your head when you go crazy with those wild color schemes!

More info

Probably the best way to learn how to use these color values is to actually try them on your website, however you might also find the following links useful.

Color Scheme Designer

Color Scheme Designer is a nice tool for finding several colors that (theoretically) should go well together. It’s a nice place to go when building a website from the ground-up.

http://colorschemedesigner.com/

Color Scheme Designer

Jonathan Schlaepfer made a nice helper tool built in Mootols for creating webkit gradients. Gradients wasn’t the subject of this entry, but it’s helpful to see a nice visualization of rgb values corresponding to the hex values.

http://schlaeps.com/mootools/gradient-creator/

Wikipedia: Web colors

HTML Colors

Leave a Comment

Video: John Resig – Testing, Performance Analysis, and jQuery 1.4

December 21st, 2009

In case you hadn’t seen it yet, John Resig was kind enough to stop by Yahoo! for the December Bayjax meetup. Here’s the video:

Usually developers are more interested in just getting the dang code to work, and as a result actual the testing and maintenance of JavaScript isn’t talked about too much, so I’m sure this will be new territory for many developers. And since it’s John Resig speaking, there was of course a bit about using TestSwarm, a testing distributed framework-agnostic automated testing tool (that’s a mouthful!).

Included in the talk are good things to note while testing, such as the fact unless you’re running Firefox or Chrome on Windows, all test times have a margin of error of up to 15ms (not to be confused with PPK’s observation of the delay between JavaScript computation and browser rendering).

(via YUIBlog)

6 Comments

PastryKit: digging into an Apple Pie

December 16th, 2009

Yesterday John Gruber wrote about Apple’s PastryKit, iPhone’s JavaScript framework that’s been discovered “in the wild” on the iPhone user guide at http://help.apple.com/iphone/3/mobile/. There’s a few ways to access the page:

  • with an actual iPhone or iTouch
  • by browsing with an iPhone/iTouch user agent. If you’re using Safari, enable the Developer menu in Safari>Preferences>Advanced and switching user agents by clicking on Develope>User Agent

What’s all the big fuss?

John was particularly interested in the responsiveness and native-like interaction of flinging through long lists, the fact the address bar is completely hidden, and the possibility of having a toolbar fixed to the top of the page. PastryKit makes all of these things possible and implements them better than anything else. And the result is nearly indistinguishable from a native app. Here’s a video I made of the iPhone user guide in action, powered by PastryKit. This is running on Safari – it’s not a native app!

PastryKit has been here for a while

As John Gruber points out, the code for PastryKit has been there for quite a while now. Stack Overflow has a question about it that was asked way back in July, and there are several more recent references to it by jQTouch developer David Kaneda on Twitter. Of course, since John’s post there’s been an explosion of interest in the form of even more tweets!

Hopefully with all of this increased attention, we’ll see Apple take notice and address it. Here’s hoping, anyway.

Some interesting features

There’s even more interesting takeaways from the PastryKit code, and I’m sure I’ve just barely scratched the surface:

  • implements its own form of Object-Oriented programming (obj.inherits and obj.synthetizes properties). When modules are declared, they’re registered as a PK Class (i.e. PKClass(PKBarButtonItem) registers PKBarButtonItem as a PK Class)
  • CSS3 wrapper functions (PKUtils.t() is a wrapper for translate3d, etc.)
  • no single library namespace (surprisingly) – which means there are many many global variables. This however is somewhat acceptable, as all variables are prefixed with “PK” and are declared to be constant (const PKStartEvent, const PKEndEvent) and cannot be overwritten.

There’s also some interesting takeaways not from PastryKit itself, but from the way the iPhone user guide is implemented. Most of the data on the page – including each menu icon (base64 encoded) – is located in a single 650kb JSON-encoded file called content.json. This means the initial loading of the page is quite slower than the user would normally expect, but once the initial payload has been delivered, it’s a relatively smooth browsing experience thereafter.

And as John Gruber already pointed out, this data is stored locally with the help of HTML5, allowing the user to continue reading even while offline!

iPhone user guide in Safari

iPhone user guide in Safari

PastryKit unminified and explained (sorta)

What I’m excited to show you now is a result of a bit of effort to make PastryKit more intelligible. Though there’s a minified version of the code on Apple’s website, it’s not obfuscated (and rendered unintelligible), so not all hope is lost! With the help of jsbeautifier.org we can now see the slightly unminified version of the code: PastryKit.js unminified.

The next thing I did was separate each module into its own file. I was able to separate the code into 27 numbered files, with the original ordering preserved (to prevent issues with dependencies). Viewing the code in this way definitely helps make sense of it all. You can download these separate files as part of a little unofficial SDK I made, which also includes a copy of the iPhone user guide with the JS iPhone-only redirect removed: PastryKit unofficial SDK.

PastryKit modules

The following is an explanation of each module I found. The descriptions are definitely incomplete and possibly inaccurate, so any comments or help is appreciated. But this should hopefully shed some light on the matter!

  • PKUtils – general helper functions (PKUtils.t() is a wrapper for CSS translate3d, PKUtils.degreesToRadians(), etc, etc.)
  • PKEventTriage – general event handler
  • PKPropertyTriage – handlePropertyChange() method – ?
  • Element – helper functions added to HTML Element prototype
  • Node – adds getNearestView() method to HTML Node prototype
  • PKClass – custom-rolled class with with “inherits” and “synthetizes” properties
  • PKObject – custom-rolled object with observer pattern. Most modules extend from this.
  • PKPoint – wrapper for WebKitPoint – used for touch events?
  • PKSize – wrapper for width/height properties
  • PKImage (inherits PKObject) – helper for creating Image elements and knowing when it’s finished loading (but doesn’t add the image to the DOM)
  • PKAnimator – basic animation tweens
  • PKTransition – helper for proprietary Webkit CSS transitions
  • PKTransaction – interacts with PKTransition – ?
  • PKView (extends PKObject) – manages a view, such as handling events that occur within that view – ?
  • PKContentView (extends PKView) – ?
  • PKRootView (extends PKContentView) – ?
  • PKScrollIndicator (extends PKView) – custom scrollbar
  • PKScrollView (extends PKView) – handles dynamically positioning the page when it’s scrolled
  • PKTableView (extends PKScrollView) – handles more touch/scroll events?
  • PKCellPath – ?
  • PKTableViewCell (extends PKView) – ?
  • PKToolbar (extends PKView) – manages the top toolbar
  • PKNavigationView (extends PKView) – manages bottom navigation bar
  • PKNavigationItem (extends PKObject) – manages bottom navigation buttons
  • PKControl (extends PKView) – manages generic controls
  • PKBarButtonItem (extends PKControl) – manages button controls
  • PKSearchBar.js (extends PKView) – manages the search bar

Conclusion after a first glance

As far as I can tell, this is no full-fledged JavaScript library. At least not for now.

On first glance PastryKit seems to be at most a nice development framework for making web apps with the same look-and-feel of native iPhone apps. And this framework in many ways does this better than anything out there (at the moment).

I echo the sentiments of Gruber – I do hope we hear more about this from Apple!

Leave a Comment

JavaScript tidbit: special variables ($, $$, _, etc)

December 8th, 2009

You’re probably used to typical variables names such as the following:

var personName = 'Joe';

You may not realize it, but there are some non-alphanumeric variables at your disposal.

Using $

For instance, the $ variable has been made popular by several JavaScript libraries, most notably jQuery. You can use it to alias operations that are commonly performed, such as the following (1):

var $ = document.getElementById;
var myElement = $('targetElement');

If you declare this variable outside of a function it will be a global variable and will compete with libraries that use the same global variable, so it’s probably best not to use it.

Interestingly, originally the dollar sign $ was originally intended for “mechanically generated code” (2), but as the usage of the symbol has become popular for other purposes, it looks like the latest version of JavaScript (ECMAScript 5th edition) now officially “oks” its use:

This standard specifies specific character additions: The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Using $$

Some have come up with the solution of simply using two or more $$ symbols in order to distinguish the variable from libraries that just use a single $:

var $$ = document.getElementById;
var myElement = $$('targetElement');

Using _

You will find that you can use the underscore _ in the same way to alias variables and functions:

var _ = document.getElementById;
var myElement = _('targetElement');

Other symbols

If you’re really getting adventurous, you can even try using other symbols such as square root √, which seems to work just fine, just as $ and _ above. The only problem: it’s quite inconvenient using it, since it’s not available on any keyboards (except through some crazy key combinations perhaps).

Or you can put the symbol to use doing what you would naturally think it should do…

var √ = Math.sqrt;
alert(√(4));   // 2

References

(1) Even Faster Web Sites, p. 128
(2) Stackoverflow: Why would a javascript variable start with a dollar sign?

Leave a Comment

Ways of passing data to functions in JavaScript

December 4th, 2009

Passing data is quite important in functional programming languages like JavaScript. When there are multiple functions (which is most of the time), there needs to be a way to pass data between the functions. This is done by passing values in parenthesis: myFunction(myData). Even when there is no data to be passed, we still have to declare and execute functions by using parenthesis: myFunction().

Simple Passing

I’ve already referred to the common method of passing data. Here’s an example of the code in action:

function greeting (name) {
    alert('Hello ' + name);
}
var personsName = 'Joe';
greeting(personsName);  // Hello Joe

This example only passes one variable to the function. Note that we can get rid of the variable personsName and make the string on the fly. So the code above is equivalent to this:

function greeting (name) {
    alert('Hello ' + name);
}
greeting('Joe');  // Hello Joe

Ok. Now let’s suppose we have a function that accepts two variables:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Joe', 'Schmoe');  // Hello Joe Schmoe

This doesn’t look too hard. But there’s a catch – the person writing the code has to remember the order of variables to pass in. Suppose they call the function like this:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Schmoe', 'Joe');  // Hello Schmoe Joe

That’s no good! This isn’t the result we want. In the case of firstName and lastName the variable order isn’t too hard to remember, but in other cases the variables aren’t in any logical order, which can cause confusion.

No constructor overloading

Unlike other languages such as C++ and Java, JavaScript has no constructor overloading. In fact, JavaScript is (for better or worse) not even strict about enforcing the number of variables passed in. For example, the following code works fine and throws no errors, even though we’re not passing in a variable in the function call:

function test (someVar) {
    // do stuff
};
test();  // no errors!

It’s only when you try to use someVar within the function that causes the problems. Otherwise, everything’s working just fine and dandy.

What happens if we try the other case scenario: pass in more variables than the function expects? No errors again:

function test () {
    // do stuff
};
test('testing 123');  // again, no errors

And what happens if we try to declare a function with the same name? No errors, but the previous function is overwritten (this is generally to be avoided of course):

function test () {
    alert('First function');
};
function test () {
    alert('Second function');
};
test();  // Second function

Because JavaScript has no function overloading, all it takes to overwrite another function is to redeclare a function with the same name. It doesn’t matter what sort of arguments they accept.

Passing with the help of the arguments object

As it turns out, JavaScript has a handy arguments object to access the arguments passed into each function:

function test () {
    alert(arguments[0]);    // testing 123
};
test('testing 123');

In the above case the arguments object acts just as an array – it’s 0-indexed and can be used to access any arbitrary number of arguments. But arguments also has an interesting and useful property: length. Using arguments.length, we can traverse the array of arguments. This is handy in cases where we might want to add an arbitrary number of elements together:

function add () {
    var sumTotal = 0;                        // initialize total to 0

    for(var i=0; i<arguments.length; i++) {  // for each argument
        sumTotal += arguments[i];            // add current argument to total
    }

    alert(sumTotal);
};
add(2, 3, 4);  // 9
add(1, 1, 1, 1, 1, 1, 1, 1, 1);  // 9

Passing an object

JavaScript libraries such as YUI have already learned that the variable order is a common nuisance and an opportunity to introduce errors, so they’ve come up with a solution: pass a single object to the function. It ends up looking something like this:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {};
nameObject.first = 'Joe';
nameObject.last = 'Schmoe';
greeting(nameObject);  // Hello Joe Schmoe

Now the variables become properties of a single object which is passed into the function. And it doesn’t matter which order the properties are declared in, which is a great relief to the developer.

Note that we can simplify the above code:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {
    first: 'Joe',
    last: 'Schmoe'
};
greeting(nameObject);  // Hello Joe Schmoe

And we can simplify even further:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
greeting({
    first: 'Joe',
    last: 'Schmoe'
});  // Hello Joe Schmoe

This is the form commonly used in these JavaScript libraries. It’s easy to copy-and-paste example code, but it might not always be so obvious what’s going on behind the scenes. You can see that just as we bypassed declaring a named variable in the Simple Passing model (with greeting(”)), here we use the same shortcut and bypass declaring a named object (with greeting({})).

call() and apply()

These two methods have different techniques for passing data to functions, but I’m going to have to hold off on them for now. It’s a bit complicated, since they’re only used to execute methods (functions) in other object contexts. But seeing as I need to explain object context to get into that, I’ll save that for a future entry!

Leave a Comment

IEMobile 6/7 bug: classes and id not supported on the HTML element

December 1st, 2009

As it turns out, IEMobile 6/7 (and presumably anything earlier) doesn’t support classes and ids that are attached to the HTML element. I confirmed this on both IEMobile 6 and 7. Fortunately it looks to be fixed in IEMobile 8 (which makes sense, since it works fine in desktop IE6, which it’s based on).

The consequence of this is that adding an id/class to the html tag will result in the style not being applied to the document:

<!doctype html>
<html id="a" class="b">
<head>
	<title>Cascade test</title>

	<style type="text/css" media="screen">
		#a span { color: red; }     /* style isn't applied in IEMobile 6/7 */
		.b span { color: yellow; }  /* style isn't applied in IEMobile 6/7 */
	</style>
</head>

<body>
<span>Testing 123</span>
</body>

</html>
1 Comment

PHP: dealing with stuff that doesn’t exist

December 1st, 2009

Introduction

As the application you’re coding becomes more and more complex, there’s more of an opportunity for things to go wrong in all sorts of unforseen ways.  One of these problems is variables or functions that don’t exist.  The problem is when you code in such a way that you presuppose their existence. But their existence isn’t guaranteed!

A simple case of this happening is when you’re dealing with user input.  As it turns out, the user didn’t fill out a text field, but the variable for that text field still gets passed around as if it did exist.  More specifically, the variable gets set, but it gets set to an empty string (”).

Check that the variable isn’t empty

A common way of dealing with this is to check that the variable isn’t empty before using it:

$name = 'Joe';
if($name != '') {
	echo 'Hello ' . $name;
}

This turns out to be ALMOST equivalent to the following, which uses empty():

$name = 'Joe';
if(!empty($name)) {  // make sure $name isn't empty
    echo 'Hello ' . $name;
}

However, as Zachary Johnson points out, empty($variable) evaluates to true when $variable=’0′, so you may want to avoid using this.

Check that the variable is defined

There’s another case we haven’t tried yet: what happens if we haven’t defined the variable?

error_reporting(E_ALL);
if($name != '') {
	echo 'Hello' . $name;
}

Nothing catastrophic happens, but if we turn on error reporting, we can see that PHP is a bit upset. We get a notice that the variable $name is undefined, yet we’re trying to evaluate it. The value hasn’t been set yet. And there’s a function to check for that:

$name = 'Joe';
if(isset($name)) {
	echo 'Variable is set';
}

We can combine what we’ve learned into the following:

$name = 'Joe';
if(isset($name) && $name != '') {
	echo 'Hello ' . $name;
}

There’s one neat thing here – if $name isn’t set, it evaluates the first part of the If condition as false (isset($name)) and doesn’t even look at the second part of the If condition ($name != ”). This is because it doesn’t matter what comes after, it will still evaluate to false (false && true evaluates to false, and false && false evaluates to false). Looking at the rest of the If condition is a waste of CPU cycles, so PHP doesn’t do it!

We can confirm this with the following code, which evaluates to false on the first If condition, then doesn’t even try to evaluate the call to a nonexisting function, and thus gives no errors:

if(false && function_that_doesnt_exist()) {
	// do stuff here
}

Check if a function exists

For functions there’s a similar helper called function_exists():

function my_function() { }
if(function_exists('my_function')) {
	my_function();
}

And it doesn’t matter if your function is declared before or after you call it! Check it out – this works fine:

if(function_exists('my_function')) {
	my_function();
}
function my_function() { }

Check if an object’s method exists

Similarly to checking if functions exist, we can check for the existence of functions belonging to an object (we call these the object’s methods) with method_exists():

// Create a test class
class myClass {
	// Create a test function
	public function my_function() {}
}

// Instantiate the class
$myObject = new myClass();

// Check to see if the test function exists
if(method_exists($myObject, 'my_function')) {
	// Do stuff here
}
2 Comments

Pitfalls of declaring variables in JavaScript

November 18th, 2009

Introduction

One of the things that’s always been confusing to me is that there are multiple ways to declare variables in JavaScript, and some ways are better than others. For the beginner programmer, just getting to code to work means complete success, but for the intermediate or advanced programmer, this is just the first step. The next step is to clean up the code and make sure everything is written in the best way it could have been written.

Declaring variables seems like such a basic thing that one almost feels insulted reading about it. Yes, this whole post is about declaring variables. But not just this – it’s about declaring variables the right way. This means declaring variables in the scope they were intended to be declared in.  For the most part this means writing variables in the scope of a function, as opposed to the global namespace (in which everything becomes a property of the window object).

Global variables can be declared in functions

When I was starting to learn JavaScript, I read about global and functional scope and wrongly assumed that functions completely protected the variables declared inside.  As it turns out, there’s many ways to create global variables in JavaScript, and none of them throw up red flags or sound off bells and whistles (unfortunately).

Here’s a few ways to create global variables in JavaScript:

// Creating global variables outside of a function
window.global1 = 1;
global2 = 2;
var global3 = 3;

// Created global variables within a function
function test() {
    global4 = 4;
    window.global5 = 5;
};
test();

You can confirm this for yourself by checking the values of the variables with alert().

Good practice: always precede variables with var

What I learned was that it was essentially good practice to always write variables preceded by the var keyword.  For variables declared outside of functions this has no effect – they are still global, but for variables within functions this ensures that they’re kept within their functional scope:

var global = null;
function test() {
    var local = null;
}
test();

Same name, but different variables

And check this out – confusingly, you can create a global variable, then create a variable with the same name that’s functionally-scoped, yet a completely different variable!

var number = 0;

function test() {
    var number = 1;
}
test();

alert(number);  // 0

When you precede a variable with the var keyword, you’re essentially saying you’re creating the variable for the first time.  So when you create “number” inside the function, no error is thrown because the variable is created in the function’s scope.  If you try to create another variable with the name “number” inside the function, you will get an error because it’s already been defined within the scope.

There’s no such thing as magical protective parenthesis

For some reason I was further mistaken into believing that extra parenthesis around an anonymous function magically protected the variables within:

(function() {
    global = null;
    var local = null;
})();

Nope – as you can see, the global variable is still global since it’s not preceded by the var keyword.  All the extra parenthesis do is execute the function immediately.  That’s it.

Shorthand for declaring multiple functionally-scoped variables

The following code ensures each variable is functionally (locally) scoped, even though only the first variable is preceded by the var keyword:

function test() {
    var local1 = null,
        local2 = null;
}
test();

Multiple variable declaration equivalence gives different scope to each variable

Today I learned another way to mistakenly create a global variable.  Trying to be fancy and declare multiple variables to be the same value, I mistakenly created a global variable (again, no bells and whistles went off to warn me, unfortunately):

function test() {
    var local = global = null;
}
test();

This sets both variables to “null” using the shortest code possible, but unfortunately only the variable “local” is preceded by the var keyword, so only that variable will be in its proper functional scope. Variable “global”, on the other hand, is… well… global. (thanks to Crescent Fish)

You learn something new every day…

Update 1

If you want to check your code for “accidental global variables” you can use JSLint or you can even use Firebug (click on the Script tab, then click on “New watch expression…”, then type “window”, which will display all the properties of the window object – these are all global variables!). Thanks to Nick for the Firebug tip.

Update 2

Just another quick note to remind you that after a variable has been initially declared, the scope will not change. Which is why you can redefine variables, but have them keep their scope:

function test() {
    var local = null;
    local = 5;    // still keeps its local/functional scope
}
test();

As you can see above, the variable “local” keeps its local scope, even though it’s redefined to be 5. This is one of the reasons it’s recommended to declare all variables at the start of a function – to make sure the scope gets set correctly.

One final note: var should only be used when declaring a variable for the first time. If you try to use var for the same variable name in the same scope, it will result in an error:

function test() {
    var local = null;
    var local = 5;    // throws an error!
}
test();

Update 3: Graphical representation

Scope in JavaScript

Scope in JavaScript

2 Comments

JavaScript Tidbit: Block scope with “let”

September 15th, 2009

JavaScript has functional scope. Meaning that if you (properly) define variables within functions, those variables remain accessible only inside the function.

Block scope, on the other hand, defines scope within a block of code, usually defined by braces. JavaScript now has block scope as of version 1.7, which means it’s available in these browsers:

  • Firefox 2+

Block scope is enabled in JavaScript with the use of “let”:

let(x=100) {
    alert(x);
};

It also works perfectly well on one line, without the use of braces:

let(x=100) alert(x);

Note that we can define global variables with the same name outside the block scope and the variables won’t interfere with each other:

x = 200;
let(x=100) alert(x);
alert(x);
// result: 100, 200

Note that there’s a slight caveat – not only is this not available in any version of IE, but it also requires a special script type declaration in order to work (at least for Firefox): type=”text/javascript;version=1.7″

References:
JavaScript Versions
Video: Best Practices in Javascript Library Design (John Resig)
New in JavaScript 1.7

Leave a Comment

PHP Tidbit: Dead simple singleton

September 14th, 2009
class Singleton {
    private static $instance;
    public static function getInstance() {
        if(!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c();
        }
        return self::$instance;
    }
}

And the explanation…

class Singleton {
    private static $instance;               // static variable to hold our 1 instance

    public static function getInstance() {  // function to get the 1 instance
        if(!isset(self::$instance)) {       // this will only run once (and instantiate once)
            $c = __CLASS__;                 // get the class (Singleton)
            self::$instance = new $c();     // instantiate the class and store it in our variable
        }
        return self::$instance;             // return the instance
    }

    public static function myFunction() {   // we can get to this through Singleton::getInstance()->myFunction()
        // ...
    }
}