Is it possible to utilize the "let" keyword in JavaScript as a way to prevent global-scope variables?

While working on a JavaScript test, I came across an interesting observation related to the let keyword. Take a look at this code snippet:

let variable = "I am a variable";
console.log(window.variable);

Surprisingly, when I tried to access the variable property from the window object, it was not there. Does this imply that variables declared using let don't exist in the global scope?

Is it possible to declare variables without having to enclose them within a function or an IIFE (Immediately-Invoked Function Expression)?

I attempted to find answers to these questions online, but no luck so far. The common advice is to use functions like {}() or work with a distinct global variable containing the code. However, my recent discovery has left me wondering if it can be utilized as an alternative to avoid such approaches.

Answer №1

The use of the let statement does not completely eliminate global variables as you may think. Although a top-level let statement creates variables in the global scope, they are not stored as properties of the "global object" (usually window).

<script>
  'use strict';
  let fromLet = 'from let';
  var fromVar = 'from var';
</script>

<script>
  console.log(fromLet);        // 'from let'
  console.log(fromVar);        // 'from var'
  console.log(window.fromLet); // undefined
  console.log(window.fromVar); // 'from var'
</script>

This behavior is primarily explained in Section 8.1.1.4: Global Environment Records of the ECMAScript 6 specification. Essentially, there exists a single global namespace/scope where values can be stored in two different ways. Certain global elements like built-ins, function and var declarations, and function* (generator) declarations are saved as properties of the global object. On the other hand, things like let, const, class, and new constructs are kept in an internal "environment record" that is not accessible as an object during runtime.

If you're interested in delving deeper into this topic, here are some excerpts to guide you:

A global Environment Record represents the outermost shared scope for all ECMAScript scripts processed within a common Realm. It handles bindings for built-in globals, properties of the global object, and all top-level declarations within a script.

Properties can be directly added to a global object. Thus, the global Environment Record component containing these properties may encompass explicitly created bindings by functions, generators, or variable declarations, alongside implicit bindings created as properties of the global object. The globally maintained list identifies which bindings were explicitly created using declarations.

Table 18 — Additional Fields of Global Environment Records

[[ObjectRecord]]: Object Environment Record

The binding object is the global object, containing global built-in and declared bindings in global code within the associated Realm.

[[DeclarativeRecord]]: Declarative Environment Record

Holds bindings for all global code declarations in the associated Realm except for functions, generators, and variable declarations.

[[VarNames]]: List of String

String names bound by function, generator, and variable declarations in global code within the associated Realm.

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

Reposition picture "overlays" additional HTML components

I am struggling with rotating an image by clicking on a button as the image overlaps the buttons. Can anyone provide guidance on how to achieve this without overlapping? For reference, here is my code and an example: here (http://jsfiddle.net/jj03b17n/5/) ...

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

What is the best way to utilize this resulting value as an input?

I am trying to generate a random number using math.random and use that value in the following script: let bday = Math.floor( Math.random() * (30 - 1 + 1) + 1 ); await test.page.select('select[name="day_select"]',bday); However, I am ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Utilizing the splice method across multiple instances of a string

When facing a string like "This website is blocked by administrator. Please get the admin permissions. You will be allowed only if permission is granted" that needs to be split into three lines for better readability, one solution is using the splice metho ...

Wordpress is having issues running jQuery

I've developed a function inside js/custom.js. The purpose of this function is to arrange posts in my Wordpress site by applying a class called articleAlign. This class will enhance the spacing between the article title and its excerpt, but only when ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

What is the best way to ensure that an iframe adjusts its height to fit the content within a tabbed container?

Is there a way to dynamically set the height of an iframe to match the content inside it when clicking on a tabbed plane? Initially, I used a fixed height of 1000px. How can this be achieved? <div class="container-fluid text-center"> <div ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

There seems to be a complete absence of rendering in this particular vue

Upon initializing a fresh Vue project using Vue CLI 3 and removing all default views and components, I proceeded to add two new views. To my surprise, these views did not render when changing the URL; instead, I was met with a blank page and no error messa ...

Why is the Angular directive '=&' value binding to the scope showing as undefined?

An Angular directive has been defined within my application: (function() { 'use strict'; angular .module('almonds') .directive('security', ['$animate', 'AuthFactory', directive]); fun ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

Encountering a JSLint error while attempting to import the 'aws-amplify' package in my main file

Recently, I installed the latest version of aws-amplify using npm. After running npm init with 'entryPoint.js' as the entrypoint file, I encountered an issue when pasting the following code at the top of entryPoint.js: import Amplify, {Auth} from ...