Scope - Your Best Friend (when it's not your worst enemy!)

by Philippe Xantus

HTML

<b>Scope - Your Best Friend (when it's not your worst enemy!)</b>
<div>
    <p>Common variable names (such as <code>name</code>) in the global scope are "an accident waiting to happen".  </p>
    <p>Output will appear below:</p>
</div>
<div id="output"></div>

CSS

#output{
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

// What's wrong with this?
// The 'name' variable in the global scope collides with 
// JSFiddle's use of the window.name property. Click 'Run'
//  a second time on this page and see JSfiddle trying to 
//  make a frame called "Larry"
var index = 4, i = 6;
var name = "Larry";
function add(n, p){
	return n + p;
}
logMessage(add(index, i) + name);


// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
    if (!id) {
        id = "output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}