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

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

When using the "Content-Disposition" header with the value "inline;filename=" + fileName, it does not necessarily guarantee that PDF files will be displayed directly

When a link is clicked, I want the PDF file to first show in a new tab as a preview before allowing users to download it. I researched and found advice suggesting that including these two headers would achieve this: Response.AddHeader("Content-Dispositio ...

What is the process for displaying the save file dialog in Safari?

I'm struggling with generating a PDF and saving it as a file in Safari using an Angular app and DocRaptor. I've tried various methods from Stack Overflow, but none seem to trigger the save file dialog. Instead, they either open the file in the cu ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

Tips on revitalizing a bootstrap wizard

In my JSP file, I am using a Bootstrap wizard. You can see the wizard layout in the following link: The wizard allows me to add employee elements that are stored in a JavaScript array (I also use AngularJS). At the final step of the wizard, there is a su ...

Encasing the Angular 2 component template in a <div> tag

Currently, I have a parent component managing multiple child components. My goal is to enclose each child component's template with a *ngIf directive for conditional rendering. The number of children in the parent component can vary. Here is an examp ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

once a value is assigned to the variable "NaN," it remains constant and does not alter

What is the reason for not getting an assigned value in the line val3.value = parseInt(val1.value + val2.value);? Is it because the specified value "NaN" cannot be parsed, or is it out of range? var val1 = parseInt(document.getElementById("num1")); var ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

Troubleshooting: Issues with jQuery Validate plugin's rules method in Javascript

I'm encountering an issue with a simple javascript file that is supposed to run the rules method, but it's not working as expected. I have confirmed that my custom javascript file is being rendered correctly since input masking is functioning pro ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

Tips for setting up npm dependencies in a subfolder

Within the main directory, I have a package.json file that contains this command: "install": "cd packages/my-package && yarn". Every time I execute yarn run install, my intention is for it to enter into the specified package, set up the node modul ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...