Home > Web Front-end > JS Tutorial > Rick and Morty and Clorsures: what do these things have in common?

Rick and Morty and Clorsures: what do these things have in common?

Susan Sarandon
Release: 2024-10-24 06:36:02
Original
764 people have browsed it

Rick and Morty e Clorsures: o que essas coisas tem em comum?

So, how are you? I hope so!

I was trying to solve some programming problems in Leetcode and in one of the challenges I came across a very important concept in programming that many people have difficulty understanding.

So I decided to write here trying to explain in the best possible way how closures work in JavaScript. Come with me!

The Problem

I was working on a challenge called "Counter" where I needed to create a counter function that initially returned the integer n and, with each subsequent call, returned 1 unit more than the previous value. For example:

  • counter(10) returns 10
  • counter() (called again) returns 11
  • counter() (called again) returns 12

The problem gives some hints, including that we can use functions that return other functions.

This is the concept of closures. So I followed the tip and went this route. Here is the solution I came up with:

var createCounter = function (n) {
    let contador = n;
    return function () {
        resultado = contador;
        contador++
        return resultado;
    };
};
Copy after login

This code defines a function called createCounter that returns another function (closure), capable of storing and manipulating a local variable (in this case, the counter).

  • The counter starts with the value of n passed when you call createCounter().
  • Each time you execute the function, the inner (return) function accesses the current counter value, returns it, and then increments it.
  • This allows the counter to "remember" where it left off, thanks to the closure.

This last step is where we realize the true power of a closure. A closure is when a function returns another function that has access to external variables and maintains its state between calls. It's like having a little "hide" inside my function where I can store information and access it later.

And where does Rick and Morty fit into this story?

The Rick and Morty series plays with interdimensional travel, other civilizations and criticizes and proposes reflections on many existential questions for human beings.

If you don't know the series, here's a brief summary: Rick Sanchez, the main character of the work, is a scientist who develops all kinds of crazy technology and usually takes his grandson Morty on his adventures. One of the old man's most famous inventions is the interdimensional portal, which allows him to travel between realities and dimensions. To find out more, you'll have to watch the series (laughs).

What are you getting at, Neilton?

Well, imagine that Rick develops an interdimensional backpack for Morty, which gives access to a specific dimension. In this dimension, Rick places some important tools. Morty can carry the backpack anywhere — whether to school, for a walk, or even for an intergalactic trip — and, even away from Rick, he will still have access to everything stored there.

The best part? Morty can open the backpack and take out the tools whenever he wants to use or even modify what's inside. And no matter where it is, what was stored remains accessible.

And how does this example connect with closures?

  • Rick is the external function, which creates the scope (dimension) and the variables (tools) that can be accessed later.
  • Morty with the backpack represents the internal function, which can access and modify the variables of the external function.
  • The dimension represents the lexical scope of the external function, that is, the variables that were created within the external function and are accessed by the internal function, even after the external function is executed.
  • The fact that Morty can access things in the dimension from anywhere reflects the scope persistence: even after the outer function is finished, the inner function maintains access to the variables in the original scope.

Closures are powerful resources in programming. Among the main advantages of using closures, I highlight encapsulation and memoization. Encapsulation because the value can only be accessed through the closure (internal function) and memoization because of the ability to preserve the value of variables between calls.


AI-generated image: https://designer.microsoft.com/image-creator?scenario=texttoimage

Prompt: Generate an image where Rick from Rick and Morty is handing Morty a glowing dimensional pocket device. Morty is pulling objects out of the pocket, like tools and gadgets, while Rick casually explains the mechanics of it in a lab. The pocket represents a closure, containing floating items that Morty can keep accessing, even after Rick steps away.


Conclusion

So, did you understand what closures are and how important they are in programming? Sometimes I wish I had a backpack like Morty's to store useful things or simply to teleport to another dimension (laughs).

If you liked the content, comment and share, go! Please give me strength if you think this article will help others.

See you next time!

The above is the detailed content of Rick and Morty and Clorsures: what do these things have in common?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template