Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. JavaScript Objects > Creating Shorthand/Literal Values from Constructors

Creating Shorthand/Literal Values from Constructors

JavaScript provides shortcuts—called “literals”—for manufacturing most of the native object values without having to use new Foo() or new Bar(). For the most part, the literal syntax accomplishes the same thing as using the new operator. The exceptions are: Number(), String(), and Boolean()—see notes below.

If you come from other programming backgrounds, you are likely more familiar with the literal way of creating objects. Below, I instantiate the native JavaScript constructors using the new operator and then create corresponding literal equivalents.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myNumber = new Number(23); // an object
var myNumberLiteral = 23; // primitive number value, not an object

var myString = new String('male'); // an object
var myStringLiteral = 'male'; // primitive string value, not an object

var myBoolean = new Boolean(false); // an object
var myBooleanLiteral = false; // primitive boolean value, not an object

var myObject = new Object();
var myObjectLiteral = {};

var myArray = new Array('foo', 'bar');
var myArrayLiteral = ['foo', 'bar'];

var myFunction = new Function("x", "y", "return x*y");
var myFunctionLiteral = function(x, y) {return x*y};

var myRegExp = new RegExp('\bt[a-z]+\b');
var myRegExpLiteral = /\bt[a-z]+\b/;

// verify that literals are created from same constructor

console.log(myNumber.constructor,myNumberLiteral.constructor);
console.log(myString.constructor,myStringLiteral.constructor);
console.log(myBoolean.constructor,myBooleanLiteral.constructor);
console.log(myObject.constructor,myObjectLiteral.constructor);
console.log(myArray.constructor,myArrayLiteral.constructor);
console.log(myFunction.constructor,myFunctionLiteral.constructor);
console.log(myRegExp.constructor,myRegExpLiteral.constructor);


</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint