Understanding Closure in JavaScript

Understanding Closure in JavaScript

This post demonstrates and briefly explains closures in JavaScript

Introduction

This article demonstrates and briefly explains closures. Let’s understand with some definitions mentioned below.

Closure is a computer science term that defines how a function can maintain a record of the environment in which it was called. This means that a function can keep track of the arguments and variables it was initially called with, even when it’s called outside of that scope.

A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain.

In other words, an inner function will always have access to the variables and parameters of its outer function, even after the outer function has returned.

Let’s see this with an example:

//***********Example 1***************//  
function yearsLeftForRetirement(retirementAge) {  
    const message = ' years left for the retirement';  
    return function calcluateYears(currentYear, birthYear) {  
        const yearsLeftForRetirement = retirementAge - (currentYear - birthYear);  
        console.log(yearsLeftForRetirement + message);  
    };  
}  
const birthYear = 1985;  
//Get years left for retirement in India  
const retirementInIndia = yearsLeftForRetirement(62);  
retirementInIndia(new Date().getFullYear(), birthYear);  
//Get years left for retirement in US  
const retirementInUS = yearsLeftForRetirement(65);  
retirementInUS(new Date().getFullYear(), birthYear);  
//Same can also be written as  
yearsLeftForRetirement(65)(new Date().getFullYear(), birthYear);  

Clearly here we can see that the inner function has access to message constant and retirement age parameter which are outside the scope of the inner function (CalculateYears).

Also, the inner function has access to them even after the yearsLeftForRetirement function is called because that is why we are able to log the message in the console.

OUTPUT

A closure gives you access to an outer function’s scope from an inner function.

Usage

  • To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function
  • The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

Some use cases for closures are event handlers, timeouts, intervals, callbacks and keeping variables private within functions.

Let’s see another example,

 //***********Example 2***************//  
const getValue = value => {  
   return {  
      get: () => value  
      };  
   };  
console.log(getValue('This is a test'));  

In the example above, the get() method is defined inside the scope of getValue(), due to which get method gets access to any variable which has been passed into getValue().

So clearly here getValue() is returning an object which has a method called get(), which is here simply returning the value passed to the getValue().

So, if we simply write the below statement.

console.log(getValue('This is a test'));  

The output will look something like.

So, in order to get the value, we need to call it this way.

console.log(getValue('This is a test').get());   

The output will look something like.

Drawbacks of using Closures

The most important thing to consider while using Closures is to look for memory management.

The drawback of using closures without thought is that it could lead to memory leaks. For example- if there are 20 functions which are referencing a common variable, then this variable will exist until all those 20 functions will get garbage collected.

Happy coding!!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript is the programming language of HTML and the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter