The unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere.

I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue with array assignment in JS.

    var gear = []; // global assignment

    gear[0]=200; // this line is causing an error

    function bla(){

        gear[0] = 200;// even putting it in a function doesn't work
    }

// I keep getting an unexpected token "[" error. It's frustrating because even BASIC allows this.

After some research, I realized that my placement of the assignment may be incorrect. I've tried assigning globally and inside a function, but I still encounter errors.

So here are my questions regarding pure JS: Is it not possible to assign a numerical value to an array? Where should I place this assignment? If I'm doing this wrong (which seems likely), how can I make index 0 equal to a specific value? Do I need to use parentheses? My program was functioning perfectly until I tried adding arrays, now I'm stuck on this token error. (I could easily do this with console API, but I prefer a web-based solution)

Thank you all for your help!

Answer №1

After some investigation, I realized that none of my initial assumptions were correct. It turns out that the error was caused by a mistake when initializing a variable and then trying to assign it a value:

For example:

var gear = []; // Initializing the array - this is fine
gear[0] = 200; // Assigning a value - this is also fine, but....

var gear[0] = 200;// In the later part of the code, I found this line which led to the error.

In most programming languages, including JavaScript, re-declaring a variable using "var" is not allowed unless the original declaration does not exist. This behavior can be confusing as other languages like PHP and Pascal are more lenient in this regard.

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 "Cannot access 'id' property of undefined" is being displayed

I have a file named auth.js along with a middleware called fetchuser. The code provided below is causing an error that I cannot figure out. The error occurs during the process of sending a token to the user and verifying whether the user is logged in or n ...

What is the best way to extract data from an array of objects in a JSON response?

I am currently exploring the utilization of API's in React. Right now, I am developing a search input feature for country names using the Rest Countries API. The data is being pulled from . However, I am facing a challenge in handling this data as it ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

Access and retrieve data from a string using XPath with JavaScript

My HTML page content is stored as a string shown below: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </ ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

What is the best way to retrieve elements from this JSON data?

Currently, I am developing a command line interface to display random quotes. I have found an API to fetch quotes from, but the issue is that the JSON response is returned as an array. [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate ...

Creating custom ExpectedConditions with Protractor for detecting attribute changes

I've been working on creating a custom ExpectedConditions method that can wait for an element attribute to change. Here is the approach I came up with: const CustomExpectedCondition = function() { /** * Check if element's attribute matches ...

How to emphasize a portion of an expression in AngularJS using bold formatting

I have a specific goal in mind: to emphasize part of an angular expression by making it bold. To achieve this, I am working with an object obj which needs to be converted into a string str. obj = $scope.gridOptions1.api.getFilterModel(); for (var pr ...

Having trouble parsing an array from Alamofire in iOS using SwiftyJSON? You may encounter null values while attempting to parse

Here is the response from the API request: [ { " ..... I am currently using SwiftyJSON to parse the data received from an Alamofire request: let json = JSON(data) let mapHeir = json[0]["Info"]["String"] print(mapHeir) However, I am facing ...

Tips for populating a Flat List with nested JSON data in React-Native

As a beginner in React-Native and Javascript, I'm trying to figure out how to retrieve data for my FlatList. The JSON format I receive is structured like this: [ { "18": { "sellingUnitName": "unité(s)", "qualifier": "GOOD", " ...

Code for dividing large JSON data based on node names in a generic way

I am facing a challenge with handling very large JSON files, where the car array can contain up to 100,000,000 records. The file size ranges from 500mb to 10 GB and I am currently using Newtonsoft json.net for processing. Input { "name": "John", "age": " ...

Avoiding model updates when cancelling in angular-xeditable

I am utilizing angular-xeditable. When changing the value of "editable-text" and pressing the Cancel button, the "editable-text" value should revert back to its previous one. In other words, "editable-text" keeps updating the model even if the Cancel butto ...

Form Automatically Submits Data Upon Loading of Page

I am currently facing an issue with my hidden div that is being loaded when I click the submit button. The form is sending results upon page load, and even though I have included the validateForm() function and called it at the end of the submit function ...

AngularJS bracket-enhanced template

Why is AngularJS giving an error when brackets are used inside ng-template content? I am trying to create an input field that should accept an array, but I keep getting this error message: "Error: Syntax Error: Token ']' not a primary expression ...

Unable to convert the existing JSON array into the specified type

I've been struggling to find a solution to this problem, even though I've come across similar topics that have been asked before. Below is a sample Json that I'm posting to a web API controller: { "AppointmentId ":2079, "ma ...

Facing troubles with the file format while trying to upload a CSV file to dropbox.com

My goal is to develop a Chrome extension that allows users to upload files directly to Dropbox.com. While most aspects of the functionality are working smoothly, I am encountering some challenges with the CSV format. The code snippet below demonstrates how ...

Automatically load VueJS components based on the prefix of the tag

I am currently working on defining components based on the prefix when Vue parses the content (without using Vuex). While exploring, I came across Vue.config's isUnknownElement function but couldn't find any documentation about it. By utilizing ...

Guide to transforming a REQUEST response into a nested Hash or Array in Ruby

When working with HTTParty for an external API call, I am encountering a nested JSON object response. The structure of the response varies, sometimes with more nested objects or arrays: { "something": "10100014", "something": "025MH-V0625", "somet ...

A guide on Implementing PastBack Functionality with AJAX Responses

When I make a GET request for an HTML page, I come across the following element: <a id="ctl00_cphRoblox_ClaimOwnershipButton" href="javascript:__doPostBack('ctl00$cphRoblox$ClaimOwnershipButton','')">Claim Ownership</a> My ...