Creating arrays in JavaScript with or without the use of jQuery

In my JavaScript script, I am defining this array:

    var status=[
    {
        "name":"name1",
        "level":0
    },
    {
        "name":"name2",
        "level":0
    },
    {
        "name":"name3",
        "level":0
    },
    {
        "name":"name4",
        "level":0
    },
    {
        "name":"name5",
        "level":0
    }];
console.log(status);

If I define it within the

$('document').ready(function(){
});

function, then the console.log(status) shows an array of objects (which is what I intend).

However, if I define it outside the document ready function, the result will be:

[object Object],[object Object],[object Object],[object Object],[object Object]

And, as mentioned earlier, this is a string...

Perhaps it's something simple, but I cannot pinpoint where the issue lies.

Answer №1

One of the reasons for this behavior is that status is already a predefined global variable that cannot be assigned an array value (it must remain a string, theoretically representing the status text displayed in the browser's footer, though modern browsers tend to ignore it):

console.log("before:", typeof status);
var status = [];
console.log("after:", typeof status);

If you attempt to assign a non-string value to it, the browser will either ignore it or, as evident in your example, coerce it to a string — resulting in the output you're observing when attempting to coerce an array with plain objects into a string:

console.log(String([{}, {}, {}]));

This highlights why relying on global variables should be avoided, given the cluttered nature of the global namespace in browsers. Rather, consider encapsulating your code within a scoping function (using `ready` or an IIFE). If a global variable is absolutely necessary, limit it to just one (as jQuery does), and structure it as an object with properties for the various elements you wish to make globally accessible.

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

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Adding and deleting MPEG-DASH segments from a media source buffer in a dynamic manner

I have been developing a custom MPEG-DASH streaming player using the HTML5 video element. Essentially, I am setting up a MediaSource and attaching a SourceBuffer to it. After that, I am appending DASH fragments into this sourcebuffer and everything is func ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

Improving basic collision detection using velocity-based 2D motion

Check out this CodePen demo where you can control the movement of the "player" square using arrow keys. You can also place a light by pressing the spacebar and the player is supposed to be prevented from crossing over the blue lines by getting pushed in ...

Tips for choosing the node_modules distribution flavor to include in your webpack bundle

Issue: Following the update of AJV.js to Version 6.4, my vendor bundle now includes the "uri-js" ESNEXT version instead of the ES5 version, causing compatibility issues with IE11. Analysis: Upon investigation, I discovered that AJV references uri-js usi ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Is it possible to combine the outcomes of a SQL query that produces numerous entities with identical identifiers?

Currently working on my first Node.js API project. Within the '/posts' endpoint, I am receiving data in this format: [ { "POST_ID": 1, "POST_TITLE": "Post N.1", "POST_DESCRIPTION" ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

Ways to protect my login details when making an ajax request?

The scenario I am dealing with is as follows: I have developed a website using Javascript where users are required to input a username and password. Subsequently, the site makes an ajax call to the Webserver. On the other end, I have a PHP-powered Webser ...

Modifying several items with Ramda's lens

I am currently working with a data structure that is structured similarly to the following: var data = { "id": 123, "modules": [{ "id": 1, "results": [{ "status": "fail", "issues": [ {"type": "ch ...

When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature. Though I admit that the site lacks attention to detail, my main ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...