facebook google plus twitter
Webucator's Free JavaScript Tutorial

Lesson: Built-In JavaScript Objects

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

JavaScript has some predefined, built-in objects that enable you to work with Strings and Dates and perform mathematical operations.

Lesson Goals

  • Learn to work with the built-in String object.
  • Learn to work with the built-in Math object.
  • Learn to work with the built-in Date object.

String

In JavaScript, there are two types of string data types: primitive strings and String objects. String objects have many methods for manipulating and parsing strings of text. Because these methods are available to primitive strings as well, in practice, there is no need to differentiate between the two types of strings.

Some common string properties and methods are shown below. In all the examples, the variable webucator contains "Webucator".

Common String Properties
Property Description
length Read-only value containing the number of characters in the string.
webucator.length; //Returns 9
Common String Methods
Method Description
charAt(position) Returns the character at the specified position.
webucator.charAt(4); //Returns c
charCodeAt(position) Returns the Unicode character code of the character at the specified position.
webucator.charCodeAt(4); //Returns 99
fromCharCode(charCodes) Returns the text representation of the specified comma-delimited character code. Used with String rather than a specific String object.
String.fromCharCode(169); //Returns "©"
indexOf(substr,startPos) Searches from startPos (or the beginning of the string, if startPos is not supplied) for substr. Returns the first position at which substr is found or -1 if substr is not found.
webucator.indexOf("cat"); //Returns 4

webucator.indexOf("cat", 5); //Returns -1
lastIndexOf(substr,endPos) Searches from endPos (or the end of the string, if endPos is not supplied) for substr. Returns the last position at which substr is found or -1 is substr is not found.
webucator.lastIndexOf("cat"); //Returns 4

webucator.lastIndexOf("cat", 5); //Returns 4
substring(startPos,endPos) Returns the substring beginning at startPos and ending with the character before endPos. endPos is optional. If it is excluded, the substring continues to the end of the string.
webucator.substring(4, 7); //Returns cat

webucator.substring(4); //Returns cator
substr(startPos,len) Returns the substring of Length characters beginning at startPos. len is optional. If it is excluded, the substring continues to the end of the string.
webucator.substr(4, 3); //Returns cat

webucator.substr(4); //Returns cator
slice(startPos,endPos) Same as substring(startPos,endPos).
webucator.slice(4, 7); //Returns cat
slice(startPos,posFromEnd) posFromEnd is a negative integer. Returns the substring beginning at startPos and ending posFromEnd characters from the end of the string.
webucator.slice(4, -2); //Returns cat
split(delimiter) Returns an array by splitting a string on the specified delimiter.
var s = "A,B,C,D"; 
var a = s.split(",");
document.write(a[2]); //Returns C
toLowerCase() Returns the string in all lowercase letters.
webucator.toLowerCase() //Returns webucator
toUpperCase() Returns the string in all uppercase letters.
webucator.toUpperCase(); //Returns WEBUCATOR

You can see these examples in a browser by opening BuiltInObjects/Demos/StringPropertiesAndMethods.html.

Math

The Math object is a built-in static object. The Math object's properties and methods are accessed directly (e.g., Math.PI) and are used for performing complex math operations. Some common math properties and methods are shown below:

Common Math Properties
Property Description
Math.PI The value of Pi (Value of Pi)
Math.PI; //3.141592653589793
Math.SQRT2 Square root of 2.
Math.SQRT2; //1.4142135623730951
Common Math Methods
Method Description
Math.abs(number) Absolute value of number.
Math.abs(-12); //Returns 12
Math.ceil(number) number rounded up.
Math.ceil(5.4); //Returns 6
Math.floor(number) number rounded down.
Math.floor(5.6); //Returns 5
Math.max(numbers) Highest Number in numbers.
Math.max(2, 5, 9, 3); //Returns 9
Math.min(numbers) Lowest Number in numbers.
Math.min(2, 5, 9, 3); //Returns 2
Math.pow(number, power) number to the power of power.
Math.pow(2, 5); //Returns 32
Math.round(number) Rounded number.
Math.round(2.5); //Returns 3
Math.random() Random number between 0 and 1.
Math.random();
//Returns random
//number from 0 to 1

You can see these examples in a browser by opening BuiltInObjects/Demos/MathPropertiesAndMethods.html.

Method for Generating Random Integers

Because Math.random() returns a decimal value greater than or equal to 0 and less than 1, we can use the following code to return a random integer between low and high, inclusively:

var low = 1;
var high = 10;
var rndDec = Math.random();
var rndInt = Math.floor(rndDec * (high - low + 1) + low);

Date

The Date object has methods for manipulating dates and times. JavaScript stores dates as the number of milliseconds since January 1, 1970. The sample below shows the different methods of creating date objects, all of which involve passing arguments to the Date() constructor.

Code Sample:

BuiltInObjects/Demos/DateObject.html
---- C O D E   O M I T T E D ----

<body>
<h1>Date Object</h1>
<h2>New Date object with current date and time</h2>
<pre>
//Syntax: new Date();
var now = new Date();
</pre>
<strong>Result:</strong>
<script>
	var now = new Date();
	document.write(now);
</script>

<h2>New Date object with specific date and time</h2>
<pre>
//Syntax: new Date("month dd, yyyy hh:mm:ss);
var redSoxWin = new Date("October 21, 2004 12:01:00");
</pre>
<strong>Result:</strong>
<script>
	var redSoxWin = new Date("October 21, 2004 12:01:00");
	document.write(redSoxWin);
</script>

<pre>
//Syntax: new Date(year, month, day, hours, min, sec, millisec);
redSoxWin = new Date(2004, 9, 21, 12, 01, 00, 00);
</pre>
<strong>Result:</strong>
<script>
	redSoxWin = new Date(2004, 9, 21, 12, 01, 00, 00);
	document.write(redSoxWin);
</script>
</body>
</html>

Code Explanation

This page is shown in a browser below.Page in Browser

A few things to note:

  1. To create a Date object containing the current date and time, the Date() constructor takes no arguments.
  2. When passing the date as a string to the Date() constructor, the time portion is optional. If it is not included, it defaults to 00:00:00. Also, other date formats are acceptable (e.g., "3/2/2017" and "03-02-2017").
  3. When passing date parts to the Date() constructor, dd, hh, mm, ss, and ms are all optional. The default for dd is 1; the other parameters default to 0.
  4. Months are numbered from 0 (January) to 11 (December). In the example above, 9 represents October.

Some common date methods are shown below. In all the examples, the variable rightNow contains "Thu Mar 02 00:23:54:650 EDT 2017".

Common Date Methods
Method Description
getDate() Returns the day of the month (1-31).
rightNow.getDate();
//Returns 2
getDay() Returns the day of the week as a number (0-6, 0=Sunday, 6=Saturday).
rightNow.getDay();
//Returns 4
getMonth() Returns the month as a number (0-11, 0=January, 11=December).
rightNow.getMonth();
//Returns 2
getFullYear() Returns the four-digit year.
rightNow.getFullYear();
//Returns 2017
getHours() Returns the hour (0-23).
rightNow.getHours();
//Returns 0
getMinutes() Returns the minute (0-59).
rightNow.getMinutes();
//Returns 23
getSeconds() Returns the second (0-59).
rightNow.getSeconds();
//Returns 54
getMilliseconds() Returns the millisecond (0-999).
rightNow.getMilliseconds();
//Returns 650
getTime() Returns the number of milliseconds since midnight January 1, 1970.
rightNow.getTime();
//Returns 1488432234650
getTimezoneOffset() Returns the time difference in minutes between the user's computer and GMT.
rightNow.getTimezoneOffset();
//Returns 300
toLocaleString() Returns the Date object as a string.
rightNow.toLocaleString();
//Returns 3/2/2017, 12:23:54 AM
toGMTString() Returns the Date object as a string in GMT timezone.
rightNow.toGMTString();
//Returns Thu, 02 Mar 2017 05:44:30 GMT

You can see these examples in a browser by opening BuiltInObjects/Demos/DateMethods.html.

The typeof Operator

The typeof operator is used to find out the type of a piece of data. The screenshot below (of BuiltInObjects/Demos/typeof.html) shows what the typeof operator returns for different data types: Type of Operator

Helper Functions

Some languages have functions that return the month as a string. JavaScript doesn't have such a built-in function. The sample below shows a user-defined "helper" function that handles this and how the getMonth() method of a Date object can be used to get the month.

Code Sample:

BuiltInObjects/Demos/MonthAsString.html
---- C O D E   O M I T T E D ----

<script>
	function monthAsString(num){
		var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		return months[num-1];
	}

	function enterMonth(){
		var userMonth = prompt("What month were you born?", "");
		alert("You were born in " + monthAsString(userMonth) + ".");
	}
	
	function getCurrentMonth(){
		var today = new Date();
		alert(monthAsString(today.getMonth()+1));
	}
</script>
---- C O D E   O M I T T E D ----

Returning the Day of the Week as a String

Duration: 15 to 25 minutes.

In this exercise, you will create a function that returns the day of the week as a string.

  1. Open BuiltInObjects/Exercises/DateUDFs.html for editing.
  2. Write a dayAsString() function that returns the day of the week as a string, with "0" returning "Sunday", "1" returning "Monday", etc.
  3. Write an enterDay() function that prompts the user for the day of the week (as a number) and then alerts the string value of that day by calling the dayAsString() function.
  4. Write a getCurrentDay() function that alerts today's actual day of the week according to the user's machine.
  5. Add a "CHOOSE DAY" button that calls the enterDay() function.
  6. Add a "GET CURRENT DAY" button that calls the getCurrentDay() function.
  7. Test your solution in a browser.

Solution:

BuiltInObjects/Solutions/DateUDFs.html
---- C O D E   O M I T T E D ----

<script>
---- C O D E   O M I T T E D ----
	function dayAsString(num){
		var weekDays = [];
		weekDays[0] = "Sunday";
		weekDays[1] = "Monday";
		weekDays[2] = "Tuesday";
		weekDays[3] = "Wednesday";
		weekDays[4] = "Thursday";
		weekDays[5] = "Friday";
		weekDays[6] = "Saturday";
		
		return weekDays[num-1];
	}

---- C O D E   O M I T T E D ----


	function getCurrentMonth(){
		var today = new Date();
		alert(monthAsString(today.getMonth()+1));
	}
	
	function enterDay(){
		var userDay = prompt("What day of the week is it?", "");
		alert("Today is " + dayAsString(userDay) + ".");
	}

	function getCurrentDay(){
		var today = new Date();
		alert(dayAsString(today.getDay()+1));
	}
</script>

---- C O D E   O M I T T E D ----

	<input type="button" value="CHOOSE MONTH" onclick="enterMonth();">
	<input type="button" value="GET CURRENT MONTH" onclick="getCurrentMonth();"><br>
	<input type="button" value="CHOOSE DAY" onclick="enterDay();">
	<input type="button" value="GET CURRENT DAY" onclick="getCurrentDay();">

---- C O D E   O M I T T E D ----

Code Explanation