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

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

Generate an array of checked inputs to be used when posting to a REST API

I have been using .push() to create a checked array of "List" inputs for posting to a REST API. However, it doesn't seem to be working correctly. When unchecking an item, it is not automatically removed from the array. Does anyone have a better solut ...

Tips for increasing the size of Material-ui Rating icons

I am currently utilizing npm to develop a widget. I aim to utilize the material-ui Rating component and have successfully integrated it. However, when I embed the widget on a webpage, the html font-size is set at 62.5%, causing the component to appear too ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...

Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the curr ...

The issue with Jquery .post function not functioning properly within a popup div

After spending countless hours on this issue, I feel like I'm at a loss... The problem lies in a div that pops up with a button, where the button fills data into different sections of the HTML... Everything works fine except for when I use ajax to c ...

Change web page in JavaScript using post data

Is there a method to utilize JavaScript for navigating to a new URL while including POST parameters? I am aware that with GET requests, you can simply add a parameter string to the URL using window.location.replace(). Is there a way to achieve this with ...

Searching for the perfect jQuery regex to validate date formats

In my application, there is an input box that allows users to enter a string date like "today" or "tomorrow". However, I am facing a new challenge now - dates such as "3 march" or "8 january." The input box includes a dropdown menu feature where users can ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

`I am facing issues with class binding in Vue 3 when using SwiperJS`

Currently, I am working with Vue 3 along with swiperjs. I have encountered a problem related to the v-bind:class behavior in my project. The issue arises when transitioning to the second slide, where the !h-auto class does not get applied as expected. St ...

JSON returning issue with date formatting

After converting a date to a string using ToString("d") in C# and then serializing it into JSON for the client, I'm encountering an issue where instead of displaying the formatted date on the page, I see the following literal text: /Date(-62135575200 ...

How to submit form data with a POST request in Flask using fetch without having to reload

Despite reading numerous similar questions, I am still unable to determine how to achieve my goal. I have multiple forms on a single page and I am trying to submit data from each form without refreshing the page. Below is an example of one of the five form ...

Is it possible for a JavaScript .execute function to be executed synchronously, or can it be transformed into an Ajax

Currently, I am utilizing the ArcGIS API for Javascript which can be found at this URL: The JavaScript code snippet I'm working with appears to be running asynchronously. Is there a way to convert it to run synchronously or potentially transform it i ...

PHP script for batch string replacement

My function is triggered by a button click, where it takes two input IDs and forms a string as follows: var str = "headingText=" + $("#headingText").val() + "&centerText=" + $("#centerText").val(); $.ajax({ url: "indexpdf.php", data: str, ...

Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area. I'm unable to override parent element properties like border or outline. I also can't use pse ...

How to Animate an Object's Rotation Gently using React Three Fiber App and Use Cannon Library?

I am currently working on a project to create a Tetris-like game using React app, react-three-fiber, and use-cannon. I would like to implement a feature where objects/meshes rotate smoothly when clicked. How can I achieve this? Here is the code for the ob ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code: router.get('/', (ctx, next) => { MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) { if (err) th ...

Looking for precise information within a Vue b-table by fetching data from an Axios API

My b-table is filled with data from an API hit through Swagger UI, and since there's a large amount of data, I need the search button at the center top of the page to work properly when inputting store code or branch. https://i.stack.imgur.com/l90Zx.p ...

JavaScript: Accessing the selectedIndex of a dropdown list in RadGrid

Currently facing an issue with utilizing the RadGrid control from Telerik. I am attempting to access and manipulate the value of a GridDropDowncolumn within RadGrid using JavaScript (while in edit mode). Does anyone have any suggestions for the correct Ja ...