Struggling to grasp the concept of closures?

Exploring the concept of closure led me to conduct some experiments, and a specific problem caught my attention.

Upon running the following code:

    var hello;
    hello = 'abc';
    test();
    function test() {
       console.log(hello);
    }

Output: 'abc'

However, upon adding another variable declaration within the function, the output changes:

    var hello;
    hello = 'abc';
    test();
    function test() {
       console.log(hello);
       var hello = 'xyz';
    }

Output: undefined

I find it puzzling why this behavior occurs. When the test() function is executed, it should log the global variable 'hello' before any declaration inside the test() function has been processed. Therefore, it seems unexpected that the result is undefined.

Any insights would be greatly appreciated.

Answer №1

The reason behind the behavior you are experiencing with the variable hello inside your function test is due to something called hoisting. This means that before your code runs, the variable declarations are moved to the top of their containing function or global scope.

function test() {
   console.log(hello);
   var hello = 'xyz';
}

This block of code is actually interpreted as:

function test() {
   var hello;
   console.log(hello);
   hello = 'xyz';
}

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

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

How to retrieve data from a JavaScript array in a separate JavaScript file

In my checklistRequest.js file, I populate an array and then try to access it in my Termine_1s.html file, which includes JavaScript code. Although I can access the array, when I attempt to iterate through it, only single digits are returned instead of stri ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

What is the best way to prevent an HTML form from being submitted when a user is not logged in, but still allow submission when the user is signed

One of the requirements for users of my application is to be signed in before they can submit form information. Upon clicking on the submit button, my jQuery script verifies if the user is already signed in. If the user is not signed in, an error message ...

Exploring AngularJS Navigation in Windows 8 App Store Applications

Hello, I recently started learning about developing Windows Store apps. I found a way to incorporate AngularJS into my Windows 8 store app by making some adjustments in the AngularJS library. However, I'm now struggling with implementing AngularJS rou ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Sending information to Bootstrap 4 modal

Can you help me insert the variable into this link? <a href="#edit_task" data-toggle="modal"><i class="fas fa-edit fa-lg fa-fw"></i></a> This is my modal: <div class="modal fade" id=" ...

When using the * selector in jQuery on Chrome, it targets and selects scrollbars

Here's the code I'm currently using: $("*").bind("mousedown.sg", { 'self':this }, this.sgMousedown); This code binds an event listener to all elements on the page, and it functions properly in most browsers except for Chrome. In Chrom ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Tips for preventing users from entering special characters into input fields

How can I prevent users from entering the # character into an HTML input field? I attempted to use the pattern attribute, but it does not seem to be effective. I included this pattern in my input element: pattern="[^-#]+" I expected that this would disa ...

You cannot nest a map function within another map function in React

Having some trouble applying the map function in HTML using React. Below is the code snippet: response = [ data : { name: 'john', title: 'john doe', images: { slider: { desktop: 'link1', mo ...

place an image next to a div element

Currently, I have a table-like structure with two columns that I am struggling to make mobile responsive. Take a look at the code snippet below: setTimeout(function() { odometer.innerHTML = '1925' }) .fiftyFiftySection { back ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below: for ( let key in imageFileObject ) { const imageFile = imageFileObject[key] dispatch('get_signed_request', ima ...

Transforming a file with a node module that lacks a .js class into a browseable format

I am currently working on browserifying my module. One of the dependencies I have is on this https://www.npmjs.com/package/chilkat_win32. It is present in my node_modules folder and here is how the structure looks: https://i.stack.imgur.com/uw9Pg.png Upo ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Discover additional and subtract options

I am trying to implement a "See more" and "See less" button functionality for my list items inside an unordered list using the code below, but it is not working as intended. $(document).ready(function() { var list = $(".partners__ul li"); var numTo ...

Guide on how to trigger the opening of a side panel with a button click in Vue.js

Embarking on my first Vue app development journey, I find myself in need of guidance on how to trigger the opening of a panel by clicking a button within the header. Starting off with a simple HTML template, my goal is to add some interactivity upon click ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...