spacer
Yehuda Shiran October 3, 1999
Type Conversion
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

Data types are converted automatically in JavaScript during the course of script execution. A variable may hold a numeric value at one point of the script, and a string at another one. The following statements constitute a valid JavaScript script:

var myVar = 12;
myVar = "university";

Although such conversions are allowed in JavaScript, they are not recommended. Mixing strings and numbers is sometimes necessary for certain operations. There are a few rules to remember. First, when an expression including both numbers and strings is evaluated to a single value, that value is a string. The number 6, for example, can be easily converted to the string "6", while the string "horse" cannot be converted to a number. Secondly, JavaScript's interpreter evaluates expressions from left to right, and only parentheses can change the order of evaluation. Convince yourself that the following statements are correct:

8 + 8 // 16
"8" + 8 // "88"
8 + "8" // "88"
"8" + "8" // "88"
8 + 8 + "8" // "168"
8 + "8" + 8 // "888"

Notice that every expression including a string operand yields a string. The + operator is an addition operator when both of its operands are numbers. It is a concatenation operator when one of its operands is a string.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business