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 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 : Named function expressions demystified

There is always something to lear in JS.

, ,

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>