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 > The Primitive Values null, undefined, “string”, 10, tru...

The Primitive Values null, undefined, “string”, 10, true, and false Are Not Objects

The null and undefined values are such trivial values that they do not require a constructor function, nor the use of the new operator to establish them as a JavaScript value. To use null or undefined, all you do is use them as if they were an operator. The remaining primitive values string, number, and boolean, while technically returned from a constructor function, are not objects.

Below, I contrast the difference between primitive values and the rest of the native JavaScript objects.

Live Code

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

/* no object is created when producing primitive values, 
notice no use of the "new" keyword */
var primitiveString1 = "foo";
var primitiveString2 = String('foo');
var primitiveNumber1 = 10;
var primitiveNumber2 = Number('10');
var primitiveBoolean1 = true;
var primitiveBoolean2 = Boolean('true');

// confirm the typeof is not object
console.log(typeof primitiveString1, typeof primitiveString2); 
  // logs 'string,string'
console.log(typeof primitiveNumber1, typeof primitiveNumber2); 
  // logs 'number,number,
console.log(typeof primitiveBoolean1, typeof primitiveBoolean2); 
  // logs 'boolean,boolean'

// versus the usage of a constructor and new keyword for creating objects

var myNumber = new Number(23);
var myString = new String('male');
var myBoolean = new Boolean(false);
var myObject = new Object();
var myArray = new Array('foo', 'bar');
var myFunction = new Function("x", "y", "return x * y");
var myDate = new Date();
var myRegExp = new RegExp('\\bt[a-z]+\\b');
var myError = new Error('Crap!');

// logs 'object object object object object function object function object'
console.log(
typeof myNumber,
typeof myString,
typeof myBoolean,
typeof myObject,
typeof myArray,
typeof myFunction, // BE AWARE typeof returns function for all function objects
typeof myDate,
typeof myRegExp, // BE AWARE typeof returns function for RegExp()
typeof myError
);

</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