17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

var numberObject = new Number(1.10023);<br />

console.log(numberObject.toFixed()); // Logs 1.<br />

console.log(numberObject['toFixed']()); // Logs 1.<br />

// Number literal/primitive converted to an object when treated as an<br />

object.<br />

var numberLiteral = 1.10023;<br />

console.log(numberLiteral.toFixed()); // Logs 1.<br />

console.log(numberLiteral['toFixed']()); // Logs 1.<br />

console.log((1234).toString()); // Logs '1234'.<br />

console.log(1234['toString']()); // Logs '1234'.<br />

<br />

Boolean<br />

Sample: sample58.html<br />

<br />

// Boolean object treated like an object.<br />

var booleanObject = new Boolean(0);<br />

console.log(booleanObject.toString()); // Logs 'false'.<br />

console.log(booleanObject['toString']()); // Logs 'false'.<br />

// Boolean literal/primitive converted to an object when treated as an<br />

object.<br />

var booleanLiteral = false;<br />

console.log(booleanLiteral.toString()); // Logs 'false'.<br />

console.log(booleanLiteral['toString']()); // Logs 'false'.<br />

console.log((true).toString()); // Logs 'true'.<br />

console.log(true['toString']()); // Logs 'true'.<br />

<br />

Notes<br />

When accessing a property on a primitive number directly (not stored in a variable), you<br />

have to first evaluate the number before the value is treated as an object (e.g.,<br />

(1).toString(); or 1..toString();). Why two dots? The first dot is considered a<br />

numeric decimal, not an operator for accessing object properties.<br />

You should typically use primitive string, number, and Boolean values<br />

The literal/primitive values that represent a string, number, or Boolean are faster to write<br />

and are more concise in the literal form.<br />

72

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!