JavaScript for geeks (Part II)

November 5th, 2003

In which I talk about truth, numbers, literals, objects and functions.

This article builds on the basics explained on Part I, so be sure you read that one first, or that you know enough javascript to

We will now get into variables, values, literals, arrays, objects and other miscelanea.

Booleans and comparisons

JavaScript considers as “false” the following:

bc. false, 0, “0”, ””, null, undefined;

Anything else is “true”.

The list above applies to any condition expression and to any boolean operator. But not necesarily to the == operator, because null is never equal to false.

bc. false 0; false “0”; false == ””; false != null; false != undefined; null == undefined;

The boolean operators not only return true, they return their operands

Since “this” is considered to be true, the boolean operators (&& and ||) can return their operands instead of a simple true value.

Look at them this way: a && b will return a if a is false (or equivalent to false, see above) or b if it’s not.

a || b will return a if a is true or b if it’s not.

Not only that. Neither operator will evaluate b unless it will be returned. So true || f(x) will never call f(x).

NOTE: Very Old Browsers, and Flash’s ActionScript don’t seem to follow this rule, so be careful.

All this means you can use nice shortcuts like:

bc. name = name || “Default Name”; result = DoSomething() || ReportError(); attrValue = object && object.attribute;

Other boolean operators, like !

Not-not will force something into a boolean.

bc. “a” true; "a" ! true; !!”a” === true;

Numbers

Number literals use the classic c-style.

bc. 12345; // decimal, start with 1-9 0xFF; // hex, starts with 0x 071; // octal, starts with a 0, no x

All numbers are floats

In JavaScript all numbers are numbers. There is no special class of Integers. Everything is considered a 64 bit floating point value. Just thought about letting you know that.

NaN (Not a Number) and infinity are special numbers

bc. “A” – 1 + 1 NaN; 1 / 0 infinity; typeof NaN "number"; typeof infinity “number”;

But they have the particularity of never being equal to anything, even themselves. So you have to use isNaN() and isFinite() to check for them.

bc. (NaN NaN) (infinity infinity) false; isNaN(NaN) !isFinite(infinity) true;

Strings

String Literals use single or double quotes.

bc. “This is a string”; ‘this is also a string’; ‘c’; // this is not a char, it’s a string. There are no chars in js

And they use a backslash \ to insert special characters and escape others.

There is no difference between single and double quoted strings. They both allow full use of backslash escaping (unlike other languages where single quotes denote strings that don’t escape).

Special String literals

bc. ”\n”; // Line Break ”\r”; // Carriage Return, less useful ”\t”; // Tab ”\’”; // Single quote ”\””; // Double quote ”\\”; // Backslash

String length

All string objects have a length property.

bc. “Test”.length 4;

Strings are arrays (well, in Mozilla anyway)

bc. "test"[3] ’s’;

But this doesn’t work in the JavaScript interpreter used by Microsoft, so don’t count on it.

Objects and Arrays

We will talk first about Objects and you’ll later see why.

Objects are implemented as Maps/Hashtables/Associative Arrays

If you don’t know what any of those terms mean, go look it up

Object attributes can be accessed using object notation or array notation.

bc. obj[“attribute”] == obj.attribute;

Of course, the second notation (also called “dot notation”) can only be used if the attribute name is a valid JavaScript name. It won’t work with spaces or other non-alphanumerical characters, while you can use any string with the “array notation”.

It won’t work either when the attribute name collides with a reserved word in JavaScript.

Objects can be created with literals or with the new operator.

Object literals use curly braces as delimiters. While the new operator uses a class name and parameters (more on this on Part III of this guide).

bc. var a = {}; a[“some”] = “a”; a[“fields”] = “b”; var a = {some: “a”, fields: “b”}; var a = new Object(); var a = new Object(“a”, “b”);

Arrays are Objects.

An array is a special class of object, but it still is an object. It is a hashmap with integer index values (and they are actually converted to strings internally).

They have a length property that evaluates to one more than the largest integer index in the array. That means that as long as you use integer indices, your array object will behave like a regular array in any other language.

But you can also add “named” attributes to an array object, just like with any other object. As long as those attributes are not valid numbers, they won’t increase the length property of the array.

There is also an array literal constructor, using square brakets.

bc. var a = [1, 5, 9, 3, 15];

Arrays have some extra methods.

Since Arrays are objects, they can have predefiend methods and the language inventors added some very useful ones.

bc. var a = new Array(“a”, “b”, “c”); a.push(“d”) 4; a [“a”, “b”, “c”, “d”]; // push() adds an element to the end of the array // and returns the new lenght a.pop() "d"; a [“a”, “b”, “c”]; // pop() gets the last element and removes it a.unshift(“d”) 4; a [“d”, “a”, “b”, “c”]; // unshift() adds an element to the start of the array // and returns the new lenght a.shift() "a"; a [“b”, “c”]; // shift() gets the first element and removes it

bc. var a = new Array(“a”, “b”, “c”); var x = new Array(“z”, “x”, “y”); concat(a, x) ["a", "b", "c", "z", "x", "y"]; a.join("-") “a-b-c”; a.reverse() ["c", "b", "a"]; a.slice(1,2) [“b”, “c”];\ a.splice(0, 2, [“m”, “n”, “o”]) == [“m”, “n”, “o”, “c”]; // (yeah, splice is confusing, go read the docs) b.sort() = [“x”, “y”, “z”]; a.toString() "a,b,c" a.join(”,”);

All objects are open-ended hashmaps.

That means that any object in JavaScript will accept new attributes. They are not statically restricted to a class template like in most compiled OO Languages.

So, for example, in a browser context:

bc. var elem = document.getElementsByTagName(“body”)[0]; elem.myData = “anything”;

Just try not to override any of their existing methods or properties, since the resulting behaviour can be unexpected.

Remember the object operators in and delete

The in operator looks for the presence of an attribute (or index) in an object, regardless of it’s value.

bc. var a = {some: “1”, things: false}; “some” in a true; "things" in a true; “other” in a == false;

The delete operator removes an attribute from an object. This is not the same as setting the attribute to null.

bc. var a = {some: “1”, things: false}; “some” in a true; delete a.some; "some" in a false;

The only cases where the in operator returns false is when the attribute never existed or when it was deleted.

Functions

Functions are variables

A function in JavaScript is also a variable that can be copied and used as a pointer to the function.

bc. function test(a) { return a + 1; } var b = test; test(1) == b(1);

And there is the function operator we mentioned in Part I

bc. var test = function(a) {return a + 1;}

This can come handy when defining functions for callbacks or event handlers.

You can do very confusing things with this, like creating one-time functions.

bc (function(){ return 1; })() == 1;

Functions are objects

Yes, they are objects too, so you can add attributes to a function.

bc. function test(a) { return test.data + a; } test.data = “hello ”; test(1) == “hello 1”;

And you can create functions by using the new Function() constructor, but it’s so ugly to write the code as a string that it doesn’t really make sense to even consider using it.

Functions have access to their arguments.

Besides each argument as a local variable, functions also have access to an array called arguments.

bc. function test(a) { return arguments0 };

Which makes it easy to implement functions with dynamic attributes.

Functions can have nested functions.

Any function can have other functions declared inside it. Those inner functions will have access to their containing function local variables.

bc. function test() { var a = “x”; function subtest() { return a + ”!”; } } test() == “x!”;

return subtest();

Some day you will figure out what can you use this for. You might see some about this when we talk about creating your own object classes. In the meantime, it can be helpful to keep your source code clean when you define new functions to be used only inside another function.

The global object

JavaScript has a mysterious but omnipresent global object.

Every JavaScript interpreter provides a global object where “global” variables and functions are stored. You can consider it to be the “context” of the interpreter. However, there is no standard way in the language to access this object.

We’ll use the keyword global in this text, but IT DOES NOT EXIST. We just need some way to describe what we’re talking about.

In Web Browsers, JavaScript uses the window object as the global object. They actually do this by setting an attribute “window” on the global object so that

bc. global.window = global;

Global variables and functions are implemented as properties of this global object

bc. var a = 1; global.a 1;

bc. function test() {...}; global.test(); typeof global.test “function”;

Functions can access their global object using this, or not using anything at all.

The this keyword always points to the object containing the function being executed. So in “global” functions, this points to the global object.

The contents of this is also the “default” variable for a function, so unless you declare a local variable a, you are accessing a on the this object.

bc. // inside a function… a == this.a;

bc. // inside another function var a; a != this.a;

This means, for example, that in a Web Browser, this.window will always point to the window this function was declared on, regardless of what window was the code that called the function.

And of course, this doesn’t apply to functions stored inside other objects.

bc. var a = new Object(); a.test = function() { // something like ‘this.window’ will not work here }

More JavaScript for geeks

Part 1 covers the basics of JavaScript syntax.

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

2 Respuestas a “JavaScript for geeks (Part II)”

  1. link- dijo:
    link
  2. afrael dijo:
    Muy bueno como siempre, no se podia esperar menos. Sin embargo, los quiero en PDF para offline browsing, voy a ver si mañana los copio y los creo en PDF y te los envio, voy a ver, no prometo nada :)

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!