Chapter 12: Built-in Objects and Functions
JavaScript has a good range of standard (built-in) objects and functions and this chapter is intended to identify the most common together with their methods.
You might like to try out some of the code samples and features using the Chrome developer tools Snippets tab.
Functions
We can start our review of JavaScript’s built-in functions with the one you should not use.
eval()
The eval() function evaluates JavaScript code passed as a string argument. This can be a straightforward as:
var x = 40, y = 2; alert(eval("x + y"));
The ability to construct and execute new JavaScript statements within a block of code looked like a great scripting language feature, particularly for a language used on web pages where a web server might send data as a string ready to be processed by the page JavaScript. The problem with eval() is that if a malicious party can find a way to take control of the string then they can execute code of their own devising with the same permissions on your PC as the web page. The right way to manage structured data flowing from a web server is to use JSON. This chapter includes a brief introduction to JSON.
isNaN()
This function can be used to check if a variable holds a value that is not a number. If the value passed as an argument to this function does not have the type Number then it is coerced to a number and then that value tested to see if it is NaN (Not a Number). Thus, a string might return false, implying it is a number, if it can be coerced into a number.
An alternative is to use the Number.isNaN() method (see later in this chapter).
isNaN(true); // false isNaN(42); // false isNaN(“42”); // false, '42' is converted to a number isNaN("42,5"); // true, as no support for European decimal format isNaN(''); // false, empty string converted to 0 isNaN(" "); // false, space converted to 0 isNaN("XYZ"); // true
parseFloat()
This function parses the argument (after converting it to a string if required) and returns a floating-point number or NaN. The function ignores leading and trailing spaces and any non-numeric characters following a number.
alert(parseFloat("43.693")); alert(parseFloat("123.45abc")); alert(parseFloat("FF"));
The Number object constructor can be used for stricter floating-point parsing.
parseInt(value, base)
The parseInt() function is similar to the parseFloat() function but returns an integer value rather than a floating point number. This function often catches out programmers new to JavaScript as it parses an integer assuming a specified base and the default is not necessarily 10. It is safest to always specify the number base in a second argument (the range is 2 to 36).
alert(parseInt("24px", 10)); alert(parseInt("42.6", 10)); alert(parseInt("1101", 2)); alert(parseInt("fe", 16));
Numbers and such
Number
A basic JavaScript type of number can be created using the Number() constructor which is stricter than the parseFloat() function.
let x = new Number("123.45"); alert(x + 1); const x = new Number("123px"); alert(x + 1);
The Number object has several properties.
Number | |
.EPSILON | The difference between 1 and the smallest floating point number greater than 1. |
.MAX_SAFE_INTEGER | JavaScript floating point numbers can only represent integers between minus (253 – 1) and plus (253 -1) exactly. |
.MIN_SAFE_INTEGER | See above |
.MAX_VALUE | The largest positive value that can be represented in a JavaScript floating point number. Values greater than this are represented as Infinity. |
.MIN_VALUE | The smallest positive value that can be held by a floating point number. |
.NaN | Not a Number |
.POSITIVE_INFINITY | The same value as the global Infinity property |
.NEGATIVE_INFINITY | The negative equivalent of the global Infinity value. |
The Number object has a range of Methods:
Number | |
.isNaN() | Stricter than the isNaN() function |
.isInteger() | Determines if the argument is an integer |
.isFinite() | Tests if the argument is a finite number |
.isSafeInteger() | Tests if the argument is an integer in the safe range. |
.parseFloat() | The same as the function parseFloat() |
.parseInt() | The same as the function parseInt() |
In addition, number instances have a range of available methods which include:
Any number instance | |
.toFixed(digits) | Returns a string with the number formatted to the specified number of decimal places |
.toPrecision(places) | Returns a string with the number formatted to the specified number of significant figures. |
.toString() | Returns a string representing the number. Takes an optional argument specifying the number base but defaults to base 10. |
Math
This JavaScript object has properties representing mathematical constants together with a range of methods. We have used a lot of these in this book.
Constants | |
Math.PI | A representation of Pi (aprox. 3.14159) |
Math.LN10 | The natural logarithm of 10 (aprox. 2.303) |
Math.LN2 | The natural logarithm of 2 |
Math.E | Euler’s constant |
Math.SQRT2 | The square root of 2 |
Method | |
Math.abs() | Returns the absolute value of a numeric argument |
Math.floor() | Returns the largest integer less than or equal to a number |
Math.ceil() | Returns the smallest integer greater than or equal to a number. |
Math.cos() | Returns the cosine of a number |
Math.sin() | Returns the sine of a number |
Math.tan() | Returns the tangent of a number |
Math.hypot() | Returns the square root of the sum of the squares of its arguments |
Math.max() | Returns the largest of a group of numbers passed as arguments. |
Math.min() | Returns the smallest of a group of numbers passed as arguments |
Math.pow(a, b) | Returns a raised to the power b |
Math.random() | Returns a pseudo random number between zero and one. |
Math.round() | Returns a value rounded to the nearest integer. Point 5 always rounds up. |
Math.sign() | Returns 1 for positive numbers, -1 for negative numbers and 0 for a zero argument. |
Math.sqrt() | Returns the square root of a number. |
Math.log10() | Returns the base 10 logarithm of a number |
Math.log2() | Returns the base 2 logarithm of a number |
Also includes: Math.acos(), Math.acosh(), Math.asin(), Math.asinh(), Math.atan(), Math.atanh(), Math.atan2(), Math.cosh(), Math.sinh(), Math.tanh() |
Date
Representing and manipulating dates can be surprisingly complicated although the JavaScript Date objects starts from a simple foundation. Dates are integer values representing the number of milliseconds since midnight at the start of January 1st. 1970 UTC. We have to add UTC there, as dates on a given device take into account the local time zone.
Date() can be used as a constructor to create a new Date object which can be set using a range of methods. Date instances inherit from the Date object.
new Date() | Creates a new Date object instance |
new Date(number) | Passed a number representing the number of milliseconds since the base date. |
new Date(string) | Passed a string representing the date (same as Date.parse()) |
new Date(year, month index, optional [day, hours, minutes, seconds, milliseconds] | Year values 0 to 99 are assumed to be 1900 to 1999. For later years provide 4 digits. The month index starts with 0 for January and 11 becomes December. |
Date Object Methods | |
Date.now() | Returns the number corresponding to the current date/time in milliseconds since 01/01/1970 |
Date.parse() | Returns a numeric date value obtained by parsing a date string (e.g. “03 Mar 2019 12:25:00 GMT”) Not recommended as implementations vary. |
Date.UTC() | Returns a numeric date value based upon Year, month index etc. the same as the optional Date() constructor. |
Date instance methods | |
.getDate() | Returns the day of the month (1 to 31) for the date. |
.getDay() | Returns the day of the week Sunday to Saturday (0 to 6) |
.getFullYear() | Returns the 4 digit year |
.getMonth() | Returns the month index (0 to 11) |
.getHours() | Returns the hour component of a date (0 to 23) |
.getMinutes() | Returns the minutes component (0 to 59) |
.getSeconds() | Returns the seconds component (0 to 59) |
.getMilliseconds() | Returns milliseconds component (0 to 999) |
.getYear() | Returns 2 digit year – use .getFullYear() instead. |
.getTime() | Returns the total number of milliseconds stored in the date instance. |
.getTimezoneOffset() | Returns the local (to PC) time zone offset from UTC in minutes (they are not all whole hours). |
.getUTCDate(), .getUTCDay(), .getUTCFullYear() etc. | Equivalent to the methods above but corrected to UTC and not local (PC) time zone. |
Then a group of methods that can be used to set or amend a date instance. | |
.setdate() | Sets the day of the month in a date instance |
.setFullYear() | Sets the year component of a date to the 4 digit argument |
.setMonth() | Sets the month index value |
.setHours() | Sets the hours component of a date |
.setMinutes() | Sets the minutes of a date instance |
.setSeconds() | Sets the seconds in a date instance |
.setMilliseconds() | Sets the milliseconds component of a date instance |
.setTime() | Sets a date instance to the supplied number of milliseconds |
.setUTCDate() etc | UTC equivalents exist for these methods |
Then there are a range of methods to return Date instance values as formatted strings.
.toDateString() | Returns the date (not time) portion of a date value as a human sensible string |
.toLocaleDateString(loc) | Returns the date in a localised date format. An argument string of ‘en-US’ would return month/day/Year while ‘en-GB’ would give day/month/year. Many options available. |
.toTimeString() | Returns the time portion of a date as a formatted string |
String
The greater part of the JavaScript code in this book has been about manipulating numbers and objects with very little work with strings. Strings are likely to become a key element when communicating complex ideas or situations to humans.
All data processed by a computer is held as one or more (binary) number. Every image, sound file or string is encoded in some way so that it can be stored and manipulated as a set of numbers. JavaScript strings are encoded using UTF-16 which is one of the Unicode variants. Unicode was introduced to the programming world to tackle the encoding of the huge range of characters used throughout the world. When early general-purpose computing got under way (principally) in the UK and USA it was felt sufficient to be able to encode the English language character set and this was easily done using just 8 bits (one byte) per character. Even early on, this system had to be stretched to incorporate a wider range of symbols and accented characters. Eventually the world started to adopt Unicode where each character is encoded as one or two 16 bit units.
Strings frequently appear in JavaScript code as a sequence of characters between a matched pair of quote marks. The programmer’s term for these objects is “string literals”. String literals sometimes need to include special characters including Unicode characters that are not available on your keyboard. This is achieved using escape notation and the escape character is a backslash (\). One or two of the standard escaped characters exist for historical reasons and have been inherited from the C programming language.
\’ | Used to embed a single quote mark within a string |
\” | As above but for a double quote mark |
\\ | As the backslash is the escape character then if you actually want a backslash in your string then it needs escaping. |
\n | New line – can be used to format text in some HTML controls where the \n character starts a new line. |
\r | Carriage return |
\v | Vertical tab (historical) |
\t | Horizontal tab |
\b | Backspace – historically used to overtype one character with another on printers. |
\f | Form feed (printers again) |
\uXXXX | A UTF-16 character where XXXX is 4 hexadecimal digits representing the character code |
If your program code needs to include a long string literal then you might want to break it up over multiple lines. This can be done using the backslash character as a continuation mark.
let myString = "If debugging is the process of removing \ software bugs, then programming must be the \ process of putting them in. (Edsger Dijkstra)";
The same thing could be achieved with an expression.
let myString = "A good programmer is someone who " + "always looks both ways before crossing " + "a one-way street. (Doug Linder)" alert(myString.length);
That last sample also illustrated that the string type has a length property that returns the number of characters (not the number of bytes) used to store the string. The string type also has a large and useful range of methods. Some string methods make changes to the string that calls them but others return a new string with any changes applied. The difference is important for how you construct your code.
.charAt(index) | Returns the character at the index position (first char is at position 0) in a string |
.charCodeAt(index) | Returns an integer (between 0 and 65535) which is the character code at the index position in a string. |
.concat(str [,str…]) | Concatenates the string arguments to the calling string and returns a new string (see sample code below) |
.includes(str [, start]) | Returns true if the calling string includes the string argument or false. An optional start position for the search can be supplied. |
.endsWith(str) | Returns true of the calling string ends with the string argument, otherwise false |
.startsWith(str) | Returns true if the calling string starts with the string argument otherwise returns false |
.indexOf(str [.start]) | Returns the index of the string argument in the calling string or -1 if not found. An optional start position for the search can be supplied. |
.lastIndexOf(str [,start]) | Returns the index of the last occurrence of the string argument in the calling string |
.padEnd(length, [,str]) | Pads a string to the specified length. Uses spaces or the optionally specified string. See sample. |
.padStart(length, [.str]) | As above but pads the start of the calling string. |
.repeat(num) | Returns a string containing the calling string repeated the specified number of times. |
.replace(searchstr, withstr) | Replaces occurrences of the first argument with the second argument returning a new string. |
.slice(from [,to]) | Returns a section of a string starting at the from index to the end of the string (or the optional to index value). |
.split(separator) | Returns an array of strings split from the calling string at the specified separator. |
.substring(start [,end]) | Returns a new string which is a substring of the calling string starting at the start index position to the end or the optional end index position. |
.toLowerCase() | Returns a new string with all of the characters in the calling string converted to lower case. |
.toUpperCase() | Returns a new string with all of the characters in the calling string converted to upper case |
.trim() | Returns a new string with all white space characters removed from the start and end of the calling string. |
.trimStart() .trimLeft() | Both return a new string with whitespace characters at the start of the calling string removed. |
.trimEnd() .trimRight() | Both return a new string with whitespace characters at the end of the calling string removed. |
.concat()
let h = "Hello"; let w = "World"; let c = h.concat(" ", w); alert(h); alert(c);
.padEnd()
alert("foo".padEnd(10) + "!"); alert("bar".padEnd(10, "stegasuarus"));
.repeat()
let defStr = "01".repeat(10); alert(defStr);
.replace()
let strA = "This would be this if that was"; let strB = strA.replace("this", "that"); alert(strA); alert(strB); // note case sensitive
.split()
let strA = "This would be this if that was"; let arrB = strA.split(" "); alert(arrB.length); // length of array holding the individual words alert(strA.length); // number of characters in the string
Collections
Array
In this book we have met a lot of arrays. We have seen arrays of numbers, strings and objects plus arrays of arrays (two dimensional arrays). We have also used some of the built-in methods that come for free but certainly not all so here is a list of those most likely to be of use.
A new array can be created very simply. The first code line below creates a new empty array. The second creates a new array with two string elements. The third line demonstrates that arrays can contain a mix of types (probably not a good idea in most instances).
let arrayA = []; // new empty array let arrayB = ["first element", "second element"]; let arrayC = ["hello", 15, "mixed", 27]; // mixed types arrayA[0] = 56; arrayA[99] = 42; alert(arrayA.length);
Array element values can be set using array notation as the code above demonstrated for arrayA which resulted in an array with 100 elements although 98 of the array elements are undefined.
Array instance methods | |
.push(val1 [, val2]) | Adds one or more elements to the end of an array, returns the revised array length. |
.pop() | Removes and returns the last element of an array. |
.shift() | Removes and returns the first element in an array. |
.unshift(val1 [, val2]) | Adds one or more elements to the beginning of an array and returns the revised array length |
.sort() | Sorts the elements of an array in place. The default sort is in ascending order using string comparison. Optionally the name of a comparison function can be supplied as an argument. Check the book index for examples. |
.reverse() | Reverses the elements of an array |
.includes(value) | Returns true if an array contains the suppled value in one of the elements, otherwise false. |
.indexOf(value) | Returns the first index of an array where an element equals the suppled value, otherwise -1 |
.join([sep]) | Returns a string by concatenating all of the elements of an array separated by a comma or by a suppled separator. |
.map(func) | Returns a new array where each element has been processed by a function supplied as an argument. |
.reduce(func) | Returns a single value generated by applying a supplied function to each element of an array. |
.sort() and .reverse();
let arrayX = [4, 7, 9, 6, 3, 2, 0, 1]; arrayX.sort(); alert(arrayX); arrayX.reverse(); alert(arrayX);
Sort using a function as upper case “B” is less than lower case “a”.
function comp(a,b){ a = a.toUpperCase(); b = b.toUpperCase(); if(a < b) {return -1;} if(a > b) {return 1;} return 0; } let arrayS = ["birds", "animals", "Air", "Ball", "bid", "bat"]; arrayS.sort(); alert(arrayS); arrayS.sort(comp); alert(arrayS);
.map(), .reduce()
let arrayX = [1, 2, 4, 8, 16, 32]; let arrayY = arrayX.map(x => x * 2); let z = arrayY.reduce((acc, cur) => acc + cur); alert(z);
In the above sample, .map() applied a function that doubled the value in each of the array elements. The .reduce() method accumulated and returned the sum of the element values.
The Map Object
A Map object holds key and value pairs. Both keys and their associated values can be of any type. Entries are stored in the order they are added.
If you look back to the section on arrays above you will see a code example where an array was populated with two elements but ended up with a length of 100. The following code sample shows how to use a Map object to store the same values. Note that a map object has a size property rather than a length (OK, there is a length but it is not useful).
let aMap = new Map(); aMap.set(0, 56); aMap.set(99, 42); alert(aMap.size); alert(aMap.get(99));
Map instance methods | |
.clear() | Removes all of the elements (key value pairs) stored in a map instance. |
.delete(key); | Removes the element identified by a key value from the map |
.entries() | Returns an iterator object that can be used to access the map elements in insertion order. (See below) |
.forEach(func) | Executes the supplied function for each key value pair in the map |
.get(key) | Returns the value associated with the specified key |
.has(key) | Returns true if an element in the Map has the specified key, otherwise false. |
.set(key, value) | Adds (or updates) a key value pair. |
.keys() | Returns an iterator object that can be used to enumerate the keys stored in the map. |
.values() | Returns an iterator object that can be used to enumerate the values stored in a map. |
.entries()
let aMap = new Map(); aMap.set(0, "Start"); aMap.set(1, "one"); aMap.set(2, "thing"); aMap.set(3, "after"); let iterator = aMap.entries(); for(let i = 0; i < aMap.size; i++){ alert(iterator.next().value); }
The Set Object
A Set object can be used to store unique values of any type. The set ignores the addition of duplicate entries. Warning: all JavaScript objects are unique even if they contain member values each identical to another object.
let aSet = new Set(); aSet.add(2); aSet.add(6); aSet.add(2); alert(aSet.size); alert(aSet.has(6));
Like Map objects, Set objects have a size property. They also have a similar group of methods.
Set instance methods | |
.add(value) | Adds a value to a set if it is not already an element of the set. |
.clear() | Removes all of the values stored in a set |
.delete(value) | Deletes a specified value from the set and returns true if the value was found and otherwise false. |
.has(value) | Returns true if the set contains the value and otherwise false. |
.entries() | Returns an iterator in a similar way to the Map. Oddly, it treats each value as if it were a key as well as a value. values are in insertion order. |
.values() | Returns an iterator that can be used to enumerate the values stored in a set. |
.forEach(func) | Applies a function to each value stored in a set. |
.entries()
let aSet = new Set(); aSet.add(2); aSet.add(6); aSet.add(2); let iterator = aSet.entries(); for(let value of iterator){ alert(value); }
JavaScript Object Notation (JSON)
JSON is a way of serialising (expressing as a string) JavaScript objects, arrays, strings, numbers and Boolean values. The JavaScript JSON object contains handy methods for parsing and serialising JavaScript type instances.
JSON is text that looks very similar to the way we define objects when writing JavaScript code. Indeed, that is implied by the name. An object storing details of an individual person, as JSON, might look like:
{ "first name": "John", "last name": "Smith", "age": 32, "address": { "street address": "1 The Avenue", "town": "York", "county": "Yorkshire", "postal code": "YO23 7HB" }, "phone numbers": [ { "type": "home", "number": "0345 120 0805" }, { "type": "mobile", "number": "07967 006743" } ], "sex": { "type": "male" } }
If we presented that as a string to the JSON.parse() method we would be returned an object containing the specified values. [The JSON shown shortened and with \ string continuation characters and note the single quotation marks to delineate the string.]
let aJson = '{\ "first name": "John",\ "last name": "Smith",\ "sex": {\ "type": "male"\ }\ }'; let anObj = JSON.parse(aJson); alert(anObj["first name"]);
The JSON.stringify() method can be passed an object to return a JSON representation of that object.
let mObj = { firstName: "Alfred", lastName: "Smith", phoneNumbers: [ {type: "home", number: "0345 120 0805"}, {type: "mobile", number: "07967 006743"} ], address: { street: "1 The Avenue", town: "York", postalCode: "YO23 7HB" } }; alert(JSON.stringify(mObj));
JSON is most commonly used to pass data between a client process running in a browser and a web server or service. JSON is also used to store JavaScript objects in a database.