[JavaScript] Builtin Objects and Functions

Even though jQuery provides a lot of features you can use, there are some really useful functions in JavaScript. Also JavaScript can be regarded as a OO language and each data type is an object. Therefore, you can access properties and methods of a type.  

1. “Array” Object

An array is an object too. It provides the “length” property and a couple of useful methods.

  • toString(): converts an array to a string, and returns the result
  • concat(array2, array3, …, arrayX): joins two or more arrays, and returns a new array
  • join(separator): joins all elements of an array into a string, the default separator is comma
  • slice(start, end): selects a part of an array, and returns the new array, the element at the end index is not included into a result, just omit the end index if you want to slice an array to the end element.
function arrayTest() {
  var arr1 = ['Hello', 'World'];
  var arr2 = ['Morning', 'Afternoon', 'Evening', 'Night'];
  alert('Length arr1 = ' + arr1.length+', Length arr2 = ' + arr2.length);
  var arr3 = arr1.concat(arr2);
  alert('Length arr3 = ' + arr3.length + ' - ' + arr3.toString());
  var arr4 = arr1.join('\t');
  alert(arr4);
  var arr5 = arr2.slice(1, 3);
  alert('Length arr5 = ' + arr5.length + ' - ' + arr5.toString());
}

 

2. “Math” Object

When you do some methematical calculations, you can use the methods provided by a “Math” object. All properties and methods are called by using a “Math” object without creating it explictly. You can think of them as static members of “Math” properties.

  • E: Euler’s number (2.718 …)
  • PI: (3.14159…)
  • SQRT2: Square root of 2 (1.414…)

– Methods –

  • abs(x): the absolute value
  • cos(x): the cosine of x, in radians
  • sin(x): the sine of x, in radians
  • tan(x): the tangent of an angle
  • acos(x): the arccosine of x, in radians
  • asin(x): the arcsine of x, in radians
  • atan(x): the arctangent of x as a numeric value between -PI/2 and PI/2 radians
  • ceil(x): rounded upwards the nearest integer (bigger than x)
  • floor(x): rounded downwards to the nearest integer (less than x)
  • round(x): rounded to the nearest integer
  • log(x):  the natural logarithm
  • exp(x): Exponential
  • pow(x,y): x to the power of y
  • sqrt(x): the square root of x
  • max(x,y,z,…,n): the highest value
  • min(x,y,z,…,n): the lowest value
  • random(): a random number between 0 and 1
function mathTest() {
  alert('ceil(1.6) = ' + Math.ceil(1.6)
    + ', floor(1.6) = ' + Math.floor(1.6)
    + ', round(1.6) = ' + Math.round(1.6));
  alert('pow(sqrt2, 2) = ' + Math.pow(Math.SQRT2, 2).toFixed(2));
  alert('max(1,2,3,4) = ' + Math.max(1, 2, 3, 4) +
', min(1,2,3,4) = ' + Math.min(1, 2, 3, 4));
}

 

3. “Number” Object

The “Number” object is a wrapper for primitive numeric values.

– Properties –

  • MAX_VALUE: the largest number possible in JavaScript
  • MIN_VALUE: the smallest number possible in JavaScript
  • NEGATIVE_INFINITY: negative infinity (returned on overflow)
  • POSITIVE_INFINITY: infinity (returned on overflow)

– Methods –

  • toExponential(x): converts a number into an exponential notation
  • toFixed(x): formats a number with x numbers of digits after the decimal point
  • toPrecision(x): formats a number to x length
  • toString(): converts a Number object to a string
function numberTest() {
  var num = 10.345;
  alert('MAX_VALUE = ' + Number.MAX_VALUE
    + ', MIN_VALUE = ' + Number.MIN_VALUE);
  alert('NEGATIVE_INFINITY = ' + Number.NEGATIVE_INFINITY
    + ', POSITIVE_INFINITY = ' + Number.POSITIVE_INFINITY);
  alert('10.345.toExponential() = ' + num.toExponential());
  alert('10.345.toFixed(1) = ' + num.toFixed(1));
  alert('10.345.toPrecision(6) = ' + num.toPrecision(6));
}

 

4. “String” object

A string has the “length” property.

– Methods –

  • charAt(index): the character at the specified index
  • charCodeAt(index): the Unicode of the character at the specified index
  • concat(s2, s3, …, sX): joins two or more strings, and returns the joined strings
  • indexOf(searchstring, start): the position of the first occurrence
  • lastIndexOf(searchstring, start): the position of the last occurrence
  • split(separator): splits a string into an array of substrings
  • substr(start,length): extracts the characters from a string, beginning at a specified start position, and through the specified number of character
  • substring(from, to): extracts the characters from a string, between two specified indices
  • toLowerCase(): converts a string to lowercase letters
  • toUpperCase(): converts a string to uppercase letters
function stringTest() {
  var s1 = 'Hello, World';
  var s2 = 'Good Morning';
  alert('(Hello, World).charAt(1) = ' + s1.charAt(1) +
', (Hello, World).charCodeAt(1) =' + s1.charCodeAt(1));
  var s3 = s1.concat(s2);
  alert('Length s3 = ' + s3.length + ' - ' + s3);
  alert('(Hello, World).substr(1,3) = ' + s1.substr(1, 3) +
', (Hello, World).substring(1,3) =' + s1.substring(1, 3));
  alert(s1.toUpperCase());
}

The “String” object lacks the very common and widely used string method ‘trim()’. If you want to remove the whitespace from the beginning and end of a string, you can use jQuery’s “trim()” function.

function trimTest() {
  var s1 = "  Hello, World   ";
  alert("(  Hello, World   ).length = " + s1.length);
  var s2 = jQuery.trim("  Hello, World   ");
  alert("jQuery.trim(  Hello, World   ).length = " + s2.length);
}

 

5. Date Object

Date is always a pain. It’s not a number or a text. It’s really hard to parse becuase there exist so many different formats.

In JavaScript, you need to create a “Date” object using a constructor.

– get Methods –

  • getFullYear(): the year (four digits)
  • getMonth(): the month (from 0-11)
  • getDate(): the day of the month (from 1-31)
  • getDay(): the day of the week (from 0-6)
  • getHours(): the hour (from 0-23)
  • getMinutes(): the minutes (from 0-59)
  • getSeconds(): the seconds (from 0-59)
  • getMilliseconds(): the milliseconds (from 0-999)
  • getTime(): the number of milliseconds since midnight Jan 1, 1970

– set Methods –

  • setFullYear(): the year (four digits)
  • setMonth(): Sets the month (from 0-11)
  • setDate(): the day of the month (from 1-31)
  • setHours(): the hour (from 0-23)
  • setMinutes(): the minutes (from 0-59)
  • setSeconds(): the seconds (from 0-59)
  • setMilliseconds(): the milliseconds (from 0-999)
  • setTime(): a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970

– Convert Methods –

  • toDateString(): converts the date portion to a string
  • toTimeString(): converts the time portion to a string
  • toString(): converts a Date object to a string
  • toUTCString(): converts a Date object to a string, according to universal time
  • toLocaleDateString(): returns the date portion as a string, using locale conventions
  • toLocaleTimeString(): returns the time portion as a string, using locale conventions
  • toLocaleString(): converts a Date object to a string, using locale conventions
  • parse(): parses a date string and returns the number of milliseconds since midnight of January 1, 1970
function dateTest() {
  var now = new Date();
  alert(now.toString());
  alert('YYYY/MM/DD HH:MM = '
    + now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + '/ '
    + now.getHours() + ':' + now.getMinutes() );
}

Be careful with the month. It starts from 0, not 1.

 

6. Window Object

Window Object represents an open window in a browser and has many properties and methods. You do not specify an object name “Window” to refer its methods or properties.

– Methods –

  • alert(msg): displays an message box with an OK button
  • confirm(msg): displays a dialog box with an OK and a Cancel button
  • prompt(msg, defaultText): displays a dialog box that prompts the user for input
function windowTest() {
  var name = prompt('Please enter your name:', 'your name here');
  if (name) {
    var choice = confirm('Is your name ' + name + '?');
    if (choice) {
      alert('Good!');
    } else {
      alert('Bad!');
    }
  }
}

 

7. Global Functions

Global functions can be used anywhere in the JavaScript code. In many times, global functions are confused with “Window” methods because both do not require any object name. In fact, global functions can be used with all built in objects.

  • isNaN(value): determines whether a value is an illegal number
  • parseFloat(string): parses a string and returns a floating point number
  • parseInt(string): parses a string and returns an integer
function globalTest() {
  var num = 10.5;
  var s1 = 'seven';
  var s2 = '10.5';
  alert('isNaN(10.5) = ' + isNaN(num) + ', isNaN(seven) = ' + isNaN(s1));
  alert('parseFloat(10.5) = ' + parseFloat(s2) +
', parseInt(seven) = ' + parseInt(s2));
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s