Just wanted to clarify what var "randomvariable" = " "; means exactly. I never really got an explanation, just from examples, it seems it means that the variable is empty and can be written into? But looking for a more descriptive answer.
-
Is it really `"variable" = ""` or `variable = ""`? – Cameron Aug 08 '15 at 03:43
-
variable = " ", I meant "variable" is a substitute for variable name – Snorlax Aug 08 '15 at 03:44
-
@Snorlax - do you have the context in which this is used? – potatopeelings Aug 08 '15 at 03:48
-
It's not a "random variable"; the construct also doesn't contain quotes around identifiers. Please provide/use working examples. – user2864740 Aug 08 '15 at 03:58
-
See: http://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional , http://stackoverflow.com/questions/3892696/is-var-necessary-when-declaring-javascript-variables?lq=1 , http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it etc. (which will explain all that you want to know, and more) – user2864740 Aug 08 '15 at 04:00
3 Answers
"variable" = " "
Is an incorrect. Because on the left side you should have an object reference, not an actual object.
variable = " "
means that you want to assign " " string to variable
.

- 11,470
- 4
- 35
- 57
Its just a declaration of the variable, so it has a value (even if its nothing, a white space, a dot, or null, or whatever).
Most probably used to prevent errors when you don't know if a variable will take a value or you are going to concatenate values on a loop. Whatever the reason you might have to need that variable to hold a value.

- 3,387
- 1
- 19
- 30
It means that it will allocate an empty string object for the variable. This object can access all the string object functions like length, contains, substring, indexOf, etc. Or you can reassign it to another value if needed.
var var1 = "";
typeof var1 === "string"; // true
var1.length === 0; // true
This is opposed to an empty variable declaration:
var var2;
typeof var2 === "undefined" // true
var2.length; // Uncaught ReferenceError: var2 is not defined

- 759
- 6
- 16
-
`var` says nothing about "allocating memory" (or "creating" objects); objects are created *independently* of scope-local variable (`var`) declarations. It is important to keep the distinction between a variable (or property) and object/value. – user2864740 Aug 08 '15 at 04:02
-
-
"It means that it will allocate memory for the variable..", which is not true. It will *create an [empty string] value* and *assign it to the variable* (or global object property, depending on scope) denoted by the name. Also, ECMAScript, a high-level language/standard, does not discuss 'memory allocation' for objects, much less for variables (or properties). – user2864740 Aug 08 '15 at 04:06
-