Skip to main content

Javascript: Closure

CLOSURE

A closure is an inner function that has access to the outer function's variables. Obviously, the inner function has access to its own function scope ('local' variables defined between its braces), and it has access to the outer function's variables, which are Closures, and it has access to the global variables.

Using closure we can use scope even after outer function return
closure function A closure is an inner function that has access to:

  1. its own scope
  2. its argument
Simple Example 1:
function outer(){
       var a = "a is var of outer function";
       document.write(a);

      function inner(){
           var b = "b is var of inner function";

           document.write(b);
           document.write(a); //closure function
}
      inner();
     document.write(b); //outer function, no print
}

outer();

Advantage:
  • Inner function can access outer global, local in inner function
  • Outer function can't access inner function.
Another Example 2: 



function welcome(name){
var name = 'nepal';


function getName(){
return name;
}
function setName(newName){
name = newName;
}


return{
takeName: getName,
resetName: setName
}
}


var a = welcome('sinuna');
console.log('welcome', a);
var getNameResult = a.takeName();
console.log('getNameResult ', getNameResult);


//change inside scope
var b = a.resetName('USA');
console.log(b);


var getNewResult = a.takeName();
console.log('getNameResult 2', getNewResult);


Explanation:
var greetMsg = 'welcome '; global scope
function welcome(name){
     var textMsg = 'How can I serve you?';

//location is closure function and its outer function is welcome
function location(loc){
      function sayHello(){
}
//sayHello is closure function and its outer function is location. sayHello can access name ma ako, location ma ako and its own
var to = 'to';
return greetMsg + ' ' + name + ' ' + to + ' ' + loc + ' ' + textMsg;
//closure function

//greetMsg->global scope access, name->outerfunction access, to->own scope, loc->own argument, textMsg->parent function parameter
function sayHi(){
    //sayHello dont give access, sayHello is in location scope
} //sayHi is closure function and its outer function is welcome

var innerFn = location('ktm'); //return location('biratnagar') same 
console.log('innerFn >>', innerFn);
return location;
}

var welcomeFn = welcome('cnuna');
console.log('It will be undefined', welcomeFn); undefined
var callInnerFn = welcomeFn('Pokhara');


//Output: while calling welcome, we need to add value in return, eg. adding innerFn result in return, same value will be shown in outer function like in innerFn.

console.log('inner fn result', callInnerFn);

end block day 1 and day 2 course included IMP

Example: 
function welcome(name){
return 'welcome to broadway ' + name;
return 3044392;
return {key:value};
return true;
return [];

}
var sinuna = 'cnuna';

console.log(welcome(sinuna));

mutable and immutable
mutable: if the state of datatype changed after they are declared, they are a mutable property

immutable: the state will not be changed after declaration

array and Object
array and object are mutable

string number and boolean are immutable

mutable example
var fruits = ['apple', 'grape', 'orange'];
console.log('fruits before insertion', fruits);

var nextFruits = fruits;
nextFruits.push('banana');push le value add garcha
console.log('fruits after insertion', fruits);
console.log('nextFruits after insertion', nextFruits);

#immutable
var a = 'I am here';
var b = a;
b = 'hello';
console.log(a);
console.log(b);

Note: 

The argument is the actual value of this variable that gets passed to function. its outer function parameter: A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. Parameter is variable in the declaration of function
global scope. closure is function and scope.

SDLC (Software development life cycle)
1. waterfall model : follows every steps serially
problem definition, identification, design, implementation, support, maintenance
once we are into step, we can not go back
traditional approach
if you want to go back again, you need to start it from begining

Lets relate waterfall model into js scope waterfall model ->top to bottom

Comments

Popular posts from this blog

Deploy react app on digitalocean using nginx

Source:  https://www.learnwithjason.dev/blog/deploy-nodejs-ssl-digitalocean/ Source:  https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04 Source:  https://www.youtube.com/watch?v=vRrhQwNixlc https://www.youtube.com/watch?v=pyxXCwgWdMw https://dev.to/xarala221/the-easiest-way-to-deploy-a-react-web-application-2l8a 1. Create a new droplet on DigitalOcean. Choose the $5/month option with Ubuntu 16.04.1 x64. Select a region closest to your users. 2. Finally, add your SSH key and ls -la ~/.ssh # This copies the key so you can paste with command + V pbcopy < ~/.ssh/id_rsa.pub # This prints it in the command line for manual copying cat ~/.ssh/id_rsa.pub   3.  Add your SSH key to the droplet Click “Add SSH Key” to save it, then make sure it’s selected, name your droplet, and hit the big “Create” button to get your server online. Your n...

Github Tutorial

GitHub brings together the world's largest community of developers to discover, share, and build better software. Delivered through software as a service(SAAS) business model 2008 by linus (Owner: Microsoft)  #Create New Repository in Github New Repository Add Repository Name and description Public / Private, initialize this repo with Read Me Create repository create a new repository on the command line echo "#test" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/sinuna/test.git git push -u origin master …or push an existing repository from the command line git remote add origin https://github.com/sinuna/firstRepository.git git push -u origin master …or import code from another repository You can initialize this repository with code from a Subversion, Mercurial, or TFS project. Initialize Repo $ git init Clone Repo $ git clone https://github.com...

NodeJS: Request and Respose Objects

# req Objects - req - req.body, req.queries, req.validationerrors - res.headers, req.users, req.file, req.assert - req.params, req.checkbody #res Objects - res.send, res.end, res.json, res.render, res.status, res.sendStatus # - .limit(4) //limit only upto 4 docs - skips(3) //skip first 3 docs - exe //query build and then execute, it is also callback function of mongoose. - sort({_id: -1}) //for decending order - populate('userId') //populating data inside the reference.