set a value to a global array within a function

After writing the following javascript code:

<script language="javascript" type="text/javascript">
    var name = new Array();
    var i = 0;
    function doSomething() {
        name[i] = "a";
        alert(name[i]);
        i++;
    }        
</script>

I encountered an issue where it alerted undefined instead of a in my Chrome browser. To troubleshoot, I tested alert(i) and that worked properly.

Is there a way to properly assign values to a global array within a function?


Update: The problem was resolved by simply renaming the array, which fixed the issue. But what caused this solution to work?

Answer №1

name is a property that belongs to the window object:

This property can be used to get or set the name of the window.

Keep in mind that global variables are actually properties of the global object (window). Interestingly, Firefox allows you to override this property, while Chrome does not. Test it out in the Chrome console:

> name = [];
[]
> typeof name
"string"

The expected output should be "object".

Lesson learned: Avoid using a global variable named name. Instead, consider renaming your variable for better results. Check out this example for reference.

Answer №2

You are signaling name[i] outside of the function; however, i has already been incremented within the function.

thus alert(name[0]);

http://jsfiddle.net/7J2nP/4/

Answer №3

One possible explanation for this issue could be due to hoisting.
It's a common misconception that variables and functions are defined in the same order as they appear in your script, but in reality, when the javascript interpreter parses your script, it moves all the variables to the top of the scope. This also applies to function declarations. It's likely that in your case, the function declaration has been hoisted above the variables, causing them not to be available within its scope. This behavior may vary depending on the browser used. One way to fix this is by using a function expression instead.

var name = new Array();
var i = 0;
var doSomething = function() {
    name[i] = "a";
    alert(name[i]);
    i++;
}

doSomething(); // alerts 'a'

UPDATE

I just tested this solution in Chrome and unfortunately, it did not work as expected. Felix's answer seems to be a better alternative.

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

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

Guide to linking an external URL with a lightbox image

I have created a gallery and an admin gallery page. In the admin gallery, there is a delete button that appears over the image. However, when I click on it, instead of showing the message "Are you sure?", it opens a lightbox. I suspect that the code for t ...

Sorting an array of pointers to different arrays using bubble sort within a C function

I'm facing an issue with my bubble sort function for an array of pointers, where each pointer points to another array. The error message I receive indicates a violation of the writing location (Visual Studio). To clarify, I use (*parr)++ because the ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

What is the best way to implement asynchronous image loading on hover events in React.js?

You may have come across this type of effect before. A good example can be found here - https://codepen.io/anon/pen/GEmOQy However, I am looking to achieve the same effect in React. While I understand that I can use the componentDidMount method for AJAX c ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Functions perfectly on Chrome, however, encountering issues on Internet Explorer

Why does the Navigation Bar work in Chrome but not in Internet Explorer? Any insights on this issue? The code functions properly in both Internet Explorer and Chrome when tested locally, but fails to load when inserted into my online website editor. Here ...

Using Flexbox CSS to Expand a Box According to its Content Size, Without Impacting Adjacent Rows

Is there a way to make the bottom-most row (highlighted in yellow) expand downward to fill available space? Check out this link for reference: https://jsfiddle.net/darrengates/oucvnfke/ I initially thought using: flex: auto; would solve the issue. Whil ...

Clicking on ng-click can lead to the dissociation of the Angular factory

My situation involves a factory with a series of prototypes that need to call each other. The issue arises when the reference to "this" is mistakenly applied to the html template instead of the original factory class when using ng-click. For example: ang ...

Encase an asynchronous function inside a promise

I am currently developing a straightforward web application that manages requests and interacts with a SQL database using Express and Sequelize. My issue arises when I attempt to call an async function on an object, as the this part of the object becomes u ...

Exploring the Comparison of Arrays in AngularJS

I am currently working with two arrays: one for Usernames and another for userRoles. The structure of the arrays is as follows: Usernames = [ { "id": 1, "userName": "Jack", "description": "jack is a nice guy", "userRoleIds": [ 1 ...

Error occurs when attempting to reload a page while utilizing Angular Ui Router with Html5 mode activated

I've implemented Angular UI Router in my Angular application and configured HTML5 mode to remove the # from the URL using $locationProvider in the config. var app = angular.module('openIDC', ['ui.router']); app.config(function($ur ...

Adding up nested arrays based on their respective indices

If I have two nested arrays within a corresponding array like this: const nums = [ [4, 23, 20, 23, 6, 8, 4, 0], // Each array consists of 8 items [7, 5, 2, 2, 0, 0, 0, 0] ]; How can I add the values based on their indexes? Expected Result: ...

Using HTML5 video with cue points and stop points

I've noticed that there are various options available for implementing cuepoints in HTML5 videos, such as using PopcornJS or CuepointsJS to trigger play events at specific times within the video track. However, I am wondering if there is a solution t ...

Basic jQuery Element Selection

1) Is there a way to trigger an alert only when images like 1_1.jpg, 1_2.jpg, 1_3.jpg or 2_1.jpg, 2_2.jpg, 2_3.jpg are selected and none of the others? (similar to *_1.jpg, *_2.jpg, *_3.jpg) 2) How can I shuffle the order of the image positions randomly ( ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Is it feasible to execute exe files within a ReactJS environment?

Hey there! I've created a Game Launcher using ReactJS for my Unity game and was wondering if it's feasible to start the game (an exe file) simply by clicking on the play button. Can anyone please advise me on this? ...

Navigation issue discovered while trying to implement Ionic's collection-repeat feature

As a newcomer to Ionic and Angular.js, I recently downloaded an example of an ionic collection repeat and navigation from http://codepen.io/ionic/pen/mypxez. Initially, the example worked perfectly with just single index.html and index.js files. However, I ...

A tutorial on assigning the length of an array to a variable in C++ using the size() function

Every time I try to write the code, an error pops up #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {12, 3, 4, 15}; int n = size(arr); cout << "Size of array is " << n; return 0; } ...

When attempting to pass a token in the header using AngularJS, I encounter an issue with my NodeJS server

Error is: Possibly unhandled Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.res.set.res.header 1. All Node.js services were functioning properly before ...