Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct?

Here is an example code snippet.

(function() {
  console.log('console.log#1 ' + globalString); // globalString function 

})();

var globalString = 'I\'m globalString variable';

(function() {
  console.log('console.log#2 ' + globalString); // string
})();

function globalString() {
  console.log('I\'m globalString function');
}

The output of this code looks like this:

console.log#1 function globalString ()
{
    console.log ( 'I\'m globalString function' );
}

console.log#2 I'm globalString variable

If a function definition overrides a variable, then console.log#2 prints the globalString function. I am unsure about how variables and functions are hoisted. Please provide some guidance.

Answer №1

When you declare a function (such as globalString()), it is hoisted by the interpreter. Essentially, your code is seen as follows:

var globalString = function globalString() {
  console.log('I\'m globalString function');
};

(function() {
  console.log('console.log#1 ' + globalString); // globalString function 
})();

globalString = 'I\'m globalString variable';

(function() {
  console.log('console.log#2 ' + globalString); // string
})();

Prior to the first IIFE executing, globalString refers to the function. After the initial IIFE runs but before the second IIFE executes, globalString is then assigned to the string value. It's important to note that only the variable name is hoisted, not ordinary assignments.

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

Uncovering the Depths of React Native Background Services

While using Firebase, I want my app to push notifications when new data is added to the database while it's in the background. Currently, I've implemented the following code: message.on('child_added', function(data) { pushNotificatio ...

for each and every object, execute the asynchronous function

I have a scenario where I need to loop through objects, call an async method ("search") with a callback, and then write the results (resultSet) to a JSON file once all objects are processed. The issue I'm facing is that the writeFile function is execu ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...

Having trouble getting a Mocha test to display two decimal places in Javascript? Both Big and Decimal libraries are causing issues

After encountering an error with the Big library, I decided to switch to Decimal. First, I ran npm install Decimal Then, I added the following code: const Decimal = require('decimal'); Even after following the examples, my comparison returned { ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

Activate a Dropdown Menu by Clicking in a React Application

I have a collapsible feature where you can click to expand or collapse a dropdown. Currently, the dropdown can only be clicked on where the radio button is located. I want the entire area to be clickable so that users can choose the dropdown by clicking an ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...

Implementing a clickable image using an anchor tag in JavaScript

I need to enhance my image tag in JQuery by adding an anchor tag alongside it. How can I accomplish this using JavaScript? Here is what I attempted: var imgg = document.createElement("img"); imgg.className='myclass'; $( ".myclass" ).add( "<a ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Utilize jQuery script on every single element

Is there a way to implement a jquery function on elements that are dynamically loaded via ajax? <span class="h">Test</span><br /><br /> <span class="h">Test</span><br /><br /> <span class="h">Test</ ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

What is the method for locating all anchor tags "In General" within the inner HTML of a div using XPath?

This query is related to a discussion on anchor tags in this thread. I am interested in identifying all anchor tags within a string. The scenario provided below is similar to the aforementioned issue, however, I aim to accomplish this using xpath and angu ...

Using jQuery to trigger an action when a user clicks on a regular audio element

Is there a way to detect a click on the default audio element of a browser using jQuery? I'm having trouble getting it to work in Chrome. $('audio').click(function(){ alert("You have clicked on an audio player"); }); <script ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Is there an issue with my JavaScript append method?

Within the following method, an object named o gets appended to a list of objects called qs. The section that is commented out seems to be causing issues, while the uncommented section is functional. What could possibly be wrong with the commented part? on ...

Troubleshooting Async Issues in Node.js

I am encountering an issue with my node.js app structure, which is as follows: async.forever( function(callback) { async.series([ function(callback) { SomeFunction1(function(err, results) { if (err) callback(err); ...

What is the most effective method for transferring data to a concealed input field?

I currently have a webpage with dual forms - one on the main page and another within a Bootstrap modal. The primary form includes fields like "Neck, Chest, Waist," while the modal's form only has an email field. To streamline the submission process, ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...