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

13. Working with Primitive String, Numbe... > You Should Typically Use Primitive S...

You Should Typically Use Primitive String, Number, and Boolean Values

The literal/primitive values that represent a string, number, or boolean are faster to write and are more concise in the literal form.

You should use the literal value because of this. Additionally, the accuracy of the typeof operator depends upon how you create the value (literal versus constructor invocation). If you create a string, number, or boolean object, the typeof operator reports the type as an object. If you use literals, the typeof operator returns a string name of the actual value type (e.g., typeof 'foo' // returns 'string').

In the code below, I demonstrate this fact.

Live Code

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

// string, number, and boolean objects
console.log(typeof new String('foo')); // logs 'object'
console.log(typeof new Number(1)); // logs 'object'
console.log(typeof new Boolean(true)); // logs 'object'

// string, number, and boolean literals/primitives
console.log(typeof 'foo'); // logs 'string'
console.log(typeof 1); // logs 'number'
console.log(typeof true); // logs 'boolean'

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