Javascript closures and side effects in plain English? (separately)

前端 未结 6 2082
灰色年华
灰色年华 2020-12-05 00:49

I\'ve been reading some JavaScript books and I always hear about closures and side effects. For some reason I can\'t understand what they really are. Can anyone explain to m

6条回答
  •  温柔的废话
    2020-12-05 01:21

    Mainly side effects are the interactions with the outside world from inside of the function. Some examples of the side effects are:- API Calls or HTTP requests, data mutations, Printing to a screen or console, DOM Query/Manipulation. Example :

    var a = 12
    function addTwo(){
       a = a + 2; // side-effect
    
    }
    addTwo()

    Closures

    According to MDN,

    A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

    Example :

    function outer(){
      var a = 12; // Declared in outer function 
      function addTwo(){ // closure function
        a = a + 2; // acessing outer function property
        console.log(a)
      }
      addTwo();
     }
     outer()

提交回复
热议问题