“Brief” Guide to JavaScript – Part 1
Introduction
So you've probably heard all the buzz about JavaScript, especially with the widespread use of AJAX. But you might not know where to start learning. Or maybe you just start copying and pasting JavaScript snippets from around the web. If so, this guide is for you.
If you already know a programming language, you'll breeze through most of this material. If you already know JavaScript pretty well, I'm afraid this may only provide a few tips here and there for you. Simply put, this guide is the accumulation of knowledge I've gained from tinkering around in JavaScript.
This article may go through certain JavaScript topics quickly. I encourage you to reread anything you're unsure of, post a comment, or do a quick Google search. If it appears a portion is unclear, I may expand upon it. Feel free to compliment, flame, share, or print out and burn these series of posts. As a disclaimer, there are probably some cross-browser details I'm not aware of since I typically use JavaScript frameworks like jQuery and MooTools.
I don't intend for someone who's completely new to programming to read this series and instantaneously become a decent JavaScript programmer (I wish). Knowledge is only half the battle. The second half is actually practicing or exercising your newly acquired knowledge. Practice makes perfect (or at least makes you better).
This article assumes prior knowledge of HTML and CSS.
What is JavaScript?
JavaScript is an interpreted, loosely-typed, prototype-based, functional language. It's a dialect of ECMAScript and is used by browsers for client-side scripting. Originally named LiveScript, it was renamed to JavaScript in an attempt to lure Java developers, although the two languages aren't related at all. Compared to traditional languages, JavaScript is:
- interpreted: Each line is compiled right before execution (at runtime). Although this has some performance implications, it tends to reduce development time.
- dynamic: Type checking for data is done during runtime (when it is interpreted) as opposed to type checking during compilation time (like c/c++ or java). The interpreter requires matching types for a certain statements to execute, but not necessarily others that a static language may require (such as changing data-types for variables).
- prototype: Unlike most modern languages, JavaScript uses prototypes to perform inheritance as opposed to classes. The easiest way to describe a prototype system is that any object can be a parent to any other object (as opposed to just classes in traditional Object Oriented Design). It is worth noting that JavaScript frameworks such as PrototypeJS and mootools implement classes for traditional-styled programming. If you don't know what classes are, don't worry, we'll cover it later in this guide.
- functional: Functional languages focus less on modern Object Oriented Design and also treat functions as another data type (as opposed to a special feature of a language). This means you can pass in functions as arguments, return a function from a piece of code, etc.
Using JavaScript
The most common place to find a JavaScript interpreter is embedded in your browser for web pages. However, there are other uses: Firefox uses it to generate it's GUI and JavaScript's younger sibling implementation, ActionScript, is used in Flash. But I'll tend to focus more on JavaScript as it relates to web pages.
Most browsers that support JavaScript also have a built-in debugger of some sort (some better than others). Firefox's Firebug extension is recommended, although you could probably get by with Safari's/Chrome's debuggers. There's one for Opera, but I haven't used it so I can't comment on its quality. IE also has a debugger, but it's simply in terms of nasty modal-dialog boxes that should be avoided when possible.
Yes, I find it amusing the javascript.com has errors. [Internet Explorer 8]
Firebug's invaluable web developer's tool [Firefox + Firebug]
Now let's get started.
Script Tag
Since I'll be focusing on JavaScript for web pages, it's worth mentioning that the browser needs to be aware of when to stop parsing HTML in a page and start treating the text as JavaScript. This is done via the script tags.
<script type="text/javascript">
// <![CDATA[
// Your JavaScript code goes here
// (Oh yeah, these are comments which is ignored by the JavaScript parser until the end of the line)
/*
This is a multi-line comment which is also ignored
by the JavaScript parser until we close it.
*/
// ]]>
</script>
The type attribute is required by the html specification (in case a new browser interpreted language comes around) while the CDATA indicates that the text inside the block shouldn't be parsed as html (in the xhtml spec). Commenting them out is for browsers that didn't completely follow the spec and aren't aware of the CDATA blocks. However, due to the forgiving implementation of most browsers, missing the type attribute or CDATA block will still make the javascript function, but it's not good practice to do so.
Alternatively, you can use the script tag to point to a javascript file which will be immediately loaded and executed:
<script type="text/javascript" src="/path/to/js/file.js"></script>
To work correctly in IE, the script tag can't be self closing (eg - "<script />"). Script tags are also not one of the few valid self-closing tags accepted in XHTML. The external javascript file does not need CDATA or script tags, just pure javascript.
It's recommended to place your script tags near the end of your html (before the closing body tag). So we'll cover, in the future, why. If you want a reason to satisfy your curiosity, I'll direct you to Yahoo!
Variables
One of the most primitive lines of code for a language: assigning variables values.
Let's look at some ways to do this in JavaScript and their meanings:
myvariable = 'a string value';
var myvariable2 = 'another string value';
These two variable declarations assign specific value each. It is worth noting that the prefix of a var is important. Var indicates the variable is being declared in the smallest scope possible. This variable definition isn't in a function definition, it's scope is global as opposed to that particular function scope. It's a good practice to always use var to indication a new variable declaration (we'll discuss this when we talk about functions).
(aside)
Semicolons are used to separate commands for the JavaScript interpreter to parse. Think of it as periods in the English language. When reading aloud, you take a breath once you reach a sentence. The computer does that too, except that when it "takes a breath", it's trying to follow what it just read (like following a cookbook).
(/aside)
A variable can store a value. They are analogous to labeled boxes. Each box can store something (data). These variables are special that there are no limitations to whatever you put in it (only by computer capabilities). Unlike their mathematical relative, programming variables are assigned in the [variablename] = [value] style. So something like:
x = 1;
x = x + 1;
Is perfectly logical in most programming languages. The first statement assigns x to 1 while the second assigns x to 2, overriding the old value in the process.
Since JavaScript is dynamic, the type is automatically adjusted to what value it's given.
var mystr1 = 'my string'; // string value (aka text)
var mystr2 = "my string"; // another string value
var mystrcopy = mystr2; // mystrcopy stores "my string", which was from mystr2
var mynum = 200; // integer value (whole numbers)
var myfloat = 20.0; // float (or decimal) value
Likewise, you can change the type whenever you feel like it:
var myvar = 'a string';
myvar = 200; // replaces current string value to a number value: 200
Similar to most other programming languages, JavaScript has boolean values (identical to yes / no). We'll see the usefulness of booleans when we start talking about conditionals.
var yes = true;
var no = false;
Operations
Numerical values (float & integers) can be affected by basic mathematical operations. So add (+), subtract (-), multiply (*), divide (/) are all possible operations you'd expect.
var num1 = 5 + 5; // => 10 (addition)
var num2 = 7/2; // => 3.5 (division)
var num3 = num1 * num2; // => 35 (multiplication)
Strings can only accept the add operator which concatenates strings together.
var str1 = 'abc' + 'def'; // => 'abcdef' (string concatenation)
var str2 = str1 + 'ghi'; // => 'abcdefghi'
Another operator is mod (%), which returns the remainder of a division operation:
var remainder = 7 % 2; // remainder stores 1
Shortcuts
Sometimes we want to make changes to an existing value of a variable:
var val1 = 22;
val1 = val1 + 1; // val1 stores 23 (incremented by 1)
This is pretty common, so there's a shorter notation.
var val1 = 22;
val1 += 1; // val1 stores 23 (incremented by 1)
You can increment by any arbitrary number or variable which is pretty handy and increases readability of the code. Subtraction, multiplication, and division are also supported. But the mod operator doesn't work.
var val1 = 10;
val1 -= 3; // val1 stores 7 (decremented by 3)
val1 *= 2; // doubles the value. Stores 14
val1 /= 2; // halves the value. Stores 7 again.
val1 %= 2; // invalid. doesn't work.
But incrementing and decrementing by one is also extremely common (especially once we start using loops), so there's even a shorter way to increment and decrement by one:
var val1 = 20;
val1--; // stores 19
val1++; // stores 20
You don't have to use these shorthand notations, but it's good to know what they are in case you read through someone else's code.
Conversion
Sometimes, you'll want to convert some data types. Although JavaScript can automatically determine when to convert data types, you might need to tell JavaScript explicitly. That's because string concatenation looks identical to numerical operations. If you get input from the user, it is usually in a string format. Take this example:
var x = 2;
var y = '3'; // assume it's input from the user
var result = x + y;
What does result contain? Not 5. Turns out result contains the string value of 23. This is because JavaScript assumed we wanted string concatenation and automatically converted the integer to a string for us. We need to resolve this if we wanted to get the sum.
Since conversions are usually from strings to numbers, JavaScript provides handy methods: parseInt and parseFloat. Both accept a string value and return a integer or float respectively.
var num1 = parseInt('11'); // 11 as an integer
var num2 = parseFloat('1.2'); // 1.2 as a float (decimal number)
However parseInt has one caveat, it can accept more than just decimal system for numbers (such as binary or hex). 98% of the time, you'll want the decimal format, however parseInt defaults to attempting to figure it out by the string. For example, a leading zero hints at an octal conversion (base-8) to JavaScript parsers: something we don't want. For good practice, pass a second parameter with a value of 10, to force the string conversion to decimal.
parseInt('011'); // => 9
parseInt('011', 10); // => 11
Special Values
Variables can also be assigned special data types:
- Infinity - Represents a really large number (see Infinity property). Any number divided by Infinity is zero. Likewise, dividing by any non-zero number by zero returns Infinity.
- NaN - Represents "Not A Number" which usually represents a non-numerical value. This occurs if you divide zero by itself.
- undefined - Represents a variable which value isn't assigned yet. var myvar; will automatically set myvar to undefined.
These special values can also be directly set using assignment. (var myvar = NaN;)
Edit: Part 2 is available.
That’s the end of the first part. Feedback is always welcomed (including spelling/grammar mistakes). Next week we’ll cover if statements and loops.
-
abrahamvegh