JavaScript for geeks (Part I)

November 5th, 2003

In which I explain the basics of javascript syntax, conditionals and iterators for people who know what conditionals and iterators are.

First of all, let me state something once and for all, just in case you are part of the group of confused people: JavaScript is not Java; JavaScript has nothing to do with Java. The fact that it has “Java” in its name is just a marketing ploy.

Now that we have set aside that urban legend, let’s start with the facts.

Syntax

JS uses the classic “C-like” syntax (also used by Java, Perl and other languages). All language constructions can take either a single statement all alone, or a group of statements enclosed with curly braces; statements end with semi-colons, and white space is ignored:

bc. statement; { statement; statement; statemet; } { statement; statement; {statement;} }

statement;

There are some cases where a semi-colon at the end of a statement is not required. Those cases are confusing. Always use a semi-colon. But if you want to know, you can omit it when you have a line break between statements and the second statement doesn’t start with an operator, or for the last statement inside a curly braced block. But you would have to count on the interpreter ability to guess where does a statement end.

Identifiers (variable and function names) can use letters, numbers or underscores, but they cannot start with a number. And yes, “_” is a valid variable name.

Comments

Not much explanation is needed:

bc. // Single line comment

bc. /* Multi-line comment */

Both types of comments can start anywhere on a line. They don’t need to start at the first column.

Conditional Statements (or branch control)

JS uses the classic if construct.

Just note that continuous else-if blocks use else if, with a space in between, not elsif nor elseif, but else if:

bc. if (condition) block

bc. if (condition) block else block

bc. if (condition) block else if (condition) block

You can also use switch statements, again, C-style

bc. switch (expression) { case value1 : statement; statement; break; case value2 : statement; statement; break; default : statement; statement; }

Note that the set of statements to be executed for each value is just a series of statements. It cannot be a block, and you need to include a break to prevent it form executing the statements of the case that follows. The final default does not need a break.

JS also provides the conditional operator ?

Even if it’s considered an operator and not a statement, I list it here for convenience:

bc. condition ? ifvalue : elsevalue

Iteration Statements

JS provides (yes, you guessed it) C-style iteration operators: for, while and do..while.

bc. while (condition) block

bc. do block while (condition)

The difference between while and do..while is that the first checks the condition before executing its block, and the later executes the block first, thus insuring at least one execution. Both will iterate as long as condition is true. And remember, it’s do..while, not do..until as in other languages.

bc. for (initialexpression; condition; stepexpression) block

is equivalent to

bc. initialexpression; while (condition) { block; stepexpression; }

The contidion is always evaluated before each iteration, and remember that stepexpression will not be evaluated if you break out of the loop.

And speaking of “break”, you can use

bc. break;

to abort the current iteration and jump out of the iterator constructor, and

bc. continue;

to abort the current iteration and continue with the next one.

Both break and continue can be used as deep inside nested ifs as needed, but the only cancel the closest loop.

bc. while (a) { while (b) { if (something) { break; } } }

will cancel the loop controled by b, but not the one controlled by a.

JavaScript also provides a for..in statement that lets you iterate over the elements of an array or object.

bc. for (variable in object) block;

It’s important to know that variable will iterate over the indexes to the contents of object, not the contents themselves. So your for..in blocks will probably look like:

bc. for (index in object) { elem = object[index]; }

Declaration Statements

You use the function statement to declare new functions.

bc. function name(parameter, parameter) { statements }

Since functions are really variables in JS, you can also use the function operator to declare a function like this:

bc. name = function(parameter, parameter) { statements }

The var operator declares variables to be local to the enclosing function.

bc. var name; var othername = value; var name = value, othername, yetanother = othervalue;

Anything not declared as a local variable is considered to be global.

You can use var inside a condition or expression for a statement, like this:

bc. for (var i = 0; i < 5; i++) {...} while (var exists = something()) { alert(exists); }

But that does NOT mean the variable is local to the block only. Variables will be local to the function they are declared in. It’s just nicer to declare them next to where they are used.

Variables in JS are dynamically typed (as in many other scripting languages), so you don’t specify a type when declaring a variable. The type depends on the value and the context.

Declaring the same variable more than once inside the same function WILL NOT trigger an error.

Operators

Since JavaScript offers the typical operators. I will only mention the ones some people might not know about.

Autoincrement operators add (++) or substract () one from a variable.

bc. a++ ;

is equivalent to

bc. a = a + 1;

You can use the operator in the middle of an expression, so if you use a+ the expression uses the old value of a, but if you use +a, the expresion uses the new value.

bc. a = 1; b = a++ + 1; // a 2, b 2 a = 1; b = ++a + 1; // a 2, b 3

Shorthand operators are useful for doing something on a variable and storing it back on the same variable.

bc. a += 1;

is equivalent to

bc. a = a + 1;

You can use that notation with most operators.

bc. a *= 2; a /= 3; a %= 2;

JavaScript has two different equality comparison operators.

bc. a b;

Is the basic one, which returns true if a and b are equal, even if they have different types, so "1" 1 is true.

bc. a === b;

Is the strict comparison, which is only true if both a and b are equal and of the same type.

Of course, there is also != and !== for not equal comparisons.

JavaScript uses the same operator for arithmetic addition and string concatenation.

Or if you prefer OO terms, the + operator is overloaded.

If any of the operands is a string, then + acts as a string concatenator.

bc. 1 + 2 3; "1" + "2" “12”; “1” + 2 "12"; 1 + "2" “12”;

If you want to force a string into a number, you have several options.

First, there are a couple of functions:

bc. var a = ParseInt(“12”); var b = ParseFloat(“3.14”); a 12; b 3.14;

But since JavaScript is a scripting language, you might want to use something simpler. The unary + operator is something most people don’t know.

bc. var a = “12”; var b = +a; b 12; var c = 2 + (+a) - 1; c 13;

Before discovering unary , I used to do the 1 – 1 trick that has worked for me in other scripting languages. In JavaScript that fails, because + is concatenation when a string is involved. But - has no overloaded meaning, so this will work:

bc. var a = “12”; b = a – 1 + 1; b 12;

Just make sure to put the - 1 first.

However, don't use this trick. You can get confused and put the 1 first and you'll never understand why your code is not working. Use unary or ParseInt / ParseFloat.

The asignment operator also returns the assigned value.

Which means you can do something like:

bc. a = (b = 2 + 1) + 2; // a 5, b == 3

and it’s very useful for iterations

bc. while (var e = GetNextElement()) { ... }

The comma operand let’s you join several expressions where you can only use one.

It simply returns the value of the last expression.

bc. a = (1 + 2, 2 + 3, 3 + 4); // a == 3 + 4

But of course, that’s really useful if each expression is calling a function with other effects, or storing a result in a variable. Usually, it’s used in for loops like

bc. for (var i = 0, var j = 0; i < 10 || j < 5; i+, j+) { ... }

More JavaScript for geeks

Part II deals with variables, contexts, using objects, using functions, function pointers and other related items.

Part III will come later and will cover creating your own object classes.

Part IV is a collection of links and other resources about JavaScript.

9 Respuestas a “JavaScript for geeks (Part I)”

  1. zazoo dijo:
    Excellent well laid out and clear explanations.
  2. afrael dijo:
    I did not know the for in syntax. Also, Im looking forward to the OOP enb Javascript, that really looks like fun :D
  3. Sergi dijo:
    nice introduction. although forcing a string into a number by adding and substracting 1 is accepted and used, I would have preferred you to write the correct syntax: parseInt(var). Going for part 2. good work.
  4. Sebastian dijo:
    Sergi... the "correct syntax" (whatever that means) for string to number conversion seems to be the "+" sign on front. After all, this is just a scripting language. No need to be using long syntaxes when something shorter is available.
  5. Sergi dijo:
    Take it as you want, but parseInt / parseFloat are the way to go. What if you want to have different base (hex/oct/2/16...)? These two functions allow you to handle it, while your method doesnt. Be precise while teaching, please.
  6. Sergi dijo:
    Moreover, "10" + 1 - 1 does: "10" + 1 = 101 101 - 1 = 100 So... you got it wrong my friend.
  7. Sergi dijo:
    sorry, "10" -1 +1 works, but it's still a bad way to do it, honestly
  8. Sebastian dijo:
    "10" - 1 + 1 works fine, because the first "-" is not confused with the string concatenation "+". "10" + 1 - 1 fails, because it's equivalent to "101" - 1. But the one I'm talking about is simply +"10". The plus sign on front of any string (or string variable) will convert it to a number. Perhaps I should change the text to make it clearer.
  9. Nombre dijo:
    The best JavaScript Tutorial I found. Especially the things you normally don't find.

Deja tu respuesta

If you can read this, you don't use a typical webbrowser that plays nice with CSS.
Please do not fill in anything here!