Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript parser accept JSON as a function body?

The other day, I came across some weird code:

var OrderSupplement = function() {
      oid: null;
      code: "";
      description: "";
      startdate: "";
      enddate: "";
      gender: null;
      cardowner: null;
      box: null;
      divisor: 0;
      created: null;
      createdBy: "";
};

The intention of the code was clear to me: It was the try to define a constructor function, in order to create an instance of OrderSupplement.

I am baffled by this syntax.

The buddy, who wrote the code, said it worked fine - although it obviously does not; at least it does not what it should. He instantiated a new instance of OrderSupplement and set e.g. oid to a nonnull value and retrieved it later. Of course retrieving a value before setting would have unveiled the bug.

The effect of the code above is like:

var OrderSupplementJson = function() {}

My question is:

Why is the code above accepted and does not throw an (syntax) error of any kind?

like image 433
Thomas Junk Avatar asked Nov 07 '14 08:11

Thomas Junk


People also ask

Why JSON parse is used in JavaScript?

JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.

Can JavaScript parse JSON natively?

JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.

Why do we use parse JSON?

JSON. parse() is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.

Why JSON is used over XML?

JSON is faster because it is designed specifically for data interchange. JSON encoding is terse, which requires less bytes for transit. JSON parsers are less complex, which requires less processing time and memory overhead. XML is slower, because it is designed for a lot more than just data interchange.


1 Answers

Because oid: defines a label.

It's syntactically correct but void of anything useful. It's obviously a bug.

like image 69
Denys Séguret Avatar answered Dec 08 '22 07:12

Denys Séguret