var keyword, a name, the assignment operator, and optionally, its value.
// Declare variable as integer var a = 123; // Negative number var b = -123; // We can use decimal points, too var c = 1.5;
0.1 + 0.2; // 0.30000000000000004
Weird, huh? This is because those numbers can't be represented exactly in binary form, and those representations are truncated by the implementation. When dealing with operations that require a high degree of accuracy - hello financial transactions! - it's recommended to manually round the result, or shift the decimal so that £1.53 becomes 153 pence.
Representing large monetary values in pence will eventually become unwieldy, so it's handy to know that they can be represented in scientific form. 1,000,000 will become 1E6: 1 to the power of 6.
A further pitfall is that numbers beginning with a 0 are interpreted as octals. In a similar manner, numbers starting with
0x will be interpreted as hexadecimal - base 16. It's a sensible idea to always sanitise user inputs and double-check strings before working with a number which may be in a different base to what is expected.
The modulo operator (
%) is used to return the remainder after division of two operands. 15 % 10 = 5.
It is possible to compare numbers using
=== (equality) and
!== (not equal to).
parseInt(value [, base]). This function will work through the characters of the string until it finds a character that is not a numeral in the specified base. Thus:
parseInt("abc123", 10); // NaN parseInt("123abc", 10); // 123
When using it, it's sensible to get in the habit of adding a base as the second (optional) argument. While most implementations will deliver a decimal if you omit it, you do run the risk of ending up with an octal or hexadecimal number.
parseInt("123abc", 2); // 1 (Only that first character is accepted in binary) parseInt("123abc", 8); // 83 parseInt("123abc", 16); // 11946485 parseInt("0123abc"); // 123 (Current implementation no longer interprets as an octal parseInt("0x123abc"); // 11946485
On occasions, complex strings can result in
NaN: Not a Number. Before working on the result of a
parseInt function, it's wise to check for the presence of
isNaN(). To complicate matters,
NaN is not equal to itself.
isNaN(NaN) // true NaN === NaN // false
To carry out similar operations with floating-point numbers, we can use the aptly-titled
||Generates a random number between its default bounds of 0 and 1. It is seeded with the current time.|
||Rounds the supplied number to the nearest whole number|
||Rounds the number down|
||Rounds number up|
||Returns the result of the base to the power of its exponent: eg.
||Returns the square root of the supplied argument|
Daniel is a front-end developer at Talis, with an interest in accessibility, performance, and web components.