Question

I am trying to add an initial empty value for a variable and I dont understand the different between these:

var question = '';

var question = {};

What is the difference between using Braces and Quotes when defining an empty value for a variable?

Was it helpful?

Solution

'' is a string. {} is an object.

Both of these are examples of literal syntax. This means that you can define a type of data with its value initialized. This is the most common approach to defining data in JavaScript.


The first creates a string type with no characters. The quotation marks are merely part of the syntax that denotes the opening and closing of the string. They are not part of the resulting data.

A string is immutable, so it's impossible to add characters to the string you created, though you can replace it with a new string held by that variable.

An example of a string initialized with characters would be:

var question = "Who is John Galt?";

The resulting string contains the characters between the quotation marks. Again, the quotation marks are not part of the result. They merely denote the literal syntax used to create the string.


The second creates an object type that contains no members. Again, the curly braces simply denote the start and end of the literal syntax. They have nothing to do with the actual data contained in the object.

An object can be mutated (except in certain situations that aren't relevant right now). So you can update the members of this object by adding properties in a variety of ways.

An example of an object initialized with members would be:

var question = {
    firstName: "John",
    lastName: "Galt"
};

The resulting object owns two members and inherits a few more. The members are key/value pairs, where the key is ultimately represented as a string (though here we used property identifier syntax, which represents a subset of valid keys), and where the value can be any JavaScript data type (in this example, I used string literal syntax to define string values).

OTHER TIPS

When you say initial empty you need to know the type. Although javascript is loosely coupled you should understand the basic types.

var a; <- undefined no type
var a = {} <- defined object "empty" of defined members
var a = [] <- defined array "empty" of defined elements
var a = 1 <- defined integer
var a = '' < defined "empty" string

This is defining variable question which contains empty string. (as pointed out by dsfq in comments)

var question = '';

This is defining a object question with {}

var question = {};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top