Home > Articles > Web Development

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

Marc Wandschneider looks at the types in JavaScript, with both text and video tutorials.
From the book

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020