The Cellar

The Cellar (http://cellar.org/index.php)
-   Technology (http://cellar.org/forumdisplay.php?f=7)
-   -   Learn Javascript (http://cellar.org/showthread.php?t=5389)

hot_pastrami 03-23-2004 12:34 AM

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.

hot_pastrami 03-23-2004 01:00 AM

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.";

if (confirm(prompt)) {
  document.bgColor = "red";
}
else {
  alert("We'll make it blue then.");
  document.bgColor = "blue";
}

The parenthase-looking characters floating around, like the one after "else," are called curly-braces, and you get them when you hold Shift and hit the square bracket keys. There are a lot of curly braces in most programming languages, so get used to them.

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.

hot_pastrami 03-23-2004 11:08 AM

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.";
var is a Javascript keyword, which is short for variable. You use this keyword whenever you want to define a new variable, in this case a variable named prompt. A variable is simply a way to attach a name to any given value, so that you can use that value later. Now that the variable prompt is defined, we can use it any time we want the text "Click OK to change the background to red.\nClick Cancel to make it blue." to appear.

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?";
...if you add this line, then any time the variable prompt is used, you'll get the new prompt text.

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.

Radar 03-23-2004 11:29 AM

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.

hot_pastrami 03-23-2004 11:32 AM

Quote:

Originally posted by Radar
A couple of questions...
I'm in the middle of typing up the next big section, but once I'm done with it I'll answer these...

hot_pastrami 03-23-2004 12:03 PM

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)) {
  document.bgColor = "red";
}
else {
  alert("We'll make it blue then.");
  document.bgColor = "blue";
}

...so, the first block will execute if the if conditional tests TRUE, otherwise that block will be skipped, and the second block will be executed. A code block can contain many sub-blocks, which can also contain sub-blocks, ad infinitum.

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)) {
if is a basic test... it basically reads as "if the test in these parenthases proves true, then execute the code in this block." The test can be as simple as "if the number one is greater than the number five," or "if the value in the variable myNumber is equal to 10."

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)
confirm() is a built-in Javascript function. confirm() opens up a window with OK and Cancel buttons... if the user clicks OK, confirm() will return TRUE, and otherwise it will return FALSE. So when the program gets to this line, it will sit and wait for the user to do click something, so that it knows whether the conditional is TRUE or FALSE, and execute the appropriate block of code.

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");
A function will sometimes return a value, which can then be used by your program. Sometime it's a true or false like confirm() returns, but sometimes it's a number, a phrase, etc. We'll see how to make use of return values later on.

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.

hot_pastrami 03-23-2004 12:14 PM

Beginners, you may gloss over this reply if you like, we'll cover this stuff soon enough.

Quote:

Originally posted by Radar
Do you have to declare your variable types such as a string, a whole number etc?

Not in Javascript... in Javascript, a basic variable can contain a boolean, a character, a number, or a string. In more advanced languages, this distinction is necessary, but not in JS.

Quote:

Originally posted by Radar
In the example of madlibs code, what are the commands for input and output of strings such as the "get" command?
Javascript have a built-in function called prompt() which asks the user for a value, and returns it. That's how we'd retreive the words from the user. We can then print those back out to the browser with a document.write() command.

Quote:

Originally posted by Radar
Does a double equal sign == mean not equal to?
No... a double equal is the test operator... if (myNumber == 10). A single equal is the assignment operator... myNumber = 15; If you want to test for Not Equals, you use the != operator.

A post on Javascript operators will be coming up shortly.

hot_pastrami 03-23-2004 12:41 PM

Having fun yet? Is anybody even reading this?

Ok, on we go to the next line:
Code:

}
That's the end of the block that is dependent on the if statement.

That was easy.

Ok, the next line:
Code:

else {
We discussed this one previously... else a way to define an optional block of code which will execute in the event that the if statement tests to False.

More later.

Radar 03-23-2004 12:50 PM

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:

var noun;

{
prompt("Please Enter a Noun.", noun);

write("The Fox jumped over the ",noun);
}
I tried assigning the variable "noun" with the prompt value by using this line

Quote:

noun = prompt("Please enter a noun.");
But that doesn't work either. hmmmm

Beestie 03-23-2004 02:10 PM

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

hot_pastrami 03-23-2004 02:49 PM

Quote:

Originally posted by Radar
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.
You're very close... try this:
Code:

var noun = prompt("Enter a noun", "dog");
document.write(noun);


hot_pastrami 03-23-2004 03:09 PM

Ah crap, I accidentally skipped a line previously:
Code:

document.bgColor = "red";
This is our first refernce to an object. But I'll save that for the next post, it's little involved.

Alrighty, onto the next line of the example:
Code:

alert("We'll make it blue then.");
alert() is just another built-in JS function, it displays a simple dialog box, and the text given as the argument is displayed, with an OK button.

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();
Next line:
Code:

document.bgColor = "blue";
See the above cop-out. Heheh. I'll get into that very soon.

And the last line:
Code:

}
This just closes the else block. Easy.

Stay tuned.

Radar 03-23-2004 03:38 PM

Thanks for the help. So madlib style would be something like this:

Quote:

var noun = prompt("Enter a noun", "moon");
document.write("The Cow Jumped over the ",noun);
I'm assuming the "document.write" part is calling an external object called "document" that is programmed to output to the screen like the old "printf" or "cout" commands in C/C++. That being said, do you have to include any specific libraries? Or is everything ready to go?

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.

hot_pastrami 03-23-2004 03:44 PM

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;
...I can put lot of kinds of data into it by assigning it with the assignment operator, a single equals sign:
Code:

whatever = "Some data";
whatever = 1122363723;
whatever = 'c';
whatever = prompt("Are you stupid");

The first line above is assigning a string to the variable. A string is just a collection of alphanumeric characters in a certain order. This phrase is a string. When working with a string, the data needs to be enclosed in "quotation marks." This is probably the kind of variable you'll work with the most.

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;

myNumber = 1 + 5;  // Variable myNumber now equals 6
myNumber = myNumber + 10; // myNumber now equals 16
var newNumber = myNumber + myNumber; //newNumber = 32, myNumber still equals 16

A variable can be named whatever you want, as long as the first character of the name isn't a number, and there are no spaces in the name. Varaiable names are case-sensitive, so a variable called TEST cannot be referenced as Test or test. The following are all valid and unique names:
Code:

var Test;
var test;
var TEST;
var _TEST_;
var Test2;
var testingIsAFunThingToDoInJavascript;

As written, these variables will all conain the special value undefined, because I didnt set any value to them with the assignment operator, the equals sign.

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.

hot_pastrami 03-23-2004 03:54 PM

New programmers can skip this post

Quote:

Originally posted by Radar
I'm assuming the "document.write" part is calling an external object called "document" that is programmed to output to the screen like the old "printf" or "cout" commands in C/C++. That being said, do you have to include any specific libraries? Or is everything ready to go?
Yeah, I've been trying to lead up to objects so they're not quite so confusing for people who have never programmed before.

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:

Originally posted by Radar
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.
You're not being a pest... I know that for you've got some experience in programming, so I seem to be moving a bit slow... I'm trying to write this so someone who has never programmed will have a shot at learning it. Hopefully I'm not confusing everyone too badly.

hot_pastrami 03-23-2004 04:25 PM

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";
var model = "Camaro SS";
var exteriorColor = "black";
var interiorColor = "charcoal";
var horsePower = "410";

...and you might create functions for your car, like start(), accelerate(), brake(), etc (I'll get into how to create your own functions shortly).

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();
mustangGT.accelerate();
alert("Who's your daddy?");

...or, for something that uses a built-in object:
Code:

document.write("Some text");
...this will print the words Some text to the browser window. Javascript also creates an object called window to provide access to the browser window. You can use the alert() function we went over previously to display the contents of the window object's location variable, which contains the current URL:
Code:

alert(window.location);
Don't worry if you don't understand it fully, objects can sort of be learn-as-you-go.

More later.

lumberjim 03-23-2004 10:43 PM

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");
}

hot_pastrami 03-23-2004 11:09 PM

Quote:

Originally posted by lumberjim
The very first characters of each code....are those commas, or periods?
I'm not sure what you're referring to here...

lumberjim 03-24-2004 05:37 AM

Quote:

Originally posted by hot_pastrami

I'm not sure what you're referring to here...

code:
.
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?

Happy Monkey 03-24-2004 06:33 AM

What browser are you using? On mine, those are horizontal lines - not pat of the code at all.

jinx 03-24-2004 06:47 AM

-lumberjim

netscape 7.1

jinx 03-24-2004 06:51 AM

1 Attachment(s)
see?

hot_pastrami 03-24-2004 10:17 AM

Quote:

Originally posted by lumberjim
are these even part of the code, or are you just putting them there out of habit?
Those are supposed to be horizonatal lines, automatically added when i use the "code" vB tags. Hmm. Netscape must have issues with horizontal lines under some circustances.

What are you doing running Nutscrape anyway? What kind of daft, running-around-with-limp-wrists silly person would choose Netscape over Mozilla? :D

lumberjim 03-24-2004 10:40 AM

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

Radar 03-24-2004 10:46 AM

Less chatting, more programming please.

hot_pastrami 03-24-2004 10:58 AM

Quote:

Originally posted by lumberjim
browser snob
Man, we're just trying to help... the first step to recovery is admitting that you have a problem. So, let me take care of that right now... I admit that you have a problem. Ok, now we can move on to the second step... bitching at you about your uber-lame browser, with really smarmy quips like this:

"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.

hot_pastrami 03-24-2004 03:18 PM

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.

lumberjim 03-24-2004 06:06 PM

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"

lumberjim 03-24-2004 06:37 PM

{(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?

hot_pastrami 03-25-2004 11:46 PM

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.

Radar 03-26-2004 02:02 PM

Let's make with the programming

hot_pastrami 03-26-2004 04:43 PM

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.

hot_pastrami 03-28-2004 02:17 PM

Ok, sorry about that delay. Due to over-exposure to work, I was clinically dead for a while. But it went away.

Quote:

Originally posted by lumberjim
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"

Javscript is limited in what it can do for reasons of security. Among those limitations is the ability to change what the buttons on a prompt() or alert() dialog say, nor can you change the title text of these boxes. Otherwise, naughty web developers could make innocent Javascript dialogs look like operating system errors, and stuff like that.

Quote:

Originally posted by lumberjim
{(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?

As for question #2, there really isn't a direct way to clear a page aside from reloading, or loading a new page. It can be accomplished through other means, but we'll get into that stuff later, because that would be getting a little ahead of ourselves. As for question #1 and #3, the answer is to use HTML formatting. I figure I'll start teaching some rudimentary HTML when we get to that point, and if anybody cares enough, I'll include more of that.

More soon.

OnyxCougar 03-28-2004 02:54 PM

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.

hot_pastrami 03-28-2004 03:01 PM

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;
01 var userName = prompt("Please enter your name");
02 var userIQ = prompt("Please enter your IQ");
03
04 if (userName == "Lumberjim") {
05    var jimResponse = "You're too sexy for your shirt";
06    document.write(response);
07  }
08  else {
09    var notJimResponse = "Jim is too sexy for his shirt";
10    document.write(notJimResponse);
11    if (userIQ < jimIQ) {
12      var iqResponse = " ...and you're not as smart as he is.";
13      document.write(iqResponse);
14    }
15 }

jimIQ, userIQ, and userName are all global variables, because they are not defined inside a block. The variable jimResponse was defined in the block which starts on line 04 and ends on line 07, so it's scope is limited to that block. If I tried to access the variable jimResponse on line 09 or line 12, I'd get a "variable not defined" error. But I *could* access notJimResponse on line 13, because that block is a sub-block of the one which defines notJimResponse.

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.

hot_pastrami 03-28-2004 03:03 PM

Quote:

Originally posted by OnyxCougar
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.
A lot of what we're covering now is just to give you a notion of how it all works... the pieces will start falling together once you have more of them to work with. That is, if I'm as effective a teacher as I hope I am.

Radar 03-29-2004 10:25 AM

Can you reference line numbers as you could in the old basic programming language? For instance "Goto 20"?

hot_pastrami 03-29-2004 11:06 AM

Quote:

Originally posted by Radar
Can you reference line numbers as you could in the old basic programming language? For instance "Goto 20"?
No, the "GOTO" command and all of it's variants are not present in object-oriented programming. The consensus is that there is always a better way to do the same thing with modern programming languages, and GOTO commands make the code very difficult to maintain.

I'll try to post the next bit this afternoon, if I get a break in work...

Radar 03-30-2004 01:20 PM

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)

hot_pastrami 03-31-2004 01:58 PM

Quote:

Originally posted by Radar
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)
Yeah, they were probably pulling code from multiple sources, and you didn't manage to get it all. I't sort of like importing libraries, but not quite.

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.

hot_pastrami 04-05-2004 03:48 PM

Ok... the gaping maw of work which recently swallowed me up has finally vomited me back out again. Look for more here soon.

lumberjim 04-05-2004 03:53 PM

yeah, you keep saying that, you big tease. why should we trust you this time?

hot_pastrami 04-05-2004 04:45 PM

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 () {
  var prompt = "Click OK to change the background to red.\nClick Cancel to make it blue.";

  if (confirm(prompt)) {
      document.bgColor = "red";
  }
  else {
      alert("We'll make it blue then.");
      document.bgColor = "blue";
  }
}

If you paste this into the Javascript Tester, nothing will happen, because though we define the function, we never make a call to it, so it doesn't execute. Try adding this to the bottom:
Code:

changeBackgroundColor();
Now it'll execute. If you added that line twice, you'd go through the dialogs twice.

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) {

  if (confirm(prompt)) {
      document.bgColor = newColor;
  }
}

When we do this, the variables prompt and newColor are created inside the function when it is called, and those variables contain the values that were passed into the function. So when we call the above function, it would look something like this:

Code:

var colorPrompt = "Click OK to change the background color.\nClick Cancel to leave it unchanged.";
var color = "purple";

changeBackgroundColor(prompt, color);

...or, just like this:
Code:

changeBackgroundColor ("Do you want to change the background color?", "green");
Say we want the function to do something useful, and hand the results back to us... we use the return keyword to send the value back to whatever called the function:
Code:

function addTwoNumbers (first, second) {
  var sum = parseInt(first) + parseInt(second);
  return sum;
}

(The function parseInt() causes Javascript to treat a value like a number rather than like a string, but we'll get to that later). So, we could call the above function like this:

Code:

var someNumber = prompt("Enter any number");
var anotherNumber = prompt("Enter any other number");
var myTotal = addTwoNumbers(someNumber, anotherNumber);

alert(myTotal);

We can return a string, a number... any kind of data.

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) {
  if (first == "") {
      alert("You didn't provide the first number");
      return 0;
  }
  if (second == "") {
      alert("You didn't provide the second number");
      return 0;
  }
  var sum = parseInt(first) + parseInt(second);
  return sum;
}

Suppose someone calls our addTwoNumbers() function without sending any arguments... When no value is sent for an argument, the function gives that variable the special value undefined. Many programming languages call this value null.

More later...

hot_pastrami 04-05-2004 04:46 PM

Quote:

Originally posted by lumberjim
yeah, you keep saying that, you big tease. why should we trust you this time?
Faith, my friend. Blind, misguided faith.

hot_pastrami 04-06-2004 03:44 PM

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...

lumberjim 04-06-2004 03:55 PM

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.

hot_pastrami 04-06-2004 04:23 PM

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
alert(300 - 32);  //subtract
alert(5 * 5); //multiply
alert(20 / 2); //divide

There is also the Assignment operator, the plain old equals sign, which assigns a value to a variable. We've used this one many times in our examples:

Code:

var someNumber = 10 + 3;
Just like in arithmetic, you can use parenthases to force things to happen in a certain order. If you don't use parenthasees, everything happens in the same order you learned in math class (Multiply, Divide, Add, Subtract):

Code:

var attendees = 40;
var extraSeats = 5;
var sessions = 10;

var totalMeals = (attendees + extraSeats) * sessions; // result will be 450
var badMath = attendees + extraSeats * sessions;  // result will be 90

The + operator is special in a way, because it works on strings as well as on numbers. If you add two strings together, the just get stuck together into one string. This is useful for lots of stuff:

Code:

function getUserName () {
  var name = prompt("Enter your full name");
  return name;
}

function welcomeUser (name) {
  document.write("Welcome to this website " + name + "!");
}

var userName = getUserName();
welcomeUser(userName);

There are also operators to compare things, as we've seen a little in our examples with the == operator. These are useful in conditionals, like the if statement, and some others that I'll post soon. Here are the most common ones:

Code:

Two items are equal: ==
Two items are NOT equal: !=
First item is greater in value to the second item: >
First item is lesser in value to the second item: <
First item is greater than or equal to the second item: >=
First item is less than or equal to the second item: <=

We'll use these in future examples.

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;
var secondNumber = 150;

if (firstNumber > secondNumber && firstNumber == 1000) {
  alert("This message will not appear unless you change firstNumber to 1000.");
  alert("...because though the first conditional is true, the second is not.");
}

if (secondNumber == 100 || secondNumber / 50 == 3) {
  alert("This WILL appear");
  alert("...because though the first conditional failed, the second was true");
  alert("...which enough for an OR");
}

The other Logical Operator is the Logical NOT, which is the exclamation point (!). It will reverse the results of any conditional. We'll use that one later.

hot_pastrami 04-06-2004 04:26 PM

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.

Radar 04-07-2004 04:38 PM

I'm looking at it between schooling criminals who want to rob me and everyone else in America. ;)

SteveDallas 04-09-2004 11:00 PM

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.