What is causing this JavaScript function to output '2'?

Recently, I came across an unusual JavaScript function:

(function f(){
    function f(){ return 1; }
    return f();
    function f(){ return 2; }
})();

To my surprise, it returns 2 instead of crashing the browsers as expected due to recursion.

Curious if anyone can shed light on this unexpected behavior.

Answer №1

When function declarations are hoisted, the code ends up looking like this:

(function f() {
    function f() { return 1; }
    function f() { return 2; }
    return f();
})();

This can also be represented as:

(function f() {
    var f = function f() { return 1; };
    var f = function f() { return 2; };
    return f();
})();

which is essentially:

(function f() {
    var f = function f() { return 1; };
    f = function f() { return 2; };
    return f();
})();

This further simplifies to:

(function f() {
    var f = function f() { return 2; };
    return f();
})();

Ultimately, the f in the more specific scope takes precedence over the outer 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

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

Utilizing AJAX to fetch and retrieve a JSON array

Check out the javascript code below: var formSerializedData = $('form#registration-form').serialize(); $.post( '<?php echo $this->url('/register', 'do_register')?>', function(response) { alert(response); } ...

Displaying exclusively distinct values in the selection box/dropdown menu

My goal is to retrieve data from the SQL server database and populate the corresponding fields on the frontend. While I am able to fetch the data, some fields in the response contain duplicate values in the dropdown menu. Here is an example of how my Compo ...

"Mastering the art of event delegation: A guide to effectively engaging with various

I have data that is generated dynamically, as shown in the snippet below: const resultsDiv = document.getElementById("results"); const getList = document.getElementById("example"); document.querySelector(".container").addEventListener("click", function ...

What is the proper file format for a form action in CSS?

What I Currently Have: In my Index.html file, there are a total of 4 form elements including text fields and a dropdown. Upon submission by the user, the data is processed in confirm.html using a separate JavaScript file for formatting before being displa ...

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

My intention is to ensure that the page is printed with the Background graphics checkbox pre-checked

When using the print button, I typically include the following code: onclick="window.print();" I also came across this code snippet to set a checkbox as checked by default: <style type="text/css" media="print"> * { -webkit-print-color- ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

Having trouble locating the module '.outputserver ode_modulespiniadistpinia' in Nuxt3 and Pinia?

I recently integrated Pinia into my Nuxt3 project, and while everything works fine in development mode, I encountered an error when trying to access the application in production mode resulting in the website freezing. [h3] [unhandled] H3Error: Cannot find ...

What are some ways to implement a pre-execution step, such as an interceptor, before Nextjs runs getStatic

When working with getStaticProps and getServerSideProps in Next.js, I need to intercept and add common header properties to all request calls that are executed server-side. axios.interceptors.request.use(function (config) { // Perform actions before ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

Creating a seamless vertical marquee of several images that continuously scroll from bottom to top without interruption can be achieved by following these

Currently, I am seeking to design a mobile-friendly HTML page that features a border with multiple color images moving smoothly from bottom to top on both the right and left sides of the mobile screen. The transition should be seamless without any gaps o ...

Need help setting up automatic audio playback on your Android device?

I'm aware that autoplay of audio is not supported on Android devices. However, I recently found a website that successfully autoplays music on an Android device: Can someone explain how this is being achieved? ...

Incomplete Json information

As I embark on my journey to learn Javascript and work on building an application simultaneously, I can't help but feel optimistic about the learning process. To guide me through this venture, I've turned to the teachings of Alex MacCaw in his bo ...

What is the process for generating an HTML document from start to finish with the 'html-element' node module?

Here is an example that demonstrates a flawed method: const HTML = require('html-element'); const doc = `<body> </body>`; const page = HTML.document.createElement(doc) page.appendChild('<div>1</div>') page.append ...

Implement a transition effect for when elements change size using the `.resizable().css` method

I attempted to incorporate a deceleration effect when resizing an element back to its original size using the resizable method. The slowdown effect should only trigger during the click event (when the "Click-me" button is pressed), not while manipulating ...

Can user-generated code execute Javascript Promises in its entirety?

Can one fully implement the JavaScript Promise class using only userspace code, without relying on any support from native code (such as the internals of JavaScript) that would typically only be accessible to those working on a JavaScript engine like the V ...