Javascript Tutorial 14 Numbers

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

var x = 0.2 + 0.1;         // x will be 0.30000000000000004

To solve the problem above, it helps to multiply and divide:

var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3

You can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).

var myNumber = 128;
myNumber.toString(16);     // returns 80
myNumber.toString(8);      // returns 200
myNumber.toString(2);      // returns 10000000
myNumber.toString();       // returns "128"

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Division by 0 (zero) also generates Infinity.

Infinity is a number: typeof Infinity returns number.

NaN: Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number. You can use the global JavaScript function isNaN() to find out if a value is a number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number). However, if the string contains a numeric value , the result will be a number:

var x = 100 / "Apple";  // x will be NaN (Not a Number)
var x = 100 / "10";     // x will be 10

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN. Or the result might be a concatenation:

var x = NaN;
var y = 5;
var y1 = "5";
var z = x + y;           // z will be NaN
var z1 = x + y1;         // z1 will be NaN5

NaN is a number, and typeof NaN returns number:

typeof NaN;             // returns "number"

Javascript Tutorial 13 String Methods

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string and the lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

var str = "Please locate where 'locate' occurs!";
var pos1 = str.indexOf("locate");     // 7
var pos2 = str.lastIndexOf("locate"); // 21

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

Both methods accept a second parameter as the starting position for the search:

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);     // 21

The search() method searches a string for a specified value and returns the position of the match:

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

indexOf() and search() are quite equal. These are the differences between indexOf() and search():

  • The search() method cannot take a second start position argument.
  • The search() method can take much more powerful search values (regular expressions).

There are 3 methods for extracting a part of a string:

  • slice(start, end)
  • substring(start, end)
    • substring() is similar to slice().
    • The difference is that substring() cannot accept negative indexes.
  • substr(start, length)
    • substr() is similar to slice().
    • The difference is that the second parameter specifies the length of the extracted part.
    • If you omit the second parameter, substr() will slice out the rest of the string.
var str = "Apple, Banana, Kiwi";
var res1 = str.slice(7, 13);   // Banana
var res2 = str.slice(-12, -6); // Banana

If you omit the second parameter, the method will slice out the rest of the string:

var str = "Apple, Banana, Kiwi";
var res1 = str.slice(7);    // Banana, Kiwi
var res2 = str.slice(-12);  // Banana, Kiwi

Negative positions do not work in Internet Explorer 8 and earlier.

The replace() method replaces a specified value with another value in a string. By default, the replace() function replaces only the first match:

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");  // Please visit W3Schools and Microsoft!

To replace all matches, use a regular expression with a /g flag (global match):

var n = str.replace(/Microsoft/g, "W3Schools"); // Please visit W3Schools and W3Schools!

By default, the replace() function is case sensitive. Writing MICROSOFT (with upper-case) will not work. To replace case insensitive, use a regular expression with an /i flag (insensitive):

var n = str.replace(/MICROSOFT/i, "W3Schools"); // Please visit W3Schools and Microsoft!

The replace() method does not change the string it is called on. It returns a new string.

A string is converted to upper case with toUpperCase().

A string is converted to lower case with toLowerCase().

There are 2 safe methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)
var str = "HELLO WORLD";
str.charAt(0);      // returns H
str.charCodeAt(0);  // returns 72

unsafe method:

str[0];             // returns H

This is unsafe and unpredictable:

  • It does not work in all browsers (not in IE5, IE6, IE7)
  • It makes strings look like arrays (but they are not)
  • str[0] = “H” does not give an error (but does not work)

If you want to read a string as an array, convert it to an array first.

A string can be converted to an array with the split() method:

var txt = "ab,cd e";      // String
txt.split(",");           // ["ab", "cd e"]
txt.split(" ");           // ["ab,cd", "e"]
txt.split("");            // ["a", "b", ",", "c", "d", " ", "e"]
txt.split();              // ["ab,cd e"]

Javascript Tutorial 12 Strings

Normally, JavaScript strings are primitive values, created from literals: var firstName = “John”

But strings can also be defined as objects with the keyword new: var firstName = new String(“John”)

var x = "John";             // typeof x will return string
var y = new String("John"); // typeof y will return object

Don’t create strings as objects. It slows down execution speed. The new keyword complicates the code. This can produce some unexpected results:

Comparison:

var x = "John";             
var y = new String("John");

// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types (string and object)

Even worse:

var x = new String("John");             
var y = new String("John");

// (x == y) is false because x and y are different objects
// (x === y) is false because x and y are different objects