Thursday, July 9, 2020

What are Closures in JavaScript

What are Closures in JavaScript What are Closures in JavaScript How Do They Work? Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript â€" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming How Do They Work? Las t updated on Nov 27,2019 537 Views Sayantini A Data Science Enthusiast with in-hand skills in programming languages such as... A Data Science Enthusiast with in-hand skills in programming languages such as Java Python. Bookmark Become a Certified Professional JavaScript is a function-oriented language that gives a lot of freedom to the user. You can create a function dynamically, copy it to another variable or pass as an argument to another function and call from a different place later. Closures in JavaScript are created every time a function is created, at function creation time. In this article, we will understand closures in the following sequence:Introduction to Closures in JavaScriptPractical ClosuresScope ChainClosure Within a LoopIntroduction to Closures in JavaScriptA closure is a combination of a function bundled together with references to its surrounding state i.e. the lexical environment. In other words, a closure provides you access from an inner function to an ou ter functions scope.Most of the Developers use closures in JavaScript consciously or unconsciously. It provides better control over the code when using them. Also, it is the most frequently asked question during any JavaScript interview.Example:function foo() { var x = 10; function inner(){ return x; } return inner; } var get_func_inner = foo(); console.log(get_func_inner()); console.log(get_func_inner()); console.log(get_func_inner());Output:10 10 10Here, you can access the variable x which is defined in function foo() through function inner() as the later preserves the scope chain of enclosing function at the time of execution of enclosing function. Thus, the inner function knows the value of x through its scope chain. This is how you can use closures in JavaScript.Practical ClosuresClosures allow you to associate the lexical environment with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate the objects properties with one or more methods.Consequently, you can use a closure anywhere that you might normally use an object with only a single method.Example:function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16);The above example is generally attached as a callback: a single function which is executed in response to the event.Scope ChainClosures in JavaScript have three scopes such as:Local ScopeOuter Functions ScopeGlobal ScopeA common mistake is not realizing that, in the case where the outer function is itself a nested function, access to the outer functions scope includes the enclosing scope of the outer function, effectively creating a chain of function scopes.// global scope var x = 10; function sum(a){ return function(b){ return function(c){ // outer functions scope return function(d){ // local scope return a + b + c + d + x; } } } } console.log(sum(1)(2)(3)(4)); // log 20It can also be written without anonymous functions:// global scope var x = 10; function sum(a){ return function sum2(b){ return function sum3(c){ // outer functions scope return function sum4(d){ // local scope return a + b + c + d + x; } } } } var s = sum(1); var s1 = s(2); var s2 = s1(3); var s3 = s2(4); console.log(s3) //log 20In the above example, there is a series of nested functions all of which have access to the outer scope of a function.Thus, you can say that closures have access to all outer function scopes within which they were declared.Closure Within a LoopYou can use closures in JavaScript to store an anonymous function at every index of an array. Lets take an example and see how closures are used within a loop.Example:function outer() { var arr = []; var i; for (i = 0; i 3; i++) { // storing anonymus function arr[i] = function () { return i; } } // returning the array. return arr; } var get_arr = outer(); console.log(get_arr[0]()); console.log(get_arr[1]()); console.log(get_arr[2]());Output:3 3 3 3With this, we have come to the end of our article. I hope you understood how closures in JavaScript works and how they are used to get a better control of the code.Now that you know about Closures in JavaScript, check out the Web Development Certification Trainingby Edureka.Web Development Certification Training willhelp you Learn how to create impressive websites using HTML5, CSS3, Twitter Bootstrap 3, jQuery and Google APIs and deploy it to Amazon Simple Storage Service(S3).Got a question for us? Please mention it in the comments section of Closures in JavaScript and we will get back to you.Recommended videos for you Angular JS Tutorial for Beginners Watch Now Whats New in Angular 4 Angular 4 Features Watch Now Deep Dive into AngularJS Javascript Framework Watch Now AngularJS Develop Responsive Single Page Application Watch Now Web Development Trends and Predictions Watch Now Web Development with HTML5, CSS3 JavaScript Watch Now Animation And Testing In AngularJS Watch Now Are You Riding The AngularJS Wave Yet? Watch Now Angular 4 Tutorial Getting Started With Angular 4 Watch Now Trendy Web Designs using HTML5 Watch Now AngularJS-Superheroic JavaScript MVW Framework Watch Now AngularJS : Superheroic JavaScript MVW Framework Watch Now A Work Day Of A Web Developer Watch Now Angular JS : Develop Responsive Single Page Application Watch NowRecommended blogs for you How To Best Use Advanced HTML Form Attributes? Read Article jQuery Tutorial A Complete Guide For Beginners Read Article What are Closures in JavaScript How Do They Work? Read Article Successful Web Development Career With AngularJS: Bag the best-paying AngularJS Jobs! Read Article How to perform CRUD operations in angularjs? Read Article What is the JavaScript MVC Architecture and How does it Work? Read Article What is AngularJS Bootstrap And How To Use It Practically? Read Article What are the Different Data Types in JavaScript Read Article JavaScript Tut orial for Beginners : A Complete Guide Read Article What are the Advantages and Disadvantages of Angular? Read Article What is a JavaScript Class and how to use it? Read Article How To Implement JavaScript Trim Method? Read Article How to Implement String Length in JavaScript Read Article Unshift JavaScript : Know How to Use Unshift() Method in Array Read Article Everything You Need to Know About NgStyle in Angular 8 Read Article How to submit a form in JavaScript? Read Article How to Upload File in AJAX? Step By Step Guide Read Article How To Best Utilize Audio Tag In HTML? Read Article How to Implement Padding in CSS With Examples Read Article What are HTML Meta Tags? Is it Really Necessary? Read Article Comments 0 Comments Trending Courses in Front End Web Development Angular Certification Training15k Enrolled LearnersWeekendLive Class Reviews 5 (5700)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.