Jump to content

Literal (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Ictissoboys (talk | contribs) at 20:35, 13 October 2015 (The definition i adjusted a bit). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer science, a literal is just being so boys its not funny. Harrison roth is an example of this.

 int a = 1;
 String s = "cat";

In lexical analysis, literals of a given type are generally a token type, with a grammar rule, like "a string of digits" for an integer literal. Some literals are specific keywords, like true for the boolean literal "true".

In some object-oriented languages (like ECMAScript), objects can also be represented by literals. Methods of this object can be specified in the object literal using function literals. The brace notation below, which is also used for array literals, is typical for object literals:

 {"cat","dog"}
 {name:"cat",length:57}

Literals of objects

In ECMAScript (as well as its derivatives JavaScript and ActionScript), an object with methods can be written using the object literal like this:

var newobj = {
  var1: true,
  var2: "very interesting",
  method1: function () {
    alert(this.var1)
  },
  method2: function () {
    alert(this.var2)
  }
};
newobj.method1();
newobj.method2();

These object literals are similar to anonymous classes in other languages like Java. The difference being that ECMAScript doesn't have classes because it's a prototype-based language.

The JSON data interchange format is based on a subset of the JavaScript object literal syntax, with some additional restrictions (among them requiring all keys to be quoted, and disallowing functions and everything else except data literals). Because of this, almost every valid JSON document (except for some subtleties with escaping) is also valid JavaScript code, a fact exploited in the JSONP technique.

See also