What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me?

function func1() {
  console.log('Func1 executed.');
};

const func2 = () => {
  console.log('Func2 executed.');
};

const test = () => {
  window['func1'](); //This works
  window['func2'](); //This doesn't work
};
button {
  width: 200px;
  padding: 20px;
  font-size: large;
  cursor: pointer;
  border: 0;
  background: linear-gradient(to top right, gray, silver);
  color: white;
  border-radius: 7px;
  box-shadow: 0px 5px 7px silver;
  text-shadow: 0px 2px 2px rgba(0,0,0,0.5);
}
<button onclick='test()'>Execute</button>

Answer №1

The clear-cut answer is:

When global variables are initialized with let and const, they do not turn into properties of the window.

Take a look at this:

const

Global constants, unlike var variables, do not transform into properties of the window object.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

and:

let

Similar to const, when declared globally (at the top-most scope), let does not generate properties of the window object.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Answer №2

While I may not have a lot of expertise in JS, my understanding is that the distinction lies in the first function being reusable multiple times while the second lambda function focuses on returning and storing a value without recomputation in the variable func2.

Feel free to correct me if I'm mistaken.

Answer №3

One thing to note is that when you call a value or variable (const func2 = could potentially end with an integer, for instance), you should actually pass the function itself in the format of window[Functioname]().

You can achieve this by implementing a second-degree function call, as demonstrated below.

By the way, nice button!

function func1() {
  console.log('Func1 executed.');
};
const func2 = () => {
  console.log('Func2 executed.');
};


function func3(){
  func2();
}
const test = () => {
  window['func1'](); //Works fine
  window['func3'](); //Works fine
  window['func2'](); //Does not work
};
button {
  width: 200px;
  padding: 20px;
  font-size: large;
  cursor: pointer;
  border: 0;
  background: linear-gradient(to top right, gray, silver);
  color: white;
  border-radius: 7px;
  box-shadow: 0px 5px 7px silver;
  text-shadow: 0px 2px 2px rgba(0,0,0,0.5);
}
<button onclick='test()'>Execute</button>

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

When resizing the window in IE8, the function DIV offsetWidth/Width/innerWidth returns a value of zero

My page is filled with many elements, one of which is the following DIV: <div id="root"> .................. <div id="child1"> ............. </div> <div id="child2"> ............... </div> & ...

How to submit a textarea with the enter key without needing to refresh the page

I'm attempting to handle the submission of a textarea when the user hits the enter key, storing the text in a variable, then swapping out the form with the text and adding a new form at the end, all without refreshing. I had success doing this with an ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Error encountered: TypeError: __webpack_require__.t is not a function - Issue appears only on live server, while localhost runs without any problem

I set up an e-commerce site that runs smoothly on localhost. However, when I deploy it to a live server, an error appears. Interestingly, the error disappears after reloading the page. Here is the code snippet: import React, { useEffect, useState } from & ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

A widget for Windows 7 that can handle both HTTP GET and POST requests

I'm currently working on a small gadget for our intranet and have set up a PHP file on our server for initial testing purposes. Everything seems to be functioning properly when I use the GET request method, but I would prefer to utilize POST in order ...

Can a single Axios request in JavaScript include both a Body and Files?

Is it possible to send both a file and body with the POST request below in axios? axios.post("http://localhost:3000/upload", formData) How can I include something in the body:{} section as well? Server response: files: { myFile: { nam ...

Incorporate action icons (such as edit and delete) into a table in React.js using material-ui

Within my existing table, I utilized a library known as react-bootstrap-table-next This library effectively displays data in a table format with values originating from a JSON response Now, my goal is to integrate an Action column that includes options f ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true. For example: If 'id' is present in obj1 but not in obj2, it s ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

Navigating through Next.js for slug URLs such as site.com/username

Can someone help me figure out how to create a profile page for each username, like site.com/jack or site.com/jill? I'll be pulling the username info from an API that also contains the user ID and email. I'm new to Next.js and would really appre ...

"What is the best way to include additional fields within a popover in an AngularJS application

This is my code for implementing a popover using AngularJS. I am trying to figure out how to add custom styling to the popover HTML, but I am having trouble binding elements in that part of the code. <!DOCTYPE html> <html> <head> <l ...

What could be causing React to render only the final two elements of my array?

I am currently working on a project where I need to display a series of images from a folder. While I have managed to accomplish this, I am facing an issue where the images are being displayed in rows of 2. Although the implementation is successful, it see ...

Leveraging the power of tabs in AngularJS

Utilizing tabs in angularjs and dynamically loading views. My goal is to prevent the re-loading of a view that has already been loaded, and to ensure that the controller does not run again when using $state.go. Instead, it should be set to active status. ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

Dynamic collapsible containers

I discovered a useful feature on w3schools for collapsing elements: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol However, I would like to reverse it so that all elements are initially shown when the page loads, and then ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

JavaScript Image Swap

I tried implementing this script but it didn't work for me. I'm not sure what to do next, so I'm reaching out for help. The script is at the top of the page, followed by a picture with an id that I'd like to change when a button below i ...

Issue with THREE.js: Object picking does not display the parent object name when an object is loaded using OBJMTLLoader

I successfully loaded an OBJ file along with MTL file textures using OBJMTLLoader. The code I used was borrowed from . The primary object, a man in a business suit with hair, hands, and shoes, is displayed correctly with all the textures applied, such as ...