Why is the JavaScript function working even without any arguments?

During my search for some JS Code, I stumbled upon this piece of code.

Check out the code snippet below:

arg = "TEST ALERT MESSAGE";
MyFunction(arg);

function MyFunction()
{
alert(arg)
}

In the above code snippet, the MyFunction() is provided with an alert message, but there is no parameter to receive the incoming argument.

Surprisingly, when I try to change the 'arg' variable (both inside and outside the function), it doesn't work as expected.

How is this possible?

Appreciate any help in advance

Answer №1

Understanding variable scope in JavaScript can be trickier than you might expect. If you want to create a 'private' variable, you can try the following approach:

var arg = "not private";
function privateMSG(){
var arg = "private";
  function alerter(){
  alert(arg);
 }
  alerter();
}

For a more detailed explanation, check out MDN's section on Nested functions and closures

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

Struggling to get this bootstrap carousel up and running

I can't seem to get this bootstrap carousel to switch slides, whether I use the indicators or arrows. My other carousel works perfectly fine and I've added all necessary Bootstrap and JavaScript CDNs. I'm puzzled as to why it's not func ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

How can I obtain hosting XULDocument for a ContentWindow or HTMLDocument within a Firefox extension?

I have a Firefox Extension with a XUL overlay that includes some Javascript with event handlers. One of these event handlers is an EventListener for DOMContentLoaded. I want to load a second overlay only when visiting a specific website. Here is a snippet ...

Custom JavaScript files are not recognized by Angular 4 pages unless the page is manually refreshed

I am facing an issue with my custom JavaScript files in Angular. I have imported them all in the angular-cli.json file but the pages do not recognize them unless I refresh the page after navigating from one page to another. Here is a snippet of my angular ...

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Dependable Timeout Functionality in JavaScript

We are currently developing an AngularJS application that presents users with questions and keeps track of the number of correct answers within a strict 20-minute time limit. However, there are some challenging requirements we need to consider: Accuracy C ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...

Update the 'duplicate' buttons according to the position in the array

My app features 14 buttons, each generating a replica button with the same text when clicked. The pre-existing buttons are numbered to aid in iteration. I'm currently attempting to organize the newly created replica buttons in ascending order from lef ...

The AJAX response is incorrect due to a PHP request, leading to the reloading

Whenever the 'signup' button is clicked, a function in my code initiates an HTML switch. The issue I am facing arises when I test for incorrect email or password during sign up. While I can successfully verify the data, it still loads the previou ...

Develop a real-time streaming service using AngularJS

I am looking to develop a website that pulls information from multiple APIs and presents it in a user-friendly format. Since I wanted to experiment with AngularJS, I opted to use it for this particular project. However, I am struggling with figuring out h ...

Alter the views of a bootstrap date picker in real-time

Is there a way to dynamically change the date picker's view based on different button selections? For example, I have buttons for month, year, and day. Here is what I am trying to achieve: When the month button is selected: I want the date picker ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Disable the 'bouncy scrolling' feature for mobile devices

Is there a way to prevent the bouncy scrolling behavior on mobile devices? For example, when there is no content below to scroll, but you can still scroll up and then it bounces back when released. Here is my HTML structure: <html> <body> ...

Creating a paginated table with Nextjs, Prisma, and SWR: A step-by-step guide

I am attempting to set up a paginated table utilizing Nextjs, Prisma, and SWR. The table will display a list of invoices sorted by their ID. Here is an example of what it would look like: https://i.sstatic.net/WymoH.png To fetch all the data to the api r ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

The onload event for windows does not fire

I am currently working on a project that requires the use of tabbing control with flyingbox. To achieve this, I consulted the following link: After referring to the above link, I made some modifications to my project. I am retrieving details from another ...