Alright, this isn't complete. In fact, it's far from it. But there's plenty enough here to get you started. 😉
- 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?
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.
Seems brief, but we'll be coming back to this later.
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.
Up next we'll be printing text onto a document.
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. 😉
document.write("Hello"); document.write(" World") 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.
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.
Of the 5, i'll take the liberty of explaining strings, numbers, and booleans.
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.
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!
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!
Arithmetic and Grouping Operators
- addition; 2 + 1
- subtraction; 7 - 5
- multiplication; 4 3
/ division; 8 / 2
% modulus; 9 % 4
( ) grouping; (8 + 2) 3
- multiplication; 4 3
- subtraction; 7 - 5
document.write(8 * 8 - 4 / (1 + 1))
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).
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.
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! :p
! 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. 😉
"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**
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.
alert("Hello World") // alert box
First up, alerts. If you don't know what an alert is, Address Bar: alert("Hello World!");void(0).
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.
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,
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,
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,
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).
confirm("Are you sure?")
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.
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)
This page was published on