Blog of Jeff A blog about programming and random other things.

23Jun/09link

“Brief” Guide to JavaScript – Part 3

Before I continue this article, I'll emphasize that I'm open to comments and corrections. I apologize if I don’t get back to you, I have a job with a long commute times (~2 hours), but I do read them. And now back to your program…


Global Scope

Variable assignments, like those from above, are stored in the global scope, that is, they can be accessed from anywhere in your code. For browsers, all the variables are automatically assigned to the window object. So if we declared the variables above, we can access them like this:

alert(myvariable); // works
alert(window.myvariable); // also works

Alert is a browser-provided function to display a simple message box with the given value. Like the variables, alert is in global scope and resides in the window object namespace. The window variable is an object provided by browsers which usually contain browser-specific functionality (such as alert).

A simple dialog created using alert.

Functions

Programmers are lazy, and retyping / copy & pasting code. It's too much effort. Doing so also makes code less flexible when we need to change something because then we need to change it for all the occurrences. That's why programmers like functions.

Since JavaScript is a functional language, functions are treated just like other data types (string, float, integer, etc.). An example function definition:

function tell(){
    alert("I'm telling on you...");
}

Like var, function definitions are put into the smallest scope possible. In this case, the global scope. We can run this function after we declared it by:

tell(); // runs alert("I'm telling on you...");
tell_copy = tell;
tell_copy(); // does the same thing as tell() above
window.tell(); // also works

Parameters

Functions, like the mathematical kinds, can accept extra parameters. This is done in the function declaration:

function say(msg){
   alert(msg);
}
say('hello world');

This provides the ability to customize what message we want to put. In reality, this is just an alias to the alert function. You can have more parameters, separated by commas.

function print_values(x, y){
    alert(x);
    alert(y);
}
print_values(500, 1200);

Returning Values

Mathematical functions return a value given. Programmatic functions can do the same. This is done with the return keyword.

function add(x, y){
    return x + y;
}
var sum = add(50, 20); // sum stores 70

Scoping

Another key attribute of functions is that they provide their own scope. I always find examples as the best way to explain things:

var globalvar = 'hello';
function myfunc(){
    var funcvar = 'world';
    anotherglobalvar = 'oh?';
    // globalvar, anotherglobalvar, & funcvar are defined here.
}
// funcvar is not defined here. but globalvar = 'hello' and anotherglobalvar = 'oh?'

As you can see, scopes help prevent us from stepping over ourselves all the time, but still allow access to variables outside of the scope. Which is pretty handy. We also see the side effect of not using var. Inside scopes, excluding the var declares the variable in the global scope. 99% of the time, this isn't what we want, so (to repeat again) it's best to use var.

You may say now, why can't I just remove the var keyword when I'm defining global variables? It's a matter of good practice (which seems to always fall on deaf ears of new programmers).

When you, or someone else, reads the code, it's easier to see variable assignment with a var and see: Okay, this person is defining a new variable, as opposed to just assigning a variable (which can make it hard to determine when a variable is created).

It's worth noting that curly braces in JavaScript do not provide scope:

if(true){
    var hello = 'world';
}
alert('hello');

This code runs just fine since the variable hello persists after the block ends. Likewise:

var j = 256;
for(var i=0; i<10; i++){
    var j = i * i;
}
alert(i); // outputs 10
alert(j); // outputs 81 (9 * 9)

Anonymous Functions

Functions are data types. And like any other data type, it doesn't need to be binded to a variable directly. This is accomplished simply by excluding the function name.

function() {
    alert('hello world');
}

At first glance, this isn't feature in JavaScript doesn't seem practical at all. And it isn't. We can't call this function. Obviously this isn't the correct way to use anonymous functions. We could replicate the same behavior as our previous function definitions by assigning it to a variable.

var tell = function(){
    alert('Tattle Tailing on You');
}
tell(); // call the function

It still doesn't seem very useful to have anonymous functions in this example. Let's see a more likely scenario:

function too_large(num1, num2, func){
    if (num1 + num2 > 10){
        func();
    }
}

This defines a function which accepts three parameters: two numeric values and one function. If the sum of both numbers is greater than 10, the passed function is called. We can define the function and then pass the function to too_large by specifying the name:

function mycallback(){ /* code */ }
too_large(5, 15, mycallback);

But that's the lousy method. We're cluttering our current scope with unnecessary variables that we use only once. Instead, we can use an anonymous function:

too_large(5, 15, function(){ /* code */ });

Many JavaScript frameworks utilize callback functions to allow framework users to plug in functionality in portions of framework code. You can also utilize it on events, special triggers that browsers fire, such as the window is resized, or the user types in something, etc.

Warning: anonymous functions shouldn't always be used willy-nilly, mostly due to performance issues. For example:

for(var i=0; i<5000; i++){
    (function(x, y){return x + y;})(5, 2);
}

Yes it's another useless function, but in each iteration of the loop, the function is first generate before being called. Not the best of things where as:

function add(x, y){return x + y;}
for(var i=0; i<5000; i++){
    add(5, 2);
}

This is faster than the previous since the function is only created once. Anonymous functions are powerful, but with great power comes great responsibility.

Don't worry, we'll talk more about anonymous functions in subsequent topics.

Edit: Part 4 is available.


That’ll wrap it up this week. We’ll cover the more advanced data types: Arrays and Objects, next week.

  • Share/Bookmark
blog comments powered by Disqus

Recent Posts

Topics

Archives

Following

Links