hjalpmig
hjalpmig

Reputation: 702

Javascript - Difference between function declarations

I've just started developing in Javascript, and have been reading up on scope and execution context. I was wondering if there's a difference between this:

function fun1 () {
    var x = 1;

    function fun2 () {
         x = x*2;
         alert(x);
    }
}

and:

function fun1 () {
    var x = 1;
    fun2(x);
}

function fun2 (x) {
    x = x*2;
    alert(x);
}

Would there be reasons to use one over the other? Do they have any performance/security implications (or other unexpected implications for beginner JS developers)?

Upvotes: 0

Views: 72

Answers (3)

Muhammad Qasim
Muhammad Qasim

Reputation: 1712

If we talk about your first approach, it is not possible to call fun2 because you have enclosed it within fun1 and its scope is local. However you can ammend your fun1 to call fun2 as follows:

 var fun1 = (function(){

    var x = 1;

    var fun2 = function(){
         x = x*2;
         alert(x);
    };

    return {
      fun2: fun2
    }

 })();

The above return statement will make your fun2 as public scope that you can call it with the fun1 object as follows:

  fun1.fun2();

Please note that the x variable is private and only accessible within fun1 function. If you need to access it using fun1.x, you will have to return it in your fun1 as I've returned fun2.

This is called modular or enclosed pattern. By this we can achieve encapsulation.

IF we talk about your second approach i.e pretty simple, your fun1 will call fun2 . I hope, it clears the concept.

Upvotes: 0

m1kael
m1kael

Reputation: 2851

In Javascript scope is defined by the enclosing function. That is, code defined within a function is not visible outside the function.

So, in your 1st example, func2 in defined inside func1, and thus is visible only inside func1.

In your 2nd example, it is defined in the global scope (the window object, when running in a browser), and as such is callable from anywhere, just like func1.

Upvotes: 0

MysterX
MysterX

Reputation: 2368

The main difference is that at the first case fun2 will be available only in the fun1 scope. At the second case both functions will be available at scope, where their definition is

Upvotes: 2

Related Questions