Declaring variables without a value

I want to create a Javascript object with nested variables, where some of the variables will not have a default value.

I currently have this:

var globalVarA = "foo";
var globalVarB = "bar";
var globalVarC;

function myFunction(){
  //do something
}

I want to change this to:

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC
  },
  myFunction: function(){
     //do something
  }
}

However, I get the following error:

Expected ':'

How can I declare this variable without a value?

Is this the best practice or is there an alternative best solution?

+5
source share
3 answers

If you want to define variables as properties GlobalVars, you need to explicitly assign themundefined

GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: undefined
  },

, . , XML formParams, / .

, undefined - undefined, , , .

, globalVarC: undefined

GlobalVars.globalVarC;//undefined
GlobalVars.globalVarX;//undefined
GlobalVars.hasOwnProperty("globalVarC");//true
GlobalVars.hasOwnProperty("globalVarX");//false

spec:

4.3.9 undefined :

, , .

+12

globalVarC javascript json , , undefined.

undefined - undefined.

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: undefined
  },
  myFunction: function(){
     //do something
  }
}
+1

You want the primitive undefinedvalue to be the default value:

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: void 0
  },
  myFunction: function(){
     //do something
  }
}

The expression void 0gives a value undefined, regardless of whether it was undefined"redirected".

0
source

All Articles