2

In javascript, we can initialise a variable with {}. What does the "{}" mean?

var o = {};
o.getMessage = function ()
{
    return 'This is an example';
};
return o;
TFS
  • 964
  • 1
  • 9
  • 19
  • it means you are initializing your variable with an object i.e. your variable is an object – Saurabh Srivastava Oct 09 '16 at 06:39
  • 4
    It is called object literal. – thefourtheye Oct 09 '16 at 06:39
  • 6
    `{}` is an empty object literal or an empty block, depending on the context. – georg Oct 09 '16 at 06:42
  • 4
    What you need to do is go through a few JavaScript tutorials so you can learn this stuff. People are happy to answer questions here, but if you keep asking questions about stuff like this you'll have to ask question after question after question. It will be a better use of your time if you study this on your own. Just search for "javascript tutorial" and you will find many useful resources. That is a much better way to start learning a language. – Michael Geary Oct 09 '16 at 06:49
  • I don't understand how such a basic question got 5 upvotes. Please use **Google** before you post a question. – Rajesh Oct 09 '16 at 07:04
  • To be honest, this question is vague as it asks what "{}" is, not what `var o = {}` results in. – Meirion Hughes Oct 09 '16 at 07:06
  • @t.niese "It is true that the content of a JSON string can be directly copied and used as a JavaScript object" --- actually, no. Not every valid JSON is a valid js literal: some would be syntactically incorrect, some would break data it supposed to hold. – zerkms Oct 09 '16 at 19:58

4 Answers4

3

This means you create an object with a variable Its known as object with literal notation.which seems like below .

var o = {} 

here your object has no property or it can be say as empty literal block .But in the below code

var o = {
o .first= 20;
o .second= 10;
o.result =function(){
return this . first- this .second;
}
} ;

now you have your object with property and function

** though there are several ways of creating object But Literal notation is the easiest and popular way to create objects

Asifuzzaman Redoy
  • 1,773
  • 1
  • 15
  • 30
0

Basically the different cases are:

Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Adi
  • 2,074
  • 22
  • 26
0

Basically, it is an empty object. When you add the getMessage() function at the bottom of the variable, you actually added it to the empty object, resulting to your empty object now to look like this:

var o = {
    getMessage: function() {
        return 'This is an example';
    }
};
JTrixx16
  • 1,083
  • 9
  • 15
0

You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope.