Home > Articles > Web Development

Tech Tune-up: A Closer Look at JavaScript Types in Node.js (text+video)

  • Print
  • + Share This
  • 💬 Discuss
From the book
Marc Wandschneider looks at the types in JavaScript, with both text and video tutorials.

This excerpt features materials from the following products:

Learning Node.js: A Hands-On Guide to Building Web Applications in JavaScriptLearning Node.js: A Hands-On Guide to Building Web Applications in JavaScript

This book brings together the knowledge and JavaScript code you need to build master the Node.js platform and build server-side applications with extraordinary speed and scalability.

Learning Node.js LiveLessons (Video Training), Downloadable Version Learning Node.js LiveLessons (Video Training), Downloadable Version

Marc Wandschneider walks you through a practical introduction to Node.js, shows you how to install and run it, gives a refresher in JavaScript, shows how to write JSON servers, web applications, and client-side templates, and continues by covering database access to both SQL and NoSQL database servers.



This book and video are also available as a Video Enhanced Edition (text integrated with video) exclusively in Safari Books Online.





This section begins the review of JavaScript by looking at the types the language offers. For much of the discussion in this chapter, I use the Node.js Read-Eval-Print-Loop (REPL) to demonstrate how the code works. To help you out, I use bold to indicate things that you type into the interpreter.

client:LearningNode marcw$ node
>

Type Basics

Click the "Full screen" option in the bottom right corner of the video window for best viewing.


Node.js has a few core types: number, boolean, string, and object. The two other types, function and array, are actually special kinds of objects, but because they have extra features in the language and runtime, some people refer to these three—object, function, and array—as complex types. The types null and undefined are also special kinds of objects and are also treated specially in JavaScript.

The value undefined means that a value has not been set yet or simply does not exist:

> var x;
undefined
> x = {};
{}
> x.not_valid;
undefined
>

null, on the other hand, is an explicit assertion that there “is no value”:

> var y;
undefined
> y
undefined
> y = null;
null
>

To see the type of anything in JavaScript, you use the typeof operator:

> typeof 10
'number'
> typeof "hello";
'string'
> typeof function () { var x = 20; }
'function'
>
Constants

Constants

While Node.js theoretically supports the const keyword extension that some modern JavaScript implementations have implemented, it’s still not widely used. For constants, the standard practice is still to just use uppercase letters and variable declarations:

> var SECONDS_PER_DAY = 86400;
undefined
> console.log(SECONDS_PER_DAY);
86400
undefined
>
Numbers

Numbers

All numbers in JavaScript are 64-bit IEEE 754 double-precision floating-point numbers. For all positive and negative integers that can be expressed in 253 bits accurately, the number type in JavaScript behaves much like integer data types in other languages:

> 1024 * 1024
1048576
> 1048576
1048576
> 32437893250 + 3824598359235235
3824630797128485
> -38423538295 + 35892583295
-2530955000
>

The tricky part of using the number type, however, is that for many numeric values, it is an approximation of the actual number. For example:

> 0.1 + 0.2
0.30000000000000004
>

When performing floating-point mathematical operations, you cannot just manipulate arbitrary real numbers and expect an exact value:

> 1 - 0.3 + 0.1 == 0.8
false
>

For these cases, you instead need to check if the value is in some sort of approximate range, the size of which is defined by the magnitude of the values you are comparing. (Search the website stackoverflow.com for articles and questions on comparing floating-point numbers for good ideas of strategies on this.)

For those situations in which you absolutely need to represent 64-bit integer values in JavaScript without any chance of approximation errors, you are either stuck using the string type and manipulating these numbers by hand, or you can use one of the available modules for manipulating big integer values.

JavaScript is a bit different from other languages in that dividing a number by zero returns the value Infinity or -Infinity instead of generating a runtime exception:

> 5 / 0
Infinity
> -5 / 0
-Infinity
>

Infinity and -Infinity are valid values that you can compare against in JavaScript:

> var x = 10, y = 0;
undefined
> x / y == Infinity
true
>

You can use the functions parseInt and parseFloat to convert strings to numbers:

> parseInt("32523523626263");
32523523626263
> parseFloat("82959.248945895");
82959.248945895
> parseInt("234.43634");
234
> parseFloat("10");
10
>

If you provide these functions with something that cannot be parsed, they return the special value NaN (not-a-number):

> parseInt("cat");
NaN
> parseFloat("Wankel-Rotary engine");
NaN
>

To test for NaN, you must use the isNaN function:

> isNaN(parseInt("cat"));
true
>

Finally, to test whether a given number is a valid finite number (that is, it is not Infinity, -Infinity, or NaN), use the isFinite function:

> isFinite(10/5);
true
> isFinite(10/0);
false
> isFinite(parseFloat("banana"));
false
>
Booleans

Booleans

The boolean type in JavaScript is both simple and simple to use. Values can either be true or false, and although you technically can convert values to boolean with the Boolean function, you almost never need it because the language converts everything to boolean when needed, according to the following rules:

  1. false, 0, empty strings (""), NaN, null, and undefined all evaluate to false.
  2. All other values evaluate to true.
Strings

Strings

Click the "Full screen" option in the bottom right corner of the video window for best viewing.


Strings in JavaScript are sequences of Unicode characters (represented internally in a 16-bit UCS-2 format) that can represent a vast majority of the characters in the world, including those used in most Asian languages. There is no separate char or character data type in the language; you just use a string of length 1 to represent these. For most of the network applications you’ll be writing with Node.js, you will interact with the outside world in UTF-8, and Node will handle all the details of conversion for you. Except for when you are manipulating binary data, your experience with strings and character sets will largely be worry-free.

Strings can be wrapped in single or double quotation marks. They are functionally equivalent, and you are free to use whatever ones you want. To include a single quotation mark inside a single-quoted string, you can use \', and similarly for double quotation marks inside double-quoted strings, you can use \":

> 'Marc\'s hat is new.'
'Marc\'s hat is new.'
> "\"Hey, nice hat!\", she said."
'"Hey, nice hat!", she said.'
>

To get the length of a string in JavaScript, just use the length property:

> var x = "cat";
undefined
> x.length;
3
> "cat".length;
3
> x = null;
null

Attempting to get the length of a null or undefined string throws an error in JavaScript:

> x.length;
TypeError: Cannot read property 'length' of null
    at repl:1:2
    at REPLServer.self.eval (repl.js:109:21)
    at rli.on.self.bufferedCmd (repl.js:258:20)
    at REPLServer.self.eval (repl.js:116:5)
    at Interface.<anonymous> (repl.js:248:12)
    at Interface.EventEmitter.emit (events.js:96:17)
    at Interface._onLine (readline.js:200:10)
    at Interface._line (readline.js:518:8)
    at Interface._ttyWrite (readline.js:736:14)
    at ReadStream.onkeypress (readline.js:97:10)

To add two strings together, you can use the + operator:

> "cats" + " go " + "meow";
'cats go meow'
>

If you start throwing other types into the mix, JavaScript converts them as best it can:

> var distance = 25;
undefined
> "I ran " + distance + " kilometres today";
'I ran 25 kilometres today'
>

Note that this can provide some interesting results if you start mixing expressions a bit too much:

> 5 + 3 + " is my favourite number";
'8 is my favourite number'
>

If you really want “53” to be your favorite number, you can just prefix it all with an empty string to force the conversion earlier:

> "" + 5 + 3 + " is my favourite number";
'53 is my favourite number'
>

Many people worry that the concatenation operator + has terrible performance when working with strings. The good news is that almost all modern browser implementations of JavaScript—including Chrome’s V8 that you use in Node.js—have optimized this scenario heavily, and performance is now quite good.

String Functions

Many interesting functions are available to strings in JavaScript. To find a string with another string, use the indexOf function:

> "Wishy washy winter".indexOf("wash");
6
>

To extract a substring from a string, use the substr or splice function. (The former takes the starting index and length of string to extract; the latter takes the starting index and ending index):

> "No, they're saying Booo-urns.".substr(19, 3);
'Boo'
> "No, they're saying Booo-urns.".slice(19, 22);
'Boo'
>

If you have a string with some sort of separator character in it, you can split that up into component strings by using the split function and get an array as the result:

> "a|b|c|d|e|f|g|h".split("|");
[ 'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h' ]
>

Finally, the trim function (V8 JS) does exactly what you would expect—removes whitespace from the beginning and end of a string:

> '       cat   \n\n\n    '. trim();
'cat'
>

Regular Expressions

JavaScript has powerful regular expression support, the full details of which are beyond the scope of this book, but I briefly show how and where you can use them. A certain number of string functions can take arguments that are regular expressions to perform their work. These regular expressions can either be entered in literal format (indicated by putting the regular expression between two forward slash [/] characters) or as a call to the constructor of a RegExp object:

/[aA]{2,}/
new RegExp("[Aa]{2,}")

Both of these are regular expressions that match against a sequence of two or more of the letter a (upper- or lowercase).

To replace all sequences of two or more a’s with the letter b on string objects, you can use the replace function and write either of the following:

> "aaoo".replace(new RegExp("[Aa]{2,}"), "b");
'boo'
> "aaoo".replace(/[Aa]{2,}/, "b");
'boo'
>

Similar to the indexOf function, the search function takes a regular expression and returns the index of the first match against it, or -1 if no such match exists:

> "aaoo".search(/[Aa]{2,}/);
0
> "aoo".search(/[Aa]{2,}/);
-1
>
Objects

Objects

Click the "Full screen" option in the bottom right corner of the video window for best viewing.


Objects are one of the core workhorses of the JavaScript language, and something you will use all the time. They are an extremely dynamic and flexible data type, and you can add and remove things from them with ease. To create an object, you can use either of the following, although the latter, known as object literal syntax, is almost always preferred nowadays:

> var o1 = new Object();
undefined
> var o2 = {};
undefined
>

You can also specify the contents of objects using object literal syntax, where you can specify member names and values at initialization time:

var user = {
    first_name: "marc",
    last_name: "wandschneider",
    age: Infinity,
    citizenship: "man of the world"
};

You can add a new property to your user object by using any of the following methods:

> user.hair_colour = "brown";
'brown'
> user["hair_colour"] = "brown";
'brown'
> var attribute = 'hair_colour';
undefined
> user[attribute] = "brown";
'brown'
> user
{ first_name: 'marc',
  last_name: 'wandschneider',
  age: Infinity,
  citizenship: 'man of the world',
  hair_colour: 'brown' }
>

If you try to access a property that does not exist, you do not receive an error, but instead just get back undefined:

> user.car_make
undefined
>

To remove a property from an object, you can use the delete keyword:

> delete user.hair_colour;
true
> user
{ first_name: 'marc',
  last_name: 'wandschneider',
  age: Infinity,
  citizenship: 'man of the world' }
>

The flexibility of objects in JavaScript makes them quite similar to various associative arrays, hash maps, or dictionaries seen in other languages, but there is an interesting difference: Getting the size of an object-as-associative-array in JavaScript is a bit tricky. There are no size or length properties or methods on Object. To get around this, you can write the following (V8 JS):

> Object.keys(user).length;
4

Note that this uses a nonstandard extension to JavaScript Object.keys; although V8 and most browsers (except Internet Explorer) already support it.

Arrays

Arrays

Click the "Full screen" option in the bottom right corner of the video window for best viewing.


The array type in JavaScript is actually a special casing of the object type, with a number of additional features that make them useful and powerful. To create arrays, you can either use traditional notation or array literal syntax:

> var arr1 = new Array();
undefined
> arr1
[]
> var arr2 = [];
undefined
> arr2
[]
>

As with objects, I almost always prefer the literal syntax version, and rarely use the former.

If you use the typeof operator on arrays, you get a surprising result:

> typeof arr2
'object'
>

Because arrays are actually objects, the typeof operator just returns that, which is very frequently not what you want! Fortunately, V8 has a language extension to let you test determinatively whether or not something is an array: the Array.isArray function (V8 JS):

> Array.isArray(arr2);
true
> Array.isArray({});
false
>

One of the key features of the array type in JavaScript is the length property, used as follows:

> arr2.length
0
> var arr3 = [ 'cat', 'rat', 'bat' ];
undefined
> arr3.length;
3
>

By default, arrays in JavaScript are numerically indexed:

// this:
for (var i = 0; i < arr3.length; i++) {
    console.log(arr3[i]);
}
// will print out this:
cat
rat
bat

To add an item to the end of an array, you can do one of two things:

> arr3.push("mat");
4
> arr3
[ 'cat',  'rat',  'bat',  'mat' ]
> arr3[arr3.length] = "fat";
'fat'
> arr3
[ 'cat',  'rat',  'bat',  'mat',  'fat' ]
>

You can specify the index of the element where you want to insert a new element. If this element is past the last element, the elements in between are created and initialized with the value undefined:

> arr3[20] = "splat";
'splat'
> arr3
[ 'cat', 'rat', 'bat', 'mat', 'fat', , , , , , , , , , , , , , , , 'splat' ]
>

To remove elements from an array, you might try to use the delete keyword again, but the results may surprise you:

> delete arr3[2];

true

> arr3

[ 'cat', 'rat', , 'mat', 'fat', , , , , , , , , , , , , , , , 'splat' ]
>

You see that the value at index 2 still “exists” and has just been set to undefined.

To truly delete an item from an array, you probably should use the splice function, which takes an index and the number of items to delete. What it returns is an array with the extracted items, and the original array is modified such that they no longer exist there:

> arr3.splice(2, 2);
[  , 'mat' ]
> arr3
[ 'cat', 'rat', 'fat', , , , , , , , , , , , , , , , 'splat' ]
> arr3.length
19

Useful Functions

Click the "Full screen" option in the bottom right corner of the video window for best viewing.


There are a few key functions you frequently use with arrays. The push and pop functions let you add and remove items to the end of an array, respectively:

> var nums = [ 1, 1, 2, 3, 5, 8 ];
undefined
> nums.push(13);
7
> nums
[ 1,  1,  2,  3,  5,  8,  13 ]
> nums.pop();
13
> nums
[ 1,  1,  2,  3,  5,  8 ]
>

To insert or delete items from the front of an array, use unshift or shift, respectively:

> var nums = [ 1, 2, 3, 5, 8 ];
undefined
> nums.unshift(1);
6
> nums
[ 1,  1,  2,  3,  5,  8 ]
> nums.shift();
1
> nums
[ 1, 2, 3, 5, 8 ]
>

The opposite of the string function split seen previously is the array function join, which returns a string:

> var nums = [ 1, 1, 2, 3, 5, 8 ];
undefined
> nums.join(", ");
'1, 1, 2, 3, 5, 8'
>

You can sort arrays using the sort function, which can be used with the built-in sorting function:

> var jumble_nums = [ 3, 1, 8, 5, 2, 1];
undefined
> jumble_nums.sort();
[ 1,  1,  2,  3,  5,  8 ]
>

For those cases where it doesn’t quite do what you want, you can provide your own sorting function as a parameter:

> var names = [ 'marc', 'Maria', 'John', 'jerry', 'alfred', 'Moonbeam'];
undefined
> names.sort();
[ 'John',  'Maria',  'Moonbeam',  'alfred',  'jerry',  'marc' ]
> names.sort(function (a, b) {
        var a1 = a.toLowerCase(), b1 = b.toLowerCase();
        if (a1 < b1) return -1;
        if (a1 > b1) return 1;
        return 0;
    });
[ 'alfred',  'jerry',  'John',  'marc',  'Maria',  'Moonbeam' ]
>

To iterate over items in arrays, you have a number of options, including the for loop shown previously, or you can use the forEach function (V8 JS), as follows:

[ 'marc', 'Maria', 'John', 'jerry', 'alfred', 'Moonbeam'].forEach(function (value) {
    console.log(value);
});
marc
Maria
John
jerry
alfred
Moonbeam
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus