![]() |
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:
|
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.