Web Development Tips

My Twitter account, WebDevTips, has been reactivated. Follow @webDevTips to get (almost) daily Web Development tips in your timeline.

Make Twitter DMs appear as if read in all browsers

Edited July 5, 2015

While the DMs no longer appear unread forever (thanks for the fix, Twitter), the ads are still annoying. Simply drag the Add Killer link to your tool bar and click when necessary.

————————— End Edit —————————

I use Twitter.com to access my tweets. I do so from several different computers and several different browsers on each of those computers. Since Direct Messages read/unread status is stored in local storage, I have to ‘read’ my DMs in every browser on every computer to make them appear read in each of those browsers. I hate that.

What I hate even more is that I have to click on my account drop down, then on direct messages link, then I have to individually open each DM thread to make them appear read, and back out of it before clearing the next.

This was driving me crazy. So, I created a little bookmarklet. I simply added the bookmarklet to each of my browsers. Now, whenever I see that little blue glow I simply click on the little bookmarklet, and the blue glow disappears until I actually get a new DM.

You can get the bookmarklet from my Github

This bookmarklet will mark all of you Twitter direct messages as read simply by deleting the entry in local storage.

The Code:

//Get the URL
var urlistwitter=window.location.href.split('/')[2].split('.'); 

// Check to see if the domain is twitter
if(urlistwitter[urlistwitter.length-2]==='twitter') {

   // remove the local storage item of unread DM references

// remove the icon that makes them appear unread
document.querySelector('#user-dropdown-toggle .nav-new').classList.remove('nav-new');

Drag this link to your toolbar. When you need to, click it when your Twitter window has focus to remove the localStorage entry and that annoying blue ‘unread’ icon:

Mark DMs as Read

details and summary polyfill

var summaryClick = function(elem){
  if (!('open' in document.createElement('details'))){
    var deetails = elem.parentNode;
    } else {
     deetails.setAttribute('open', 'open')

add the summaryClick to your <summary> click event listeners

And then in my CSS I put something similar to:

details:not([open]) {
   height: 2em; 
   overflow: hidden;
details[open]  {
   height: auto;
summary::before {
   content: "▶ ";

Only browsers that understand the JS used will understand the selectors used. So, this isn’t fool proof, but it’s nice, quick and dirty.

Placeholder Attribute Support in ALL browsers

Included along with jQuery, the following code allows you to include the HTML5 placeholder attribute work in older browsers. The idea is to find all the input elements that have a placeholder attribute that the browser is ignoring since it doesn’t understand. Check to see if the input value is empty. If it is empty, include the placeholder value temporarily as the value (preferably making it look like a placeholder). If the user focuses on the input, clear the placeholder value, which is the default behavior in browsers that support the placeholder value. When the user exits the input box, the script checks to see if there is a value. If not, reinstate the value of the placeholder.

The second script is for when the user submits the form: we want to make sure that the form is not alwasy submitting the placeholder value. The main issue with this function is that the user cannot actually enter data that matches the placeholder, so, if you’re going to use this function, make sure that the placeholder value is not one that a user would intentionally submit. For example, use ‘first name’ and ‘last name’ for names, rather than ‘john’ and ‘doe’. Use ‘phone number’ or ‘415.555.1212’ for phone numbers, and other implausible values, etc.

  //make HTML5 placeholders work in non supportive browsers
     // $(this).addClass('hasplaceholder');
        if($(this).val()==$(this).attr("placeholder")) $(this).val("");
       // $(this).removeClass('hasplaceholder');
	  // $(this).addClass('hasplaceholder');

		if($(this).attr("placeholder") == $(this).val()) {$(this).val('');}

Here are the lines explained:

Finds and iterates thru each input with a placeholder attribute:

Checks to see if the value is empty

Commented out, you can add this line to add a class to the inputs that currently don’t have a value, so you can stylize them to look like placeholders (in other words, change the color to light grey using CSS):
// $(this).addClass('hasplaceholder');

Find the value of the placeholder attribute and sets it as the value of the value attribute

Create an onFocus event handler

When focused, checks to see if the current value matches the value of the placeholder. If so, it clears the placholder
if($(this).val()==$(this).attr("placeholder")) $(this).val("");

If you included the class to stylize the placeholder look and feel, remove it when the user is focusing on this input
// $(this).removeClass('hasplaceholder');

Close out the onFocus event handler

Create an onBlur event handler for when the user exits the input box

Check to see if the input box is empty (the user has NOT entered any data)

If the value is empty, we’re going to not just put the placeholder in, we should also include a class to be able to stylize it as a placeholder would look:
// $(this).addClass('hasplaceholder');

Put the value of the placeholder in the value — as we did on page load above.

Close out all the set up stuff

We also need to ensure that the element has a legitimate value when the form is sumbitted:

We create an onSubmit event handler:

We go thru all the inputs that have the placeholder attribute:

If the current value matches the placeholder value, we clear it before sumbitting:
if($(this).attr("placeholder") == $(this).val()) {$(this).val('');}

We close out the function:

Note that if the element is ‘required’, the submit function would be different and we would test to see if the browser supports the placeholder attribute before doing any of this, but i am just providing a small snippet to show how easy (and possible) it is to make older browsers support HTML5 form features.

Introduction to GeoLocation

Geolocation allows users to share their physical location with your application if they choose to. Especially useful in social networking, geo tagging, and mapping, but applicable to any type of application, geolocation enables developers to enhance the user experience, making content, social graphs and advertisements more relevant to the location of the user.

The browser will request the permission of the user before accessing geolocation information. Geolocation is an opt in feature: when your web application requests Geolocation information, mobile browsers create an alert, and the desktop browser asks via banner that pops up at the top of the browser window asking permission to access location information. The user can grant permission or deny it, and optionally remember the choice on that site. If permission is granted, the Geolocation information will be accessible to your scripts and any third party scripts included in the page, letting your application determine the location of the user, and maintain location as the user moves around.

Location information is approximate, not exact, being garnered from IP addresses, cell towers, Wi-Fi networks, GPS, or even getting the information through manual data entry by the user.  The geolocation API does not care how the client determines location as long as the data is received in a staddard way. Because determining location can take time, the geolocation API is asynchronous.

To determing browser support for geolocation use:

if(navigator.geolocation) {
   //geolocation is supported

The geolocation object provides for the getCurrentPosition() method that asynchronously returns the user’s current location.

if(navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(handle_success, handle_errors);

If successful, the callback function will return the current position with the coords property contains the more common latitude and longitude properties as well as the altitude, accuracy, altitudeAccuracy, heading and speed properties. The following script will return the alert the current latitude and longitude, and is available in the chapter files:

if(navigator.geolocation) {
function handle_success(position){ 
 alert('Latitude: ' + position.coords.latitude + '\n Longitude: ' + position.coords.latitude); 
 function handle_errors(err) { 
   case err.PERMISSION_DENIED: alert("User refused to share geolocation data"); 
   case err.POSITION_UNAVAILABLE: alert("Current position is unavailable"); 
   case err.TIMEOUT: alert("Timed out"); 
   default: alert("Unknown error"); 



The draft specification can be found at http://dev.w3.org/geo/api/spec-source.html#geolocation_interface. Geolocation is support in Firefox, Webkit and Opera, but not IE. It is anticipated that it will be supported in IE9.

HTML5: Introduction to <canvas>

Canvas: Tutorial of basic canvas functionality, canvas properties and methods

The HTML5 Canvas specification is a JavaScript API for coding drawings. The canvas API allows the definition of a canvas context object as the <canvas> element on your HTML page inside which we can draw.

We can draw in both 2D and 3D (WebGL) context. 2D is available in all the modern Web browsers, IE9, and via excanvas.js in current versions of IE, and will be more thoroughly introduced below. 3D is still nascent, with only experimental implementations.

2D context provides a simple yet powerful API for performing quick drawing operation, on a 2D bitmap surface. There is no file format, and you can only draw using script. You do not have any DOM nodes for the shapes you draw — you’re drawing pixels, not vectors. OK, not true. You are drawing vectors, but once drawn, only the pixels are remembered.

Your first <canvas>

Being a very basic introduction to canvas, we are only going to cover basic shapes and lines. If you are unfamiliar with JavaScript, the syntax may at first seem a bit confusing. If you are familiar, it should make sense.

Step 1 is adding the <canvas> element to your document. In terms of HTML, the only step involved in adding a canvas to your document is adding the <canvas> element to your document:

<canvas id="flag" width="320" height="220">
You don't support Canvas. If you did, you would see a flag

That is it for the HTML part of it. . We could simply have written <canvas></canvas>. However, you should include an id for ease of JavaScript targeting, but you could also target via placement within the DOM. You can also define the width and height of the canvas, though you can define that in the CSS as well. We’ve also included alternative content for users that don’t support or otherwise can’t see your <canvas> content

With that, we’ve created your blank drawing board, or canvas. Everything else takes place in our JavaScript files. Step 2 is drawing on our canvas. From now on, everything is in javascript. We target the canvas node with getElementById(‘flag’) or getElementsByTagName(‘canvas’)[0], initialize a 2D context and start drawing using 2D context API commands. We can draw the Japanese flag:

var el= document.getElementById("flag");

if (el && el.getContext) {
var context = el.getContext('2d');
context.fillStyle = "#ffffff";
context.strokeStyle = "#CCCCCC";
context.lineWidth = 1;
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
context.strokeRect(10, 10, 300, 200);
context.fillRect(10, 10, 300, 200);
context.fillStyle = "#d60818";
context.arc(160, 107, 60, 0, Math.PI*2, false);


The first line finds your <canvas> element by matching the element’s id attribute. Before creating the 2D context, we check to make sure that the canvas element has been found AND that the browser supports canvas by checking for the existence of the getContext method.

We have to then create a reference to a context using the getContext(contextId) method of the canvas element –‘2d’ and ‘3d’ are the contextId value choices. If context creation is successful, we are finally free to draw in our canvas.

Before drawing a shape, we must define the look and feel of the shape we want to draw by setting properties on the context object. We define the look of the border (stroke and linewidth) properties and the shadow of our first rectangle, which we draw with the strokeRect() method. We pass the same parameters as our SVG example: (10, 10, 300, 200). The four values are the x-offset, the y-offset, width and height respectively. Once the script executes a command, the script forgets about what it has done, and moves onto the next line of code. Unlike our SVG example, the rectangle we’ve drawn on our canvas is not part of the DOM.

When we draw our second rectangle using the fillRect method, which paints rectangles using the previously set fillStyle property, we need to pass the coordinates again as the DOM does not remember our first rectangle, though it can access pixel information.

Both rectangle method calls have the same parameters — 10, 10, 300, 200 — we’ve drawn our fill rectangle directly on top of our dropshadow rectangle. We could have created an object with those coordinates and passed it to both methods, but we can’t tell the canvas to access the first rectangle’s coordinates and copy to the second after the method call

As mentioned above, once you paint onto the canvas, the DOM has no recollection of what you’ve painted. Yes, the JavaScript remembers the values of the properties you’ve set, but the pixels that are places on the canvas are just pixels of color. As we start the process of drawing the disc or sun on our flag, the DOM has no recollection of which pixels were painted with which colors, but it does remember some properties we set, like our shadowColor. As we don’t want a shadow on the red circle, we can set the shadowColor to transparent.

Next we define our circle. We are not actually drawing the circle yet. context . arc(x-offset of center, y-offset of center, radius, startAngle, endAngle, anticlockwise) adds points to an arced path creating a virtual circumference of a circle described by the arguments, starting at the given start angle, in our case 0, which is on the right horizon, and ending at the given end angle, going in the given direction, which in our case is clockwise. Had our endAngle been less than 2Π, our circle would have been flattened: the start and end points connected by a straight line. Π would have created a half circle. We also re-define the fill color, from white to red. We then paint the circle we created using the fill() method that fills the described arc in the fillStyle color.

We haven’t even touched the surface of what <canvas> can do. http://ie.microsoft.com/testdrive/Graphics/CanvasPad/Default.html is a fun page to learn simple shapes, colors, shadows, text, images, transformation, animation and mouse movement with <canvas>.

Canvas functions and properties


Set the fillStyle


Set the strokeStyle


Line widths


Line join styles

   context.lineJoin="bevel || round || miter"

Line end styles

   context.lineCap="butt || round || square"


Draw a rectangle

   context.strokeRect(left, top, width, height)

Fill a rectangle

   context.fillRect(left, top, width, height)

Erase a rectangle

   context.clearRect(left, top, width, height)


Begin a path


Complete a path


Move the pen to a location

   context.moveTo(horizontal, vertical)

Draw a straight line from current point to a new location

   context.lineTo(horizontal, vertical)

Stroke the current path


Fill the current path



Shadow color


Shadow horizontal offset


Shadow vertical offset


Shadow blur


Canvas versus SVG

HTML5 Canvas and SVG may seem similar, in that they are both web technologies that allow you to create rich graphics inside the browser, but they are fundamentally different. In SVG, you ‘draw’ with XML. For canvas, you draw with JavaScript. Canvas is the painting of pixels onto a canvas, once painted, each pixel is forgotten. SVG, on the other hand, creates DOM nodes, accessible until deleted or until navigation away from the page. They both have their advantages and disadvantages.

SVG is resolution independent, making SVG an excellent choice for user interfaces of all sizes as it allows scaling for all screen resolutions. SVG is an XML file format enabling easy accessibility. SVG can be animated using a declarative syntax, or via JavaScript. Each element becomes part of and is accessible via the SVG DOM API in JavaScript. However, anything that accesses the DOM repeatedly slows the page down.

Canvas is all drawn in pixels. Zooming can lead to pixilation. Canvas is inherently less accsessible: accessibility is limited mainly to including fallback content should canvas not render. Interactivity requires redrawing of each pixel. There are no DOM nodes for anything you draw. There’s no animation API, instead timers are generally used for updating the canvas at quick intervals. Canvas gives you a surface to draw onto with the API of the context you choose. Canvas, however, is very well suited for editing of images, generating raster graphics such as for games or fractals, and operations requiring pixel-level manipulation. Canvas can also be exported to gif or jpeg.


SessionStorage is an alternative to session cookies, but more powerful. The HTML5 storage API defines persistent data storage of key-value pair data in Web clients. The HTML5 Storage API improves upon HTTP session and local cookies that you are likely to be already familiar with. While cookies are limited to 4KB, the new standard allows for more space. The size depends on the browser, but is generally in the MB rather that KB range. HTML5 provides for two types of storage: persistant localStorage, and unique per open window/tab sessionStorage. Today we’ll focus on sessionStorage.


Session storage is accessible to any page from the same site opened in that window. If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.

Cookies are sent to the server with every HTTP request. Session data, however, isn’t sent automatically, reducing the size of every request. The developer determines which key-value pairs need to be sent with each request.

Most shopping carts us use cookie-based authentication to remember the users browser session. Without sessionStorage, if two users want to shop on the same site from two windows of the same browser, it is not possible because cookies are tied to the browser session. With session storage, this can be done as the session storage is tied to the current window. As each window maintains its own session information, using sessionStorage is perceived as if each window is a different user accessing the shopping cart from different systems.

Okay that example explains how session storage is different from cookies… but is there not a slightly more practical example to talk about? I’m just thinking what storefront is ever going to think of what you just described as a desirable scenario that they’ll want to support (or care about)?

Perhaps something like the ability to test websites by logging in as different users as the same time from different tabs, or? just something that is a bit more practical would help I think…

sessionStorage should be used to store temporary data related to a single browser window as it ceases to exist after the window is closed.

The sessionStorage object has five methods and one property:

  • setItem(key, value) – sets the value for the given key. For example, define the session variable with:
    sessionStorage.setItem('keyname', 'data value')
  • getItem(key) - retrieves the value for the given key. Returns null if the key does not exist.
  • removeItem(key) - removes the key and its associated value. Unset the value with:
  • key(position) – returns the key for the value in the given numeric position.
  • clear() – removes all key-value pairs. Clear all the key value pairs with:
  • length – The length property indicates how many key-value pairs are currently stored in sessionStorage.

Using sessionStorage is extremely easy. It is like defining and using a regular variable, except that it needs to be prefixed with sessionStorage.

For more information on sessionStorage, see http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/


Up until now, users of web applications have only been able to use the applications while connected to the Internet. When offline, web based e-mail, calendars and other online tools have been unavailable, and, for the most part, continue to be. While offline, users may still access some portions of sites they have visited by accessing what is in the local cache, but that is limited and inconvenient. If a user gets bumped offline in the middle of a process — writing an email, filling a form — hitting submit can lead to a loss of all the data entered. The HTML 5 specification provides a few solutions including a SQL-based database API for storing data locally, and an offline application HTTP cache for ensuring applications are available even when the user is offline. HTML 5 contains several features that address the challenge of building Web applications that don’t lose all functionality while offline, including SQL, offline application caching APIs as well as online/offline events, status, and the localStorage API.

In this section we are focusing on the Application Cache.

A book could be written about each of these topics. In this series of articles, we’re are introduced to each of the HTML5 API and related modules (for example, GeoLocation is not in the HTML5 specifications, but is often thought to be). This series will provide a brief introduction to each topic, linking to the specifications and other relevant articles. It’s important to know about what is going to be in HTML5 so that when these features are needed, and when they are available and supported on your target devices, you’ll know about these features.

Application Cache

To access a webpage offline, we’ve been able to click on the ‘save’ menu item in our browser to save the html file and associated media for a while now, but this method of saving web pages only works for static content. With the ubiquity of web-based applications, it is more important now than ever that web applications be accessible when the user is offline: whether the user is offline for the duration of a 5 hour flight, or if the user is just temporarily offline as 3G connectivity is lost while driving… um, I mean, riding as a passenger. While browsers have been able to cache components of a website, HTML5 addresses some of the difficulties of being offline with the ApplicationCache API.

Using the cache interface gives your web application the advantages of 1) offline browsing, 2) faster reloads and 3) reduced server load. With Application Cache offline browsing, you entire site (within limits) can be navigable even when a user is offline. By caching resources, the resources are local, loading much faster, and they’re retrieved only when altered, which reduces the server load. AppCache enables the local storing of up to 5MB (or limits you to 5MB, depending on your perspective) per website.

The Application Cache (or AppCache) enables you to specify which files should be cached and made available offline, enabling your website to work correctly, including page reload, when your user is not online.

For AppCache to work, you include the manifest attribute in the opening <html> tag. The value of which is the URL of a text file listing which resources should be cached. In your HTML file, include manifest="URL_of_manifest".

<!doctype HTML>
<html manifest="resourcelist.manifest">
<meta charset="utf-8" />

With the inclusion of the manifest attribute linking to a valid manifest file, when a user downloads this page, the browser will cache the files listed in the manifest file, the manifest file itself and the current document and make them available even when the user is offline.

When the page is visited, the browser will try to update the cache if the manifest file has changed. It fetches the manifest and, if the manifest has changed since the page was last visited, the browser re-downloads all the assets and re-caches them.

The cache manifest file

The .manifest file is a text file that lists the resources the browser should cache. The file must start with the following string: CACHE MANIFEST. The required string is then followed by a list of files to be cached, and optional comments and section headers.

To create a comment, include a # as the first character of the line and the remainder of the line will be ignored. Section headers change the current section. There are three possible section headers, CACHE:, FALLBACK: and NETWORK:. The files following the CACHE: header are explicit. If no header is defined, or if files are listed above the headers, those files are explicit. FALLBACK: switches to the fallback section — if the first file is not available, the second file listed on the line will be served. While secure (https://) files may be cached, they have to be from the same origin as the manifest. The NETWORK: heading leads the online white list section – it isn’t cached, and references to this file will bypass the cache and access the file online.

The manifest file is also permanently stored into the browser cache, only to be overwritten if there is an edit made to the file. While the browser will not read the comment, the .manifest file needs to be served with the mime-type "text/cache-manifest". You may need to add a custom file type to your web server or .htaccess configuration if you don’t have access to the server.

A .manifest file lists the files that the browser should cache. The file may look something like this:


#files that explicitly cached

#Resources requiring connectivity

The Application Cache API adds an element to HTML5. The <event-source> element is a new feature in HTML 5 that allows servers to continuously stream updates. When used with the appCache, its src attribute takes as its value a NETWORK: file. The NETWORK: files will never be cached, so that any attempt to access that file will bypass the cache. The <event-source> tag defines a source for events sent by a server. The src attribute of the <event-source> element takes as it’s value the white-listed NETWORK: file to allow for continuous upsteaming from the server.

You’ll note that there is a version number in a comment on the second line. While the browser will generally ignore the comment, it will note if there are changes to the file. Changing the commented version number has become the standard way of informing the browser that the manifest file should be considered updated.

Updating the cache

Once an application is offline it remains cached until the user clears their browser’s data storage for your site, the .manifest file is modified or the app cache is programmatically updated.

If you update a file listed in the manifest, this does not inform the browser that the assets must be re-cached. The reason we added the commented version number was to inform the browser that the assets must be re-cached by altering the .manifest file itself.

If the manifest file or a resource specified in it fails to download, the entire cache update process fails and the browser will keep using the old application cache.

JavaScript Variable Scope

There are two variable scopes in JavaScript: local and global. Local variables exist only inside the function in which they were declared. Local scope means a variable can only be referenced from within that function in which it was declared. Global variables, on the other hand, once declared, exist throughout the script and their values can be accessed (and changed) from within any function or outside of a function. In other words, global scope means a variable can be referenced from anywhere within your site’s javascript.

There is a third type of scope called "static" or "closure". "Closures" are variables that are local to a function, but keep their values between function calls. Closures are an advanced javascript topic and will not be discussed in this article.

Let’s show 5 variables being declared, and discuss their scope

1.  <script type="text/javascript">
3.  var outsideFunction1 = "hello"; 
4.  outsideFunction2 = 42; 
6.  function myFunction(myParameter){
7.      var insideFunction1 = new Array();
8.      insideFunction2 = false;
9.  }
11. </script>

Listing 1: Example of local and global variable declaration

The first variable is on line 3: outsideFunction1. Even though this variable is declared with the var keyword, it is declared outside of any function, and therefore has global scope.

The second variable is on line 4: outsideFunction2. This variable is also declared outside of any function, and therefore has global scope.

The third variable is on line 6: myParameter. Function parameters always have local scope. Even if there were a global variable called myParameter, that global variable will maintain its value even if the value of myParameter was changed within the function.

The fourth variable is on line 7: insideFunction1. Because this variable is declared within a function with the var keyword, it also only has local scope. Similar to parameter variables, even if there were a global variable called insideFunction1, that global variable would maintain its value even if the value of insideFunction1 were changed within the function.

The fifth variable is on line 8: insideFunction2. This is really the reason that this article is needed: this is a global variable declared within a function, which is one of the most common causes of logic errors. Because the var keyword has been omitted, the insideFunction2 variable is global.

Local Variables

Variables initialized inside a function using the var keyword will have a local scope. If you initialize a variable inside a function without the var keyword, your variable will have a global scope. Parameters are local variables, as if the keyword var was included before the parameter. Local variables, including a parameters, can have the same name as a global variable.

var myName = "estelle";  // global
function alertThisName(myName){ // local
		alert(myName); // alerts "jonathan"
alert(myName); // alerts "estelle";

Listing 2: The variable myName is declared both globally outside of the function, and locally as the function parameter. Variables declared as function parameters have local scope. The myName variable on the first line is a global variable. The variable myName declared as a parameter of the function is a local variable only visible within the alertThisName function.

In this case, declaring a local variable with the same name as a global variable masks the global variable: all global variables in your script are accessible to this function EXCEPT the global myName variable.*

Note: In browsers, global variables that are masked by a function’s local variable with the same variable name are still accessible to the function by accessing the global variable thru it’s parent. In Listing 2, if you are in a browser, you could access the global myName variable from within the alertThisName function by using window.myName or top.myName.

var myCount = 7;  // global
function doSomeMath(){ // 
		var myCount = 7 * 7;
		alert(myCount); // alerts "49"
alert(myCount); // alerts "7";

Listing 3: In this example, the global and local variables both have the same name. Since the variable within the function was declared using the var keyword, the variable has local scope. Manipulating the value of the local value has no impact on the value of the global variable declared in the first line.
Once we exit the function, the local variable myCount no longer exists and recognition of the global variable’s existence is reinstated.

Similar to listing 2, in this case the local declaration of the myCount variable makes the global myCount variable inaccessible to this function. The function can access all global variables EXCEPT for the global myCount variable, unless you access the variable as noted in the tip above.

var myCount = 7;  // global
function doSomeMath(){ 
		myCount = 7 * 7;
		alert(myCount); // alerts "49"
alert(myCount); // alerts "49";

Listing 4: Since the variable within the function was declared WITHOUT using the var keyword, the variable has GLOBAL scope. The global variable declared in the first line and the variable used in the function both have the same name and are, indeed, the same global variable. In this example, manipulating the value of the global value within the function changed the value of the variable throughout the program.

function doSomeMath(){  
		myCount = 7 * 7;
		alert(myCount); // alerts "49"
alert(myCount); // throws an error: myCount is undefined

Listing 5: While the variable in the doSomeMath function would be a global variable, as the variable is declared in the function WITHOUT using the var keyword. Since the function is never called, the variable is never declared. Accessing the variable that doesn’t exist in the last line throws an error.

Rules to remember:

  1. Local variables inside a function can only be referenced from within the function in which the local variable was declared.
  2. All global variables can be referenced from within any function.
  3. All global variables can be referenced from outside any function.
  4. No local variables, declared with use of the var keyword, can be referenced from outside the function in which they were declared