0

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)?

6
  • Well … it is impossible to call fun2 in the first example. Commented Apr 13, 2017 at 9:02
  • Second example is better for re-usability. Now you can call function fun2 again in other functions. Commented Apr 13, 2017 at 9:03
  • @Quentin Impossible from outside fun1, inside it's not. Commented Apr 13, 2017 at 9:03
  • @Arg0n — It isn't called from inside fun1 Commented Apr 13, 2017 at 9:07
  • What you do in the first case is an example of closure. Read about JavaScript closures and you should be clear about it Commented Apr 13, 2017 at 9:12

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.