Working with Numbers

JavaScript is a loosely typed language. Any variable can be assigned any data type. Programmers used to strongly typed languages such as Pascal, C++, or Java will find this difficult to get used to when working with numbers. For example in C/C++/Java the following statements:
int result;
result = 5/10;
does the following:
  • a variable named result is created that can only hold an integer number such as 1 - it cannot hold a number with a fractional part such as 1.5.
  • five is divided by ten, however, since the result is 0.5 and the variable result can only hold an integer, it is assigned the value 0. The fractional part (the .5) is thrown away.
C programmers are used to integer division where the decimal part of the result is truncated. In JavaScript there are no explicit integers or floating point numbers. Depending on how a number is assigned to a variable and the operations performed on it, the number may be stored as an integer or a "floating point" number in memory. In JavaScript the following single line of code:
result = 5/10
would do the following:
  • 5/10 would be evaluated to equal the number 0.5
  • 0.5 would be assigned to the variable result.
Here are some other examples of working with JavaScript numbers. Please take a minute to read through this table. On the far left are statements that assign the value that results from a simple expression using an operator. The name of the operator appears in the next column and the value that is stored in the variable is described in the last two columns.

Expression

Operation

result is assigned

Data Type of result

result = 5 + 10
Addition
15
Number
result = 5 + "Hello" 
Concatenation
Note: a number and a string are being "added" together. Whenever a string is involved the number is converted to text and concatenated with the string to form a longer text string.
5Hello
String
result = 5 - 10
Subtraction
-5
Number
result = 5 * 10
Multiplication
50
Number
result = 5 / 10
Division
0.5
Number
result = 10 / 5
Division
2
Number
result = 



0 comments:

Post a Comment

Flag Counter