Is there closure in this function over this block?

Exploring the concept of closures, I decided to enclose a function within a block instead of another function. Knowing that functions are not block-scoped and are hoisted outside of the block, I initially thought it wouldn't have access to the block's scope. Surprisingly, the function was able to return the block-scoped variable. Could this indicate that the function is acting as a closure?

{
   let a = 'hi'
   function test() {
      return a
   }
}
test() // hi

Answer №1

According to the definition provided by Wikipedia, this situation could be considered a closure:

A closure in programming is essentially a record that contains a function along with its associated environment. This environment includes a mapping of every free variable within the function (variables used locally but defined outside of it) to the specific values or references they had when the closure was created. Unlike a regular function, a closure permits access to these variables through copies of their values or references, even when the function is called outside of its original scope.

In the function test, the variable a is a free variable - utilized by the function without being internally defined. When the function is called outside of its block, it retains the value assigned to a. Therefore, the essential characteristics of a closure, as per the Wikipedia definition, are met here.

Typically, closures involve defining a function within a certain environment and then exposing it by linking the function object to a name with broader reach. However, due to JavaScript's treatment of function declarations inside blocks, a similar effect is achieved in this scenario. While the function isn't explicitly exported, it still exhibits closure-like behavior thanks to how JavaScript handles block-scoped functions. Despite the absence of an explicit export mechanism, the set-up resembles a closure.

If you were to write:

{
   let a = 'hi'
   let test = () => a
}
test()

An error would occur. On the other hand, the following snippet works:

let b;
{
   let a = 'hi'
   let test = () => a
   b = test
}
b() // "hi"

Therefore, the block essentially acts as a non-local environment capable of capturing variables. In essence, it may be acceptable to refer to this setup as a closure since it behaves like one, despite deriving from a pre-ECMAScript 2015 implementation that allowed relatively flexible handling of function declarations within blocks. If it resembles a duck, it might as well be one.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

Is your jQuery search scope correctly restricted?

Upon coming across this code snippet, I can't help but wonder if it's merely limiting the scope or selecting both elements simultaneously. container = jQuery("#test", parent.document); jQuery("param[name=scale]", another.object) Would anyone b ...

How come my CodeMirror's height is not adjusting with the CSS changes?

I have implemented CodeMirror to display a JSON object within a simple div: <codemirror v-model="codeToPrint" class="CodeMirror" :options="cmOptions"/> Shown below are the configuration options I am using : cmOptions: { ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Errors Arise when Using jQuery UI Dialog with Greasemonkey

Encountering a peculiar error whenever attempting to create a dialog using Greasemonkey... I suspect it may be related to the constraints of XPCNativeWrapper, though I can't be certain. Thus far, none of the fundamental jQuery functions I've uti ...

Tips for Passing Parameters to Vuex mapActions correctly:Executing mapActions in Vuex requires a specific

I am facing an issue with my ProjectPage.vue where I display project issues in a v-data-table. The projects are fetched from a server API call in the sidebar and displayed there. Once I select a project, I want to use its id to retrieve its corresponding i ...

Convert the HTML element from a div to an unordered list (ul) with the help

i am fresh to jquery i would like all divs with these classes turned into unformatted lists : .view-content -----> 'ul' .view-row ----> 'li' .view-organigramme-departements ---> '<ul><li></li></ul&g ...

What is the best way to transfer a row value from one table to another and then reinsert it back into the original table

I attempted to transfer a row value from one table to another and then back to the original table, but unfortunately, I was unable to find a solution. $('#one tbody tr td input.checkbox').click(function() { if ($(this).attr('checked&apo ...

What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need. ...

What is the best way to utilize a forEach method or other array methods on arrays within objects in Javascript?

I'm currently exploring the use of modern array methods on arrays, but I'm curious if there's a way to apply these methods to objects that contain arrays? If not, would it be more efficient to store the entire object as an array instead? va ...

The masonry plugin overlays images on top of each other

I have gone through similar questions but haven't found anything that applies to my specific case. Following an ajax call, I am adding li elements to a ul $.ajax({ url: 'do_load_gallery.php?load=all' }).done(function(result) { ...

Please explain the purpose of the .forEach statements listed below

Describe the functionality of the two forEach loops provided in the code snippet below. Also, is 'col' a predefined property for arrays? var width = data.length, height = data[0].length; data.forEach(function(col){ col.forEach(function(v ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

The utilization of Ajax requests within the RESTful client is integral to enhancing

Working with a Java RESTful service alongside the consuming client involves data transmission in JSON format. I need to discuss the implementation of 2 requests in the consuming RESTful client. When a button is clicked, a new entity called WalletInfo is g ...

Resolving the issue of multiple instances of React within a single application

I'm currently working on a React module in my local environment. To link the module, I am using npm link. Although the module is being imported successfully, the hooks inside the module are failing with the following error message: Invalid hook call ...

Is it possible to adjust the width of the comment box on the Facebook "Like" button?

Is there a way to set the width of the comment box that appears after clicking the Facebook "Like" button? I know how to adjust the width of the button itself and related content, but can't find any options for the comment box: I've tried overri ...

Unwillingness of Ajax to accept Names containing apostrophes as a parameter

$(".loadingPnl").removeClass('hdn'); var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/S ...

Conflicts with FullCalendar - Dealing with Popovers and Over

I am currently using FullCalendar v6 with the resourceTimeGridDay feature. Within the 'eventDidMount' event render hook, I have implemented a JS function to display popovers on each event for showing event details. The popover is set to appear o ...