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.


All times are GMT -5. The time now is 02:39 PM.

Powered by: vBulletin Version 3.8.1
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.