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