ikerhurtado.com
You're in
Iker Hurtado's pro blog
Developer | Entrepreneur | Investor
Software engineer (entrepreneur and investor at times). These days doing performant frontend and graphics on the web platform at Barcelona Supercomputing Center

Going deeply into Javascript. Basics (II): Number, String and Array types

15 May 2015   |   iker hurtado  
Share on Twitter Share on Google+ Share on Facebook
In this post I write down some notes on JavaScript basics like Number, String and Array types. It's not intended to be an exhaustive or complete resource about this issues.

Numbers

JavaScript has a single type for all numbers: it treats all of them as floating-point numbers. However, the dot is not always displayed, only when necessary.

Values of other types are converted to numbers as follows:

undefined -> NaN
null -> 0
false -> 0 and true -> 1
Strings: The empty string ('') is converted to 0. For the rest of cases, the value is parsed to number: if the value doesn't represents a number a NaN value is returned.
Objects: Call ToPrimitive(value, Number) and convert the resulting primitive.

The error value NaN (not a number) is a number value. NaN is the only value that is not equal to itself.

In order to check whether a value is NaN, we have to use the global function isNaN(). Note that isNaN() does not work properly with nonnumbers, because it first converts those to numbers.

Infinity is an error value indicating one of two problems: a number can’t be represented because its magnitude is too large, or a division by zero has happened.

Infinity is larger than any other number (except NaN). Similarly, -Infinity is smaller than any other number (except NaN).

The Internal Representation of Numbers

JavaScript numbers have 64-bit precision (double precision) and tis internal representation is based on the IEEE 754 standard.

It not recommended to compare nonintegers directly due to rounding errors. Instead, we can take an upper bound (machine epsilon) for rounding errors into consideration. The standard epsilon value for double precision is 2−53.
var EPSILON = Math.pow(2, -53);

function epsEqu(x, y) {
  return Math.abs(x - y) < EPSILON;
}
epsEqu() ensures correct results where a normal comparison would be inadequate.

Integers in JavaScript

As said, JavaScript has only floating-point numbers. However, most JavaScript engines store small enough numbers without a decimal fraction as an integers and maintain that representation as long as possible. They have to switch back to a floating-point representation if the number’s magnitude grows too large or if a decimal fraction appears.

There is no problem working with integers of up to 53 bits magnitude. However, working with 64-bit unsigned integers requires these are stored as string values. In addition, to perform arithmetic with such integers requires special libraries.

Converting a number n to an integer means finding the integer that is “closest” to n. The following functions are usually the best way of converting a number to an integer: Math.floor(), Math.ceil(), and Math.round().

Strings

Strings are immutable sequences of JavaScript characters. Each such character is a 16-bit UTF-16 code unit. That means that a single Unicode character is represented by either one or two JavaScript characters. You mainly need to worry about the two-character case whenever you are counting characters or splitting strings.

Object values are converted to strings by calling ToPrimitive(value, String) function. They are first converted to primitives, which are then converted to strings.

[Pending to note some string utility functions]

Arrays

An array is a map from indices to values (array elements). they are actually a special type of object.

It's possible use the array property length to remove and append elements. The array method push() provides another way of appending an element.

Arrays are objects and can have properties but they are not considered array elements.

The in operator detects whether an object has a property with a given key. But it can also be used to determine whether a given element index exists in an array.

It's worthy to note that in arrays, all values in brackets are converted to strings and interpreted as property keys, even numbers. An array index must be a stringified integer in the 32-bit range.

Looping an array

Typical way:

for (var i = 0, len = a.length; i < len; i++) {
  // Do something with a[i]
}

Efficient way:

for (var i = 0, item; item = a[i++];) {
  // Do something with item
}
This trick should only be used for arrays which you know do not contain "falsy" values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use the i, len idiom instead.

Holes in Arrays

Arrays can have holes: indices smaller than the length that are missing in the array. Reading an element at one of those indices returns undefined.

var a = [3,,5];
> 1 in a // hole at index 1
false

var a1 = [5,,]; // length = 2, last comma is always ignored 
It is recommended to avoid holes in arrays. JavaScript handles them inconsistently: some methods ignore them, other don’t.

The value of a array element can be undefined and it is not a hole. Iteration via forEach skips the holes, but not the undefined elements:

var a = [ undefined, 3 ];

> a.forEach(function (x) { console.log(x) });
undefined
3

Some operations involving arrays ignore holes, while others consider them.

The basic function of the length property is to track the highest index in an array. Thus, length does not count the number of elements with values but elements plus holes.

The delete operator can delete array elements by creating holes (the length property is not updated).


[Pending to note more used array methods]

POST A COMMENT: