Notes of Maks Nemisj

Experiments with JavaScript

JavaScript function declaration among the browsers

Yesterday I came across two interesting JavaScript behaviors. They gave me different results based on the browser. The first one was only reproducible in Internet Explorer (IE) and the second one only in Firefox.

First, lets see the IE code:

var get = function() {
    return function bla() {
        alert( bla.property );
    }
}

var fnc = get();
fnc.property = "Hello There!";
fnc();

If you think that this code alerts “Hello There!” you are half right. It does in all browsers, except the IE.

The second one also interesting, this is for the Firefox :

var get = function(flag) {
    if (flag) {
        function it() {
            alert( "Flag is true" );
        }
    } else {
         function it() {
            alert( "Flag is false" );
         }
    }

    it();
};

get( true );

When I typed it, I thought it would alert me “Flag is true”. Well, the problem is, my thoughts were correct, but only for the Firefox browser. In all other browsers it alerts “Flag is false”.

If you had the same thoughts as me, I advice you to read this great article about function declaration: Named function expressions demystified

There is always something to learn in JavaScript.

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.