"Variables declared with const do not get hoisted when used in immediately invoked functions

Recently, I was experimenting with the new ECMASCRIPT-6 const keyword. There was one particular behavior of the keyword that left me confused.

Imagine we have two functions:

In the first case:

(function(){
  console.log(_t); 
  const _t=10;
})();

and in the second case:

function t(){
  console.log(_y); 
  const _y=11;
}
t();

Upon running the code, the output for the first case is (which puzzled me):

ReferenceError: can't access lexical declaration `_t' before initialization

While for the second case, the output turns out to be (as expected):

undefined

The result of the second case makes sense, but I couldn't figure out why the first case threw an error. The error message seems to suggest that the variable is not hoisted. But why is that? After doing some research on this resource, I learned that const uses block scope. Could this be related to the scoping issue?

I conducted these tests on the Firefox Developer Edition console.

Answer №1

This particular issue seems to be tied to Firefox according to information provided here

Notes specific to Firefox

In Firefox, the const declaration predated its inclusion in the ECMAScript 6 specification. For full ES6 compliance with const, refer to bugs 950547 and 611388.

Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33) onward:

{const a=1}; will now throw a ReferenceError and not return 1 anymore due to block-scoping. const a; will now throw a SyntaxError ("missing = in const declaration"): initialization is required. const a = 1; a = 2; will also result in a SyntaxError ("invalid assignment to const a").

I also came across something interesting here

The const hoisting behavior in Firefox's engine appears to be quite strict.

This explanation aligns with my understanding of the situation.

Answer №2

Testing it out in Firefox (38.0.1), I encountered the same error message for both situations; indicating that access is denied before initialization. This aligns with the fact that there's a function expression and a function declaration.

The constant identifiers are indeed hoisted, leading to the issue of being unable to access them before initialization.

In this scenario, block scope and function scope coincide, given that the function code blocks serve as the sole blocks present.

If you introduce a code block causing the constant to be out of reach when attempting to use it, the error message "ReferenceError: _y is not defined" will be displayed instead:

function t(){
  {
    const _y = 11;
  }
  console.log(_y); // _y is out of scope
}
t();

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

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

Tips for sending data from a JSP to a Servlet with Javascript

My code creates an array of circular buttons with dynamic values. When clicked, these buttons get deleted and their values are stored in a JavaScript object array. I need to send these deleted button values to a servlet once my task is complete. To do this ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

Schema-based validation by Joi is recommended for this scenario

How can we apply Joi validation to the schema shown below? What is the process for validating nested objects and arrays in this context? const user = { address: { contactName: 'Sunny', detailAddress: { line1: & ...

Using jQuery to parse JSON transforms an array into a hash object

I recently encountered an issue with a string that I needed to convert into a JSON object. The string looked like this: string = '{ "key": [ { "foo": "bar" } ] }'; To convert the string, I used: json = $.parseJSON(string); However, after co ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

Tips for minimizing the need to copy the entire dojo library each time you create a new Java EE package for deployment on GlassFish

Currently, I am diving into comet programming and utilizing the cometd implementation along with the JavaScript dojo library before deploying my war files to GlassFish. The issue I have encountered is that every time I create a new project, I find myself i ...

Send both file and model data using AngularJS with FormData

When uploading an image using the file input type along with other user data, my model includes the User class: public class User { public int Id { get; set; } public string Name { get; set; } public int Rollno { get; set; } public byte[] ...

What is the best way to expand ScrollToBottom to cover the entire screen height?

Check out this code sandbox that showcases a Logs React component functioning perfectly. The implementation incorporates react-scroll-to-bottom to display a page with a header and logs. What's interesting is that the log section dynamically adjusts i ...

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...

JavaScript function issue with automatic tabbing

Encountered an issue while utilizing this in our asp.net application. The main goal is as follows: When in a textbox -> tab once MaxLength is reached When in a checkbox -> tab once the control is toggled with the keyboard (spacebar) Other than bu ...

Handling form submissions in Vue.js before navigating away from the current route

As a newcomer to VueJs, I am facing a problem with creating a form. My goal is to display an alert dialog with the message "you might lose the data, please save the data before you leave," and upon clicking 'yes', the form should be submitted and ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

A guide to iterating through columns and modifying variables

After scratching my head, I am on the lookout for guidance in the right direction to solve my issue. I have a Google spreadsheet with multiple rows, but I only need the script to focus on the newest row. Despite not having undergone any formal computer tr ...

Implementing a Next.js server-side permanent redirection instead of displaying a 404 error page

My Next.js application consists of three routes: /home, /about, and /contact. When a user accesses a route that doesn't exist, Next.js automatically redirects them to the 404 page. However, I want to change this behavior and permanently redirect use ...

Receiving an absence of string or a null value from a text box

My goal is to test the functionality of an <input> element by entering text into a textbox and then displaying that data in the console. However, I am encountering issues with retrieving and printing the content. Additionally, I am interested in test ...

What is the correct way to utilize a recursive function call in order to retrieve the property of a deeply nested object?

In my Angular project, I am incorporating the AngularTree directive from to display a tree view based on this specific data structure: $scope.subjectAreas = [ { name: "Area-1", link: "dashboards.dashboard_1", ...

Using Regex in Javascript to locate unfinished items that start and finish with brackets

Can anyone assist me in utilizing regex to identify any incomplete items that start with {{. I have attempted to search for instances in the string that begin with {{ and are followed by letters (a-Z) but do not end with }}. However, my attempts always re ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...