1

I'm declaring this array in a javascript script:

    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 declare it inside the

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

function, then the console.log(status) return me an array of objects (like I want it to be).

But if I declare it outside the document ready function, it will return this string:

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

And, i repeat, it's a string...

Maybe it is something stupid but I can't figure out where the problem is.

1

1 Answer 1

12

It's because status is a pre-existing global whose value you can't set to an array (it can only be a string, in theory it's the status text shown in the browser's footer, if it has one; and browsers ignore it these days):

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

If you set it to a non-string, either the browser will ignore it, or (as in your case) it will coerce to string — what you're seeing is what you get for an array with plain objects in it when you coerce to string:

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

This is one of the reasons not to use globals, on browsers the global namespace is really crowded. Instead, wrap your code in a scoping function (whether you use ready or just an IIFE). Or if you have to have a global, have just one (like jQuery [almost] does), and make it an object with properties on for the various things you want to be "global".

Sign up to request clarification or add additional context in comments.

3 Comments

For this reason, I frequently add an underscore for any global I need to create, and also usually add my application name. Ex: __appnameStatus
Does OP say status is pre-existing global?
@AnkitAgarwal: OP says their code doesn't work at global scope. The above is why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.