beyond applications and software

JavaScript summed up #1: Functions

PREFACE: This is the first post in a series of posts about JavaScript. There’ll be roughly one post per week in the next couple of weeks (don’t ask me, yet, how many weeks I’m going to hang in there – a couple, at least! ;-) .
The goal is to give a thorough overview of some important core aspects of the language – ranging from building blocks like closures to best practices like unit testing.
Honor to whom honor is due – I’ve not invented these concepts and best practices but learned them from some of the best – most notably folks like John Resig or Douglas Crockford.

The first post is about the concepts of “functions” in JavaScript.

NOTE: In a lot of examples, you will see the expression “console.log(…)”. This causes Firebug to output something on its console. So please have the Firebug plugin for Mozilla Firefox ready when you’re playing with the code.

==============

Functions are a core part of JavaScript. Admittedly, functions are a core part of almost every language. But since JavaScript doesn’t have the classic implementation of classes (more on that in a later post), functions become even more important.

First of all it’s important to know that functions are indeed objects in JavaScript. Because they’re objects, quite a few very JavaScriptish things are possible – that might not be common in other languages.

  • Functions can be stored in variables
    var myFunction = function(){
        alert("Hello world");
    };
  • Functions can return functions
    var my2ndFunction = function(){
        return myFunction;
    };
  • Functions can be arguments to other functions
    var alertThroughFunctionArg = function(arg){
        arg();
    };
    var argFunction = function(){
        alert("Number 4");
    };
    alertThroughFunctionArg(argFunction);
    // ===> "Number 4"
  • Functions can have properties
    This might seem a little strange. A function that has properties?? Yes, you’re right. If you remember that a function is „just“ an object, it sounds reasonable that a function can have properties.

    function calledFunction(){
        calledFunction.called += 1;
    };
    calledFunction.called = 0;
    
    calledFunction();
    calledFunction();
    calledFunction();
    console.log(calledFunction.called);
    // ===> 3
  • Functions have a prototype attribute (more on that in a later post)

„arguments“ variable

Every function has a variable called „arguments“.  It’s a array-like collection of all the arguments the function has received. „Array-like“ because you can access its items, but not manipulate it. It can be used to implement what’s known as „function overloading“ in other languages.

„length“ property

There’s another freeby regarding functions: the length property, which also every function has. It contains the number of expected (defined arguments in the function signature -  not the number of really passed arguments when called!).

function lengthFunction(a, b, c){
    console.log(lengthFunction.length);
};

Calling lengthFunction would show „3“ in Firebug.

return value

Every function has a return value. Whether you’re explicitly stating „return“ or not. If you’re not returning an explicit value, „undefined“ is returned. This is similar to what is delivered to the function body, if a parameter wasn’t provided at all at call time – „undefined“.

scope

Unlike other C-syntaxed languages, JavaScript has no „block-scope“. Variables are visible inside the function where they’re defined. If you define them inside of a block, like an if-statement, they continue to be visible even if the block is left. So, JavaScript only cares about function-scope, there’s no block-scope.

Share this:
  • Print
  • email
  • PDF
  • Twitter
  • Digg
  • del.icio.us
  • MisterWong
  • StumbleUpon
  • Facebook
  • Netvibes
  • Google Bookmarks
  • FriendFeed
  • Mixx
  • Live
  • Ping.fm
  • Technorati
  • Yigg

7 comments

1 zorg { 08.07.09 at 11:38 am }

recapitulated ?

2 Dan { 08.07.09 at 12:02 pm }

Hi Tobias,
Interesting article!
Dan
(”Recapulated” – should it not be “recapitulated”?)

3 Tobias Günther { 08.07.09 at 12:14 pm }

Hi Dan and Zorg,
oops, you’re absolutely right… That’s what you get when you’re trying to sound clever in a language you’re not a native speaker in ;-)
Thanks for the hint, I updated it!

4 JavaScript recapulated #1: Functions — puremedia { 08.07.09 at 12:45 pm }

[...] the original post here:  JavaScript recapulated #1: Functions — puremedia SHARETHIS.addEntry({ title: "JavaScript recapulated #1: Functions — puremedia", url: [...]

5 t3n-Linktipps: WP-Theme aufpeppen, JavaScript-Kurs, Britische Armee twittert, OpenOffice 3.1.1 und Android oder iPhone? » t3n Magazin { 08.10.09 at 3:58 pm }

[...] Die Web-Entwickler von puremedia haben aktuell auf ihrem Blog eine Artikelserie zum Einstieg in JavaScript gestartet. Erster Themenkomplex: Functions. [...]

6 Markus Giesen { 08.13.09 at 6:20 am }

Nice one, but maybe add the information for “really” “really” new JS users that they need to have Firefox+Firebug and link to it?
Beside that. Nice article, waiting for more :)

7 JavaScript summed up #7: Dynamic code — puremedia { 09.21.09 at 10:19 am }

[...] or remove functions dynamically at runtime. Since functions are just objects in JavaScript (see my previous post on functions), you could just add a new one like [...]

Leave a Comment