Post by Schubaltz on Mar 24, 2008 14:03:40 GMT -5
I've got a more up-to-date "version," but I can't be bothered to convert all the HTML to UBBC. I'm getting closer still to finishing the whole tutorial. You can be sure i'll post it here first.
Introduction
JavaScript, introduced in December of '95, is a client-side, object-based programming language intended for the manipulation of HTML and XML documents. Now, JavaScript isn't a full-blown object-oriented language, but it is indeed object-based. So despite any rumors you may have heard, there's alot more to this language than pop-ups and corny roll-over effects. Let's say, for example, you work at the local book store and need to compile and organize a list of books going in and out. You could create an object that recorded this data for you and allowed you to access it and check for recent changes instantly. And ever wondered how those professional websites create those accelerating/decelerating scrollbars? Well, they do it with flash, but it can be done with JavaScript. So, still not convinced that JavaScript is worth learning? Or maybe it's just been too complex a concept in the past? Well, if you said yes to the first question, you're a lost cause. As for the latter, i've done my best to cover this information in common-speak, so don't worry, i'm not going to drown you in history lessons.
Now that we've gotten the boring stuff out of the way, we can focus a little more on JavaScript's capabilities. So, what exactly can this "wonder-language" do?
The above list, of course, doesn't cover everything. But I figure it should be enough to get your mind buzzing. Now then, ready to start coding?
Getting Started
JavaScript can be inserted directly into an HTML document via the HTMLScriptElement.
Not a complicated start, right? We'll be compiling our script within the opening and closing tags of this element. The type attribute is simply there to ensure that the browser knows what type of data it's dealing with.
A key thing to remember when inserting your script, is that JavaScript can only manipulate what of the document has already loaded. And when you think about it, that makes perfect sense (you can't change what doesn't yet exist). But before we continue, you should be aware of some of JavaScript's flaws. For one, as you can well imagine, JavaScript did not come into being at the same time as the internet, so earlier browsers aren't equiped to read and interpret it---resulting in lines upon lines of script appearing as plain text on the page. Another primary flaw is that, as a safety precaution, users may enable/disable JavaScript at will. In short, this means you can't expect everyone to see the outcome you intended.
So, is JavaScript not all it's cracked up to be? Certainly not. In fact, these flaws can easily be trumped (starting with the script block).
All browsers support HTML comments, so browsers that don't recognize javascript will completely ignore the text inside. However, browsers that do support JavaScript will take note of the script type and execute the code. And what of flaw number 2? Simple. The HTMLNoScriptElement.
I doubt this needs any explanation, but hell, I love to babble. The code inside the noscript tags will execute when JavaScript is disabled. These tags are most commonly used to output messages such as, "For a better browsing experience, please enable JavaScript," but if need be, you can execute a couple hundred lines of CSS and HTML.
Debugging
I'll be honest with you, coding in JavaScript can be a messy job, and you're bound for enumerous errors. But luckily, being a client-side language, JavaScript is interpreted by the browser and does not require a compiler. This means that when confronted with an error, the browser will simply halt execution of the script and continue on through the rest of the source code.
Seems brief, but we'll be coming back to this later.
My First JavaScript
As with most any programming language, JavaScript embraces comments. These comments won't execute as code and simply allow us to guide ourselves (or others) through a script. In JavaScript, there are two types of comments, one-line and multiple-line. One-line comments are intiated by two preceding forward slashes and are terminated when the line is broken. Multiple-line comments are a bit more complex. They are initiated with a forward slash preceded by an asterick and terminated in opposite (don't worry, this is why we have examples).
The browser will recognize these lines as comments and decidedly ignore them. But...what if we used special characters and declarations in our comments? Would the browser then interpret them as code?
The answer is no. Take a look at the script above. You'd think the line would create a comment, terminate it, and create a new one. But in fact, "// Hello there!" is ignored by the browser entirely. We could write one thousand forward slashes preceding one another and the browser would recognize it all as a single comment and move along through the script. To sum it up, until you terminate them, you can put anything you wish in your comments.
And now that we're in to comments, I think it need be known that the closing "-->" won't always parse correctly (some times JavaScript-enabled browser will attempt to read the line as script). We can prevent this from happening by writing "-->" as a one-line comment.
Alright, so far we've learned what JavaScript is, how to declare it, what it can do, it's pros and cons, and how to write comments within it. If you need a break, go ahead and take it. This tutorial isn't going anywhere.
Up next we'll be printing text onto a document.
As I said before, JavaScript is object-based. Meaning it works off of an entire library of actions constructed upon one another. Take a look at the above code. An object is simply a "thing" with it's own unique characteristics and actions. Take for example the average human-being. We have characteristics (hair, eyes, skin-tone), and we have actions that we can perform (walk, talk, jump, eat). This is the foundation of an object-based language. Look again at the above script. document is our object and write() is one of the many actions it can perform. An object's properties and actions are made accessable through JavaScript's dot-structure.
Confusing stuff? Yeah, it can be. But don't worry about it, you're just getting started. We'll come back to it in another tutorial.
Now then, seeing as I have yet to explain what the above line of code is doing...document addresses the document that the JavaScript is currently in and write() states to print the text in parenthesis onto it. Keep in mind that JavaScript is case-sensitive, so to code Document.write("Hello World") would trip an error.
Datatypes
When you go to open a file on your computer, you'll note that near the bottom of the window is a drop-down list titled "Files of type." These types can range anywhere from txt to wav to jpg. These little extensions help the computer identify and sort different types of data. Were it not for them, you could end up opening picture files in Notepad.
The same holds true for JavaScript (and most anything computer-related). As programming languages become more and more extensive, there becomes a greater need for data organization.
JavaScript has 5 primitive datatypes---the building blocks upon which larger, more complex types of data (composite datatypes) are constructed.
Of the 5, i'll take the liberty of explaining strings, numbers, and booleans.
Recall our document.write() script. Then consider this, in that script, we printed Hello World to the page. But what if we wanted to print document to the page? Seeing as document holds the place of an object in JavaScript, that's not really possible, is it? But surely there has to be a way. Surely there's a way to get the browser to differentiate between special texts and plain texts.
Note that Hello World is in quotations. Strings, our first type of data, inform the browser that certain texts should not be parsed. This means that we can in fact print document to the page.
Strings are initiated and terminated by either single or double quotes. The trick comes when you want to place quotes in your string.
Depending on the type of quote you use to initiate the string, the other can be used inside it. Starting with a double quote, we can place single quotes in the string, and starting with a single, double in the string. Now eventually, you'll want to write both inside.
This is when backslash escaping comes into play. Kind of like strings, it prevents single characters from being parsed. Above, we needed to use both types of quotes in our string. Since we initiated the string with a double quote, we couldn't use a double quote in the string. By placing a backslash before those doubles, their special properties are eliminated and they don't terminate the string. Here's what would happen if we didn't do this:
The browser will initiate the string at the first quote and terminate it at the second ("I'm reading "). Then, since there are no quotations around it, it'll try and execute The Three Little Pigs as script. Thus the error, and why we must backslash escape.
Strings are a very important part of communication. Both with the user and the browser. This is why so many methods (actions to be performed) are offered to act on strings, ranging from grabbing, to replacing, to matching chains of characters within a string. Later in this tutorial, we'll be doing some cool things with them like validating forms and encrypting passwords. But to do so, will require knowledge of our next two datatypes. So let's get going!
Numbers, where would we be without them? Well, certainly not here, browsing the web. Hell, there wouldn't even be computers (calculators or otherwise)! And how would the world survive without high school calculus? Alright, maybe that's too much. But you can't deny that math is all around us. We judge time by counting orbital rotations, we judge lengths based on metrics, we judge maturity based on age, it's all about amounts. And of course, JavaScript wouldn't be complete if it didn't support something so fundamental.
Right, so we wrote a number to the page. Big deal, eh? Well, it gets better (really). Now that we're into numbers, I get to talk about operators!
JavaScript offers a wide variety of operators that allow you to assign values, compare operands, concatenate strings, perform arithmetic, etc. And seeing as we're only into numbers, you'll start learning from arithmetic.
Pretty straight-forward. Only ones I should have to explain are modulus and grouping. Modulus is simply the remainder you get when dividing two operands. 9 % 4 for example, returns 1 because 4 can only go into 9 twice (yielding 8; 9 - 8 = 1). Grouping in JavaScript works just the same as it would in basic math. JavaScript follows the order of PEMDAS, so grouping is often necessary when you want to add before multiplying, etc.
Perform the operations and what do we get? 62. But the fun doesn't stop there. JavaScript also supports floating numbers (e.g. 6.21) and negatives.
Nothing special here. Except of course, the last operation. Can we really subtract a number from a string? The answer is yes. You can perform any of the above operations so long as that string only contains numbers. If we were to say, subtract -3 from "8a", our result would be the datatype NaN (not a number). The only real catch to performing arithmetic on strings is concatenation.
String concatenation occurs when a + is performed between two operands and one of them is a string. It's a simple operation that combines the characters from both operands into one string. Just another reason to be wary of what types of data you're dealing with.
I'll wrap this up by introducing comparison operators, and in turn, booleans (yay).
The first four shouldn't take much explaining. "abc" < "def" should be the only mind-boggler. So, not only can we add strings together, but we can compare them? Sure, why not? What you're seeing ("abc" < "def") is called lexicographical string comparison. This basically checks if the strings are in order by character (...6789abcdef...), and seeing as the first character in our first operand "abc" is "a", and it does indeed come before the first character in our second operand "def" ("d"), "abc" is less than "def". If both operands had started with the same character, the comparison would have been between the next two characters and so on.
As for the last four, they take a bit more thinking. == checks if both operands have the same value (e.g. 9 and "9"), != checks if both don't have the same value (e.g. 8 != 7). === and !==, however, check for both value and type. This means that while 9 == "9" is true, 9 === "9" is not because one is a number and one is a string.
Each of the previous comparison examples return a boolean datatype. Booleans are logical entities, either true or false.
Nothing much to say here. Any comparison operation that isn't true is boolean false. And empty strings, 0s, undefineds, nulls, and NaNs are all boolean false. Soon enough, we'll be performing tasks based on these principles. In fact, it just may be that we'll do more work with booleans than strings and numbers combined! And while we're on the subject of logical entities, it seems only right to introduce logical operators!
Alright, we've got arithmetic, comparison, and logical operators all in one boat here, so pay attention. Our first operation, !(6 / 2 == 4), says to return boolean true of 6 / 2 == 4 is boolean false (another example, !false returns true). Our second operation, 2 + 4 == 6 && 2 + 4 < 7, returns boolean true if 2 + 4 equals 6 and 2 + 4 is less than 7. Our last operation is probably the trickiest. Unlike the other two, it doesn't return a boolean. Instead, it sends back one of its two operands. Here's the breakdown: If the first operand is boolean true, it is returned. If the first operand is boolean false, however, the second operand is returned instead. As trivial as it seems, this is actually pretty nifty. And we'll be putting it to some real use as soon as the next section.
Now then, before the next section, here's a summary. Play around with it. ;-)
Introduction
JavaScript, introduced in December of '95, is a client-side, object-based programming language intended for the manipulation of HTML and XML documents. Now, JavaScript isn't a full-blown object-oriented language, but it is indeed object-based. So despite any rumors you may have heard, there's alot more to this language than pop-ups and corny roll-over effects. Let's say, for example, you work at the local book store and need to compile and organize a list of books going in and out. You could create an object that recorded this data for you and allowed you to access it and check for recent changes instantly. And ever wondered how those professional websites create those accelerating/decelerating scrollbars? Well, they do it with flash, but it can be done with JavaScript. So, still not convinced that JavaScript is worth learning? Or maybe it's just been too complex a concept in the past? Well, if you said yes to the first question, you're a lost cause. As for the latter, i've done my best to cover this information in common-speak, so don't worry, i'm not going to drown you in history lessons.
Now that we've gotten the boring stuff out of the way, we can focus a little more on JavaScript's capabilities. So, what exactly can this "wonder-language" do?
- It can interpret a form and send a response without reloading the page
- It can create dynamics and interactivity on a webpage
- It can store and read cookies on a user's browser
- And of course, it can create those flashy roll-over effects that everyone loves so much
The above list, of course, doesn't cover everything. But I figure it should be enough to get your mind buzzing. Now then, ready to start coding?
Getting Started
JavaScript can be inserted directly into an HTML document via the HTMLScriptElement.
<script type="text/javascript"></script>
Not a complicated start, right? We'll be compiling our script within the opening and closing tags of this element. The type attribute is simply there to ensure that the browser knows what type of data it's dealing with.
A key thing to remember when inserting your script, is that JavaScript can only manipulate what of the document has already loaded. And when you think about it, that makes perfect sense (you can't change what doesn't yet exist). But before we continue, you should be aware of some of JavaScript's flaws. For one, as you can well imagine, JavaScript did not come into being at the same time as the internet, so earlier browsers aren't equiped to read and interpret it---resulting in lines upon lines of script appearing as plain text on the page. Another primary flaw is that, as a safety precaution, users may enable/disable JavaScript at will. In short, this means you can't expect everyone to see the outcome you intended.
So, is JavaScript not all it's cracked up to be? Certainly not. In fact, these flaws can easily be trumped (starting with the script block).
<script type="text/javascript">
<!--
CODE HERE
-->
</script>
All browsers support HTML comments, so browsers that don't recognize javascript will completely ignore the text inside. However, browsers that do support JavaScript will take note of the script type and execute the code. And what of flaw number 2? Simple. The HTMLNoScriptElement.
<noscript>
CODE TO EXECUTE IF JAVASCRIPT IS DISABLED
</noscript>
I doubt this needs any explanation, but hell, I love to babble. The code inside the noscript tags will execute when JavaScript is disabled. These tags are most commonly used to output messages such as, "For a better browsing experience, please enable JavaScript," but if need be, you can execute a couple hundred lines of CSS and HTML.
Debugging
I'll be honest with you, coding in JavaScript can be a messy job, and you're bound for enumerous errors. But luckily, being a client-side language, JavaScript is interpreted by the browser and does not require a compiler. This means that when confronted with an error, the browser will simply halt execution of the script and continue on through the rest of the source code.
Seems brief, but we'll be coming back to this later.
My First JavaScript
As with most any programming language, JavaScript embraces comments. These comments won't execute as code and simply allow us to guide ourselves (or others) through a script. In JavaScript, there are two types of comments, one-line and multiple-line. One-line comments are intiated by two preceding forward slashes and are terminated when the line is broken. Multiple-line comments are a bit more complex. They are initiated with a forward slash preceded by an asterick and terminated in opposite (don't worry, this is why we have examples).
<script type="text/javascript">
<!--
// This is a one-line comment
/* This is a
multiple-line
comment */
-->
</script>
The browser will recognize these lines as comments and decidedly ignore them. But...what if we used special characters and declarations in our comments? Would the browser then interpret them as code?
<script type="text/javascript">
<!--
// // Hello there!
-->
</script>
The answer is no. Take a look at the script above. You'd think the line would create a comment, terminate it, and create a new one. But in fact, "// Hello there!" is ignored by the browser entirely. We could write one thousand forward slashes preceding one another and the browser would recognize it all as a single comment and move along through the script. To sum it up, until you terminate them, you can put anything you wish in your comments.
And now that we're in to comments, I think it need be known that the closing "-->" won't always parse correctly (some times JavaScript-enabled browser will attempt to read the line as script). We can prevent this from happening by writing "-->" as a one-line comment.
<script type="text/javascript">
<!--
CODE HERE
//ending the script-->
</script>
Alright, so far we've learned what JavaScript is, how to declare it, what it can do, it's pros and cons, and how to write comments within it. If you need a break, go ahead and take it. This tutorial isn't going anywhere.
Up next we'll be printing text onto a document.
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
As I said before, JavaScript is object-based. Meaning it works off of an entire library of actions constructed upon one another. Take a look at the above code. An object is simply a "thing" with it's own unique characteristics and actions. Take for example the average human-being. We have characteristics (hair, eyes, skin-tone), and we have actions that we can perform (walk, talk, jump, eat). This is the foundation of an object-based language. Look again at the above script. document is our object and write() is one of the many actions it can perform. An object's properties and actions are made accessable through JavaScript's dot-structure.
Confusing stuff? Yeah, it can be. But don't worry about it, you're just getting started. We'll come back to it in another tutorial.
Now then, seeing as I have yet to explain what the above line of code is doing...document addresses the document that the JavaScript is currently in and write() states to print the text in parenthesis onto it. Keep in mind that JavaScript is case-sensitive, so to code Document.write("Hello World") would trip an error.
Datatypes
When you go to open a file on your computer, you'll note that near the bottom of the window is a drop-down list titled "Files of type." These types can range anywhere from txt to wav to jpg. These little extensions help the computer identify and sort different types of data. Were it not for them, you could end up opening picture files in Notepad.
The same holds true for JavaScript (and most anything computer-related). As programming languages become more and more extensive, there becomes a greater need for data organization.
JavaScript has 5 primitive datatypes---the building blocks upon which larger, more complex types of data (composite datatypes) are constructed.
- string
- number
- boolean
- undefined
- null
Of the 5, i'll take the liberty of explaining strings, numbers, and booleans.
Strings
Recall our document.write() script. Then consider this, in that script, we printed Hello World to the page. But what if we wanted to print document to the page? Seeing as document holds the place of an object in JavaScript, that's not really possible, is it? But surely there has to be a way. Surely there's a way to get the browser to differentiate between special texts and plain texts.
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
Note that Hello World is in quotations. Strings, our first type of data, inform the browser that certain texts should not be parsed. This means that we can in fact print document to the page.
document.write("document")
Strings are initiated and terminated by either single or double quotes. The trick comes when you want to place quotes in your string.
document.write("Have you read 'The Three Little Pigs' lately?")
document.write('Have you read "The Three Little Pigs" Lately?')
Depending on the type of quote you use to initiate the string, the other can be used inside it. Starting with a double quote, we can place single quotes in the string, and starting with a single, double in the string. Now eventually, you'll want to write both inside.
document.write("I'm reading \"The Three Little Pigs\"")
This is when backslash escaping comes into play. Kind of like strings, it prevents single characters from being parsed. Above, we needed to use both types of quotes in our string. Since we initiated the string with a double quote, we couldn't use a double quote in the string. By placing a backslash before those doubles, their special properties are eliminated and they don't terminate the string. Here's what would happen if we didn't do this:
document.write("I'm reading "The Three Little Pigs"")
The browser will initiate the string at the first quote and terminate it at the second ("I'm reading "). Then, since there are no quotations around it, it'll try and execute The Three Little Pigs as script. Thus the error, and why we must backslash escape.
Strings are a very important part of communication. Both with the user and the browser. This is why so many methods (actions to be performed) are offered to act on strings, ranging from grabbing, to replacing, to matching chains of characters within a string. Later in this tutorial, we'll be doing some cool things with them like validating forms and encrypting passwords. But to do so, will require knowledge of our next two datatypes. So let's get going!
Numbers
Numbers, where would we be without them? Well, certainly not here, browsing the web. Hell, there wouldn't even be computers (calculators or otherwise)! And how would the world survive without high school calculus? Alright, maybe that's too much. But you can't deny that math is all around us. We judge time by counting orbital rotations, we judge lengths based on metrics, we judge maturity based on age, it's all about amounts. And of course, JavaScript wouldn't be complete if it didn't support something so fundamental.
document.write(8)
Right, so we wrote a number to the page. Big deal, eh? Well, it gets better (really). Now that we're into numbers, I get to talk about operators!
JavaScript offers a wide variety of operators that allow you to assign values, compare operands, concatenate strings, perform arithmetic, etc. And seeing as we're only into numbers, you'll start learning from arithmetic.
Arithmetic and Grouping Operators | |
+ | addition; 2 + 1 |
- | subtraction; 7 - 5 |
* | multiplication; 4 * 3 |
/ | division; 8 / 2 |
% | modulus; 9 % 4 |
( ) | grouping; (8 + 2) * 3 |
Pretty straight-forward. Only ones I should have to explain are modulus and grouping. Modulus is simply the remainder you get when dividing two operands. 9 % 4 for example, returns 1 because 4 can only go into 9 twice (yielding 8; 9 - 8 = 1). Grouping in JavaScript works just the same as it would in basic math. JavaScript follows the order of PEMDAS, so grouping is often necessary when you want to add before multiplying, etc.
document.write(8 * 8 - 4 / (1 + 1))
Perform the operations and what do we get? 62. But the fun doesn't stop there. JavaScript also supports floating numbers (e.g. 6.21) and negatives.
document.write(14 / 5) // 2.8
document.write(2.8 * 5) // 14
document.write("8" - -3) // 11
Nothing special here. Except of course, the last operation. Can we really subtract a number from a string? The answer is yes. You can perform any of the above operations so long as that string only contains numbers. If we were to say, subtract -3 from "8a", our result would be the datatype NaN (not a number). The only real catch to performing arithmetic on strings is concatenation.
document.write("5" + 8) // "58"
document.write("Hey " + "there") // "Hey there"
String concatenation occurs when a + is performed between two operands and one of them is a string. It's a simple operation that combines the characters from both operands into one string. Just another reason to be wary of what types of data you're dealing with.
I'll wrap this up by introducing comparison operators, and in turn, booleans (yay).
Comparison Operators | |
> | great than; 10 > 4 |
< | less than; "abc" < "def" |
>= | greater than or equal to; 9 >= 9 |
<= | less than or equal to; 2 <= 4 |
== | equals; 9 == "9" |
!= | does not equal; 8 != 7 |
=== | equals (value and type); 4 === 4 |
!== | does not equal (value and type); 5 !== "5" |
The first four shouldn't take much explaining. "abc" < "def" should be the only mind-boggler. So, not only can we add strings together, but we can compare them? Sure, why not? What you're seeing ("abc" < "def") is called lexicographical string comparison. This basically checks if the strings are in order by character (...6789abcdef...), and seeing as the first character in our first operand "abc" is "a", and it does indeed come before the first character in our second operand "def" ("d"), "abc" is less than "def". If both operands had started with the same character, the comparison would have been between the next two characters and so on.
As for the last four, they take a bit more thinking. == checks if both operands have the same value (e.g. 9 and "9"), != checks if both don't have the same value (e.g. 8 != 7). === and !==, however, check for both value and type. This means that while 9 == "9" is true, 9 === "9" is not because one is a number and one is a string.
Booleans
Each of the previous comparison examples return a boolean datatype. Booleans are logical entities, either true or false.
8 < 10 // boolean true
5 < 4 // boolean false
5 != 4 // boolean true
"" // empty string; boolean false
0 // boolean false
undefined // undefined datatype; boolean false
null // null datatype; boolean false
NaN // NaN datatype; boolean false
false // a boolean datatype (obviously false)
true // a boolean datatype (true)
Nothing much to say here. Any comparison operation that isn't true is boolean false. And empty strings, 0s, undefineds, nulls, and NaNs are all boolean false. Soon enough, we'll be performing tasks based on these principles. In fact, it just may be that we'll do more work with booleans than strings and numbers combined! And while we're on the subject of logical entities, it seems only right to introduce logical operators!
Logical Operators | |
! | not; !(6 / 2 == 4) |
&& | and; 2 + 4 == 6 && 2 + 4 < 7 |
|| | or; 3 - 1 > 3 || 3 - 1 < 4 |
Alright, we've got arithmetic, comparison, and logical operators all in one boat here, so pay attention. Our first operation, !(6 / 2 == 4), says to return boolean true of 6 / 2 == 4 is boolean false (another example, !false returns true). Our second operation, 2 + 4 == 6 && 2 + 4 < 7, returns boolean true if 2 + 4 equals 6 and 2 + 4 is less than 7. Our last operation is probably the trickiest. Unlike the other two, it doesn't return a boolean. Instead, it sends back one of its two operands. Here's the breakdown: If the first operand is boolean true, it is returned. If the first operand is boolean false, however, the second operand is returned instead. As trivial as it seems, this is actually pretty nifty. And we'll be putting it to some real use as soon as the next section.
Now then, before the next section, here's a summary. Play around with it. ;-)
"Hello" + " " + "World!" // string concatenation; "Hello World!"
7 + 9 // arithmetic; 16
17 != 4 // comparison; boolean true
"apple" > "apples" // lexicographical string comparison; boolean false<br /><br />
!NaN // logical; boolean true
7 > 9 || null // first operand is boolean false; return second operand
!("a" + "sam" < "b" + "sam" && "sam" >= "sam") // boolean false