Commets, Varialbles & Special Keywords
Comments
Javascript supports two types of comments. Double-slashes (//) tell javascript to ignore everything to the end of the line. You will see them used most often to describe what is happening on a particular line.
var x=5; // Everything from the // to end of line is ignored(*)
var thingamajig=123.45; // 2 times the price of a whatsit.
"Blockquotes" begin a comment block with a slash-asterisk (/*) and Javascript will ignore everything from the start of the comment block until it encounters an asterisk-slash (*/). Blockquotes are useful for temporally disabling large areas of code, or describing the purpose of a function, or detailing the purpose and providing credits for the script itself.
function whirlymajig(jabberwocky) {
/* Here we take the jabberwocky and insert it in the gire-gimble, taking great care to observe the ipsum lorum! For bor-rath-outgrabe! We really should patent this! */
return (jabberwocky*2);
}
You should note that while comments are useful for maintaining the code, they are a liability itself in Javascript since they will be transmitted along with the code to each and every page load, which can create substantial bandwidth penalties and increase the load time of your page for users.
This doesn't mean you shouldn't comment your code, just that once your code is "finished" you should make a backup copy with the comments, then strip out all the comments in the file which is actually sent to the user.
The result of minimizing your Javascript is a tiny, compact file which is a fraction of the size of the original which will save you bandwidth and provide speedier page-load time for your visitors. However the result is also a very unmaintainable source-code mess which is why you should keep a separate, unminimized (and heavily commented) version of the original file.
(*) Of special consideration, you should note that the browser itself is ALWAYS looking for a </script> tag to mark the end of your Javascript and if it finds that tag, intact, in-one-piece, be it in a string or a comment, it is going to stop processing Javascript at that point and restart-processing HTML.
var x=5;
/* The browser will break the Javascript when it sees this </script> tag.
Everything from tag forward is now being processed as HTML!
This is a bad thing! To avoid this you need to avoid using this
tag anywhere in your Javascript, and if
you must have it, you should break the string out like this... */
document.writeln('</scr'+'ipt>');
VariablesJavascript is not a strongly typed language which means you rarely have to concern yourself with the type of data a variable is storing, only what the variable is storing and in Javascript, variables can store anything, even functions.
var thisIsAString = 'This is a string';
var alsoAString = '25';
var isANumber = 25;
var isEqual = (alsoAString==isANumber); // This is true, they are both 25.
var isEqual = (alsoAString===isANumber); // False one is a number, the other a string.
var concat=alsoAString + isANumber; // concat is now 2525
var addition=isANumber + isANumber; // addition is now 50
var alsoANumber=3.05; // is equal to 3.05 (usually).
var floatError=0.06+0.01; // is equal to 0.06999999999999999
var anExponent=1.23e+3; // is equal to 1230
var hexadecimal = 0xff; // is equal to 255.
var octal = 0377; // is equal to 255.
var isTrue = true; // This is a boolean, it can be true or false.
var isFalse= false; // This is a boolean, it can be true or false
var isArray = [0, 'one', 2, 3, '4', 5]; // This is an array.
var four = isArray[4]; // assign a single array element to a variable.
// in this case four = '4'
var isObject = { 'color': 'blue', // This is a Javascript object
'dog': 'bark',
'array': [0,1,2,3,4,5],
'myfunc': function () { alert('do something!'); }
}
var dog = isObject.dog; // dog now stores the string 'bark';
isObject.myfunc(); // creates an alert box with the value "do something!"
var someFunction = function() {
return "I am a function!";
}
var alsoAFunction = someFunction; //No () so alsoAFunction becomes a function
var result = alsoAFunction(); // alsoAFunction is executed here because ()
// executes the function so result stores the
// return value of the function which is
// "I am a function!"
A variable may not be a Javascript reserved word or begin with a number or any symbol other than $ or _. In Internet explorer you should also avoid variable names with the same name as html elements you have named. For instance…
var someDiv = document.getElementByID('someDiv');
…will cause problems in Internet Explorer because the variable name and the division name are identical.
In recent years a convention has formed around the use of the $ symbol as various libraries like Prototype and JQuery use it to look up a named HTML element. For most purposes if you see $('something') in Javascript you should read that as being
document.getElementById('something').
This is not standard Javascript, in order for $('something') to work, you need to be using a Javascript framework which will define $ as doing something (Like JQuery, Prototype, etc).
The use of a leading underscore (_) is generally useful to indicate a global variable or a variable that has been set outside the current scope.
A final consideration on variables is that functions themselves can be defined like, and act like variables. Once a function has been defined it can be passed to other functions as an argument (A process knows as lambda), or assigned to other variables just like a string, array or any other Javascript object. Generally if you use a function without trailing parenthesis (), the function is treated like a variable and can be passed and assigned. Trailing parenthesis INVOKE the function, executing it and passing back the return value (if any).
Please note that this is a very broad summary overview of Javascript's data types. For more information please see the other articles in this series (listed at the top of the page) which go into exhaustive detail on each Javascript type.
Variable Scope
Variables in Javascript have FUNCTION scope. That is, all variables are global unless they are explicitly defined inside a function and even then child-functions have access to their parent's variables. If a function defines a new variable WITHOUT using the var keyword, that variable will be global in scope.
var global = 'this is global';
function scopeFunction() {
alsoGlobal = 'This is also global!';
var notGlobal = 'This is private to scopeFunction!';
function subFunction() {
alert(notGlobal); // We can still access notGlobal in this child function.
stillGlobal = 'No var keyword so this is global!';
var isPrivate = 'This is private to subFunction!';
}
alert(stillGlobal); // This is an error since we haven't executed subfunction
subFunction(); // execute subfunction
alert(stillGlobal); // This will output 'No var keyword so this is global!'
alert(isPrivate); // This generate an error since isPrivate is private to
// subfunction().
alert(global); // outputs: 'this is global'
}
alert(global); // outputs: 'this is global'
alert(alsoGlobal); // generates an error since we haven't run scopeFunction yet.
scopeFunction();
alert(alsoGlobal); // outputs: 'This is also global!';
alert(notGlobal); // generates an error.
The concept that a variable will continue to exist, and can be referenced after the function that created it has ceased executing is known as CLOSURE. In the above example, stillGlobal, and also Global can be considered closures because they persist after the function that creates them has ceased to operate. You can do some pretty fancy stuff with it later on, but it's not terribly hard to understand once you associate it with creating a global scoped variable inside a function.
Special Keywords
Javascript has a few pre-defined variables with special meaning. NaN -- Not a Number (Generated when an arithmetic operation returns an invalid result). NaN is a weird construct. For one, it is NEVER equal to itself so you can't simply check to see if 3/'dog' == 'NaN'. You must use the construct isNaN(3/dog) to determine if the operation failed. In boolean operations NaN evaluates to false, however 0 also evaluates to false so use isNaN. Since NaN is never equal to itself you can use this simple trick as well:
if (result != result) { alert('Not a Number!'); }
Infinity is a keyword which is returned when an arithmetic operation overflows Javascript's precision which is in the order of 300 digits. You can find the exact minimum and maximum range for your Javascript implementation using Number.MAX_VALUE and Number.MIN_VALUE.
null is a reserved word that means "empty".
When used in boolean operation it evaluates to false.
Javascript supports true and false as boolean values.
If a variable hasn't been declared or assigned yet (an argument to a function which never received a value, an object property that hasn't been assigned a value) then that variable will be given a special undefined value. In boolean operations undefined evaluates as false. Here's an example…
function doAlert(sayThis) {
if (sayThis===undefined) { // Check to see if sayThis was passed.
sayThis='default value'; // It wasn't so give it a default value
} // End check
alert(sayThis); // Toss up the alert.
}
Comments
Post a Comment