0

I'm just wondering if it's fine to declare variables with JSON format?

For example, do this:

$(function(){
    var global = {
        varA : 'This is a global variable from global.varA ~!',
        varB : 'This is a global variable from global.varB ~!'
    };

    alert(global.varA);
    alert(global.varB);
});

Instead of this:

$(function(){
    var globalVarA = 'This is a global variable from globalVarA ~!',
        globalVarB = 'This is a global variable from globalVarA ~!';

    alert(globalVarA);
});
  • The reason why I want to do this is that, It would be easier to look for when I work on a really long JS file. And anything starts with global. I know it is a global variable.
  • Is it a good practice?
  • Is there anything I need to put into considerations?
2
  • 1
    It's not json, it's just a javascript object. Commented Apr 8, 2014 at 2:08
  • 1
    And you are not creating global variables at all. The first is completely valid JS, so why not just do that? What it does is create a local variable global whose value is an object. edit: Oh you are asking whether it's "fine". Yes it is ;) Commented Apr 8, 2014 at 2:09

2 Answers 2

2

First, this is not JSON format, it's just normal javascript object literal.

Second, since it's valid syntax, you could do this, and this is normal practice to put the variables in a namespace (through there's no namespace concept in javascript).

If you want to make global be global, then you could set it to be a property of the global object window:

$(function(){
    var global = {
        varA : 'This is a global variable from global.varA ~!',
        varB : 'This is a global variable from global.varB ~!'
    };
    window['global'] = global;    
});
Sign up to request clarification or add additional context in comments.

Comments

1

Your "new variables" are actually properties of an object literal. They are not variables, nor do they have global scope. However, I don't think it's the worst way to define "references to values". You're using an object as an associative array, which is A-OK.

Comments

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.