TUTORIAL: Javascript Introductory

  • derfleurer
  • Beginner
  • Beginner
  • derfleurer
  • Posts: 56

Post 3+ Months Ago

Alright, this isn't complete. In fact, it's far from it. But there's plenty enough here to get you started. ;)

Oh, and to compensate for posting this on a forum, instead of interactive links, i've provided text to the effect of: Address Bar: javascript:confirm('Are you sure?');void(0). This is just a simple request for you to copy and past the italicized text into the address bar and hit "go."

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 flashy 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 (that was attempted humor). 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 passed the formalities, 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.

Code: [ Select ]
<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). So, if we wanted to modify the body of the document, we'd avoid placing the script in the header. ;-) 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).

Code: [ Select ]
<script type="text/javascript">
<!--
CODE HERE
-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3. CODE HERE
  4. -->
  5. </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.

Code: [ Select ]
<noscript>
CODE TO EXECUTE IF JAVASCRIPT IS DISABLED
</noscript>
  1. <noscript>
  2. CODE TO EXECUTE IF JAVASCRIPT IS DISABLED
  3. </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).

Code: [ Select ]
<script type="text/javascript">
<!--
 
// This is a one-line comment
 
/* This is a
multiple-line
comment */
 
-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3.  
  4. // This is a one-line comment
  5.  
  6. /* This is a
  7. multiple-line
  8. comment */
  9.  
  10. -->
  11. </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?

Code: [ Select ]
<script type="text/javascript">
<!--
 
// // Hello there!
 
-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3.  
  4. // // Hello there!
  5.  
  6. -->
  7. </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.

Code: [ Select ]
<script type="text/javascript">
<!--
 
CODE HERE
 
//ending the script-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3.  
  4. CODE HERE
  5.  
  6. //ending the script-->
  7. </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.

Code: [ Select ]
<script type="text/javascript">
<!--
 
document.write("Hello World");
 
//-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3.  
  4. document.write("Hello World");
  5.  
  6. //-->
  7. </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 associative arrays and [or]--in the above case--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. The semi-colon at the end of this line of code, simply enough, terminates it. It's technically not needed unless you're performing several actions on one line, but it's good practice to place anyway.

Code: [ Select ]
document.write("Hello"); document.write(" World")
document.write("Hello") document.write(" World") // syntax error, script halts execution
  1. document.write("Hello"); document.write(" World")
  2. document.write("Hello") document.write(" World") // syntax error, script halts execution


Unlike everything else in this tutorial, I won't take care to review every instance in which a semi-colon is or isn't necessary. This is something you're better off figuring out for yourself.

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.

Code: [ Select ]
<script type="text/javascript">
<!--
 
document.write("Hello World");
 
//-->
</script>
  1. <script type="text/javascript">
  2. <!--
  3.  
  4. document.write("Hello World");
  5.  
  6. //-->
  7. </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.

Code: [ Select ]
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.

Code: [ Select ]
document.write("Have you read 'The Three Little Pigs' lately?")
document.write('Have you read "The Three Little Pigs" Lately?')
  1. document.write("Have you read 'The Three Little Pigs' lately?")
  2. 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.

Code: [ Select ]
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:

Code: [ Select ]
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 (rawr), it's all about amounts. And of course, JavaScript wouldn't be complete if it didn't support something so fundamental.

Code: [ Select ]
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.

Code: [ Select ]
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.

Code: [ Select ]
document.write(14 / 5); // 2.8
document.write(2.8 * 5); // 14
document.write("8" - -3); // 11
  1. document.write(14 / 5); // 2.8
  2. document.write(2.8 * 5); // 14
  3. 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.

Code: [ Select ]
document.write("5" + 8) // "58"
document.write("Hey " + "there") // "Hey there"
  1. document.write("5" + 8) // "58"
  2. 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.

Code: [ Select ]
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)
  1. 8 < 10 // boolean true
  2. 5 < 4 // boolean false
  3. 5 != 4 // boolean true
  4. "" // empty string; boolean false
  5. 0 // boolean false
  6. undefined // undefined datatype; boolean false
  7. null // null datatype; boolean false
  8. NaN // NaN datatype; boolean false
  9. false // a boolean datatype (obviously false)
  10. 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! :p

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 if 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. ;-)

Code: [ Select ]
"Hello" + " " + "World!" // string concatenation; "Hello World!"
7 + 9 // arithmetic; 16
17 != 4 // comparison; boolean true
"apple" > "apples" // lexicographical string comparison; boolean false
!NaN // logical; boolean true
7 > 9 || null // first operand is boolean false; return second operand
!("a" + "sam" < "b" + "sam" && "sam" >= "sam") // boolean false
  1. "Hello" + " " + "World!" // string concatenation; "Hello World!"
  2. 7 + 9 // arithmetic; 16
  3. 17 != 4 // comparison; boolean true
  4. "apple" > "apples" // lexicographical string comparison; boolean false
  5. !NaN // logical; boolean true
  6. 7 > 9 || null // first operand is boolean false; return second operand
  7. !("a" + "sam" < "b" + "sam" && "sam" >= "sam") // boolean false


Pop-up Boxes


Alright, now the real fun (and potentially lethal) stuff, pop-ups! But not the kind you need a blocker for. These are pop-up boxes; used to relay messages and interact with the user. Pay close attention here, we'll be using them for the remainder of the tutorial.

Code: [ Select ]
alert("Hello World") // alert box


First up, alerts. If you don't know what an alert is, Address Bar: alert("Hello World!");void(0).

And before delving too far into things, I figure this is an ideal time to talk about functions. In JavaScript, a function is just a self-contained script. So far, we've called two different functions, write() and alert(). By passing data (arguments) through a function, we give it information to play with and manipulate. Above, our argument is the string "Hello World." The function will execute, and pop an alert onto the page with the information you gave it.

Later in this tutorial, we'll have an entire section dedicated to functions, but for now, this is all you need to know: they're self-contained code that may or may not require arguments in order to execute.

Code: [ Select ]
prompt("What's your name?", "name here") // prompt


Now this is something to get excited over. A prompt, as the name implies, prompts the user, requesting input. There are two arguments here, the request, and the input. Address Bar: prompt("request", "input");void(0). Cool stuff, right? And it gets better. The prompt actually returns the input! Here's a nifty example,

Code: [ Select ]
document.write( "Hey, " + prompt("What's your name?", "name here") + ". Welcome to my website." )


Alright, we're passing one argument through the write() function, a big, long, concatenated string. prompt() is returning the user's input. And since our request asks for a name, we should get a print to the document like, "Hey, Aaron. Welcome to my website." It's not all fun and games here, though. If the user doesn't supply an input, the prompt will return an empty string "", and if they hit Cancel, the prompt will return a null datatype (meaning no input exists).

But we can be clever about this. Remember that our logical Or operator returns one of its two operands based on the boolean value of the first. And since nulls and empty strings are boolean false, we can rig this up,

Code: [ Select ]
prompt("What's your name?", "name here") || "No Name"


With the above, if our user provides input, the prompt will return that input, and the first operand will be boolean true. In turn, the || operation will return that input. If the prompt (our first operand) returns null or "", however, the operation will return the second operand instead, the string "No Name." Now let's apply it,

Code: [ Select ]
document.write( "Hey, " + ( prompt("What's your name?", "name here") || "No Name" ) + ". Welcome to my website." )


Handy trick, isn't it? We use grouping operators (the parenthesis) around the || operation because we want it to return a value before being concatenated into the string. Alright, now on to confirmation boxes, things we unfortunately can't put to much use right now (but they're still pretty).

Code: [ Select ]
confirm("Are you sure?")


Address Bar: javascript:confirm("Are you sure?");void(0). Confirmation boxes only pass a single argument, and like prompts, they have return values. When a user clicks Ok, a boolean true is returned, and when they click Cancel, a boolean false.

And to wrap this section up, here's an example to make use of each box and our lovely || operator. Study it and continue on when you're ready.

Code: [ Select ]
confirm("Do you want to leave?") || alert("Hello, " + (prompt("I'm glad you decided to stay, your name is?", "") || "No Name") )


Address Bar: confirm("Do you want to leave?") || alert( "Hello, " + (prompt("I'm glad you decided to stay, your name is?", "") || "No Name") );void(0)
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

Post Information

  • Total Posts in this topic: 1 post
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 1 guest
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.