Variable unique to the specific function in universal function

Can you explain why the alert displays "AAA" instead of "BBB"?

http://jsfiddle.net/Lp4cS/

var z = "AAA";

function xx() {

    var z = "BBB";
    yy();

}

function yy() {

    alert(z);

}

xx();

Answer №1

Here's a breakdown of how this code functions:

var a = "AAA";    // Set global variable a to "AAA"

function b() {   
  var a = "BBB";  // Set local variable a to "BBB"
  c();           // Call function c
}

function c() {   
  alert(a);       // Alert the global variable a
}

b();             // Call function b

Answer №2

When var z = "BBB" is declared in a function, specifically within the context of xx, it remains local to that function. This is why when yy accesses the variable, it displays "AAA."

Answer №3

The reason for this issue is that by re-declaring the variable z within the function.

function xx() {

    var z = "BBB";
    yy();

} 

Now, the scope of z is limited to the function xx()

If you wish to update the global variable z, you should instead do:

function xx() {

     z = "BBB";
    yy();

}

Answer №4

http://jsfiddle.net/Lp4cS/1/

Here is a demonstration of how you can achieve the desired functionality, but it is important to note that relying on global variables is not recommended as it goes against best practices in programming.

window.z = "AAA";

function xx() {

    window.z = "BBB";
    yy();

}

function yy() {

    alert(window.z);

}

xx();

A similar approach can be taken in PHP...

<?php

$z = "AAA";

function xx() {

    global $z;
    $z = "BBB";
    yy();

}

function yy() {

    global $z;
    echo $z;

}

xx();

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

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

Uploading and previewing multiple images on a canvas

After successfully creating single upload for images and placing them on canvas as seen in http://jsfiddle.net/StJnY/, I am now looking to adapt the script for multiple image uploads. Here is how I plan to modify the script: JS : $(function () { $(&a ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the fi ...

Revalidation of paths in NextJS 13 is functioning properly for newly created comments, however, it is not working as

I'm encountering an issue with the implementation of revalidatePath() in my CommentForm and PostForm components. Despite both components having a similar structure and functionality, only the CommentForm component is able to utilize revalidatePath() c ...

Unable to capture mistakes in function executed within try-catch statement

I'm currently facing challenges with implementing asynchronous functions in a Node.js server. This is my first experience working with try/catch blocks and I'm strugging to catch errors within the called function. Here's an excerpt of my co ...

How to prevent links from being affected by the Gooey effect in D3

Issue: When applying the Gooey effect, the links are also affected, resulting in a teardrop shape instead of a circle. The code snippet includes a dragged() function that allows users to detach node 1 from node 0 and reconnect them by dragging. The code s ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

Exploring data visualization within a JSX Component

I am attempting to dynamically render a Card component that is mapped from an array of objects. However, I am encountering an "unexpected token error" and the URL is not rendering as expected. The goal is to display five cards based on the data within the ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...

IE7 is throwing an error saying "Object Expected" when handling the JSON response. This issue does not

Just when I thought I was ready to launch my webapp, IE7 decides to throw a wrench in my plans! I am using the JQuery Form plugin for uploading data to my server. Everything works perfectly on Chrome and Firefox, but IE7 is giving me an "Object Expected" ...

Leverage nan for the transmission and retrieval of Float32Array within an addon module

I am currently attempting to utilize nan in order to perform calculations on an array of floating point numbers within an add-on and then return the result as a Float32Array. However, while the arguments have IsNumber() and NumberValue() functions, there ...

Is it possible to use the same HTML select/dropdown menu for multiple rows in a table?

I am working with an HTML table that usually has between 10-30 rows, each containing a column for "item name". The drop down menu consists of about 75 products to choose from. In order to reduce the page size, I want to use a single drop down list for all ...

Sending information from React JS to MongoDB

I am currently facing a challenge in sending data from the front-end (react js) to the back-end (node js), and then to a mongodb database for storage. While I have successfully called the server with the data, I am encountering an issue when attempting to ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

The URL in React Router updates as expected, but when attempting to render a component using a button component link

I have encountered a situation similar to the one portrayed in this CodeSandBox example, where I am required to implement react routing within two distinct components. The issue that is perplexing me is that, when I navigate down to either the Profile or ...