Matthew Tyson
Contributing writer

Using JavaScript’s built-in objects

how-to
Oct 25, 20238 mins
JavaScriptSoftware Development

Built-in JavaScript objects and functions are ones you'll use all the time. Here's how to use Object, JSON, String, Math, Date, and console in your JavaScript programs.

Mathematics, equations, pie chart, objects
Credit: Chekyravaa/Shutterstock

JavaScript’s built-in objects include Object, JSON, console, String, Math, Date, and the window and global objects. These are some of the most important and useful parts of the JavaScript language. Together, they are essential elements of the programming environment in both the browser and server-side platforms like Node.

The Object in JavaScript

Object is the root object of all prototypes in JavaScript. Aside from providing the foundation for the JavaScript object model, Object imparts important methods such as toString() and assign(). Every object in JavaScript has these methods thanks to Object

The toString() method is very simple. You can call it on anything, and if nothing has been defined, it’ll use the default version. Many objects, like arrays, do define their own version. Custom objects can also define a version. When you interpolate an object into a string literal—console.log(“This is my object: “ + myObject)—it will call the toString() method.

The assign() method is a mechanism for cloning objects. It is a static method on Object itself:


let object1 = {foo:”bar”};
let object2 = Object.assign({}, object1);
console.log(object2.foo); // outputs “bar”

Note that assign() makes a shallow copy, meaning it doesn’t copy nested properties. Also, the copy has references to the same pointer properties (that is, object1.objectRef === object2.objectRef).

The JSON object

Of all of JavaScript’s built-in objects, JSON may be the most commonly used. It lets you transform between string JSON and live JSON objects. (For more about JavaScript Object Notation, see InfoWorld’s primer, What is JSON?.)

The JSON object is useful all the time. Here’s an example that might be familiar:


let stringJson = '{"nums": [1,2,3,4]}';
console.log(JSON.parse(stringJson).nums[0]); // outputs “1”
let jsonObject = {“letters”: [a,b,c,d]};
console.log(JSON.stringify(jsonObject)); // outputs “{“letters”: [a,b,c,d]}”

These are powerful methods that make using JSON in JavaScript very simple. The ease of dealing with JSON is one of the great things about JavaScript. 

The console object

I’ve said JSON is JavaScript’s most popular built-in object, but console is a close second. Here is where you can log in both server-side and browser JavaScript. In the browser, calls will output to the developer console, which is accessible with the F12 key. With a server-side platform like Node, it’ll go to the operating system console:


console.log(“A generic logging statement”);
console.debug(“A very nit picky logging statement”);
console.info(“Info statement”);
console.warn(“A warning…”)
console.error(“An error!”);

If you are being careful, use the appropriate logging level. If you’re in a rush, console.log() is often sufficient. Always use console.error() when dealing with an error condition, and be sure to pass in the cause:


console.error(“Bad stuff happening”, rootError);

The String object

The String object is used all the time. New String objects are created implicitly using a variable assignment. For example,


let myString = "This is a string";

This creates a String, with the specified text, called myString.

String objects have one property: length. The length property returns the length of the string and uses the syntax string.length, where string is the name of the string variable. Both of the following code snips will display 16:


console.log("This is a string".length)

Here’s another way to write it:


const myString = "This is a string";
console.log(myString.length);

While there may be just one string property, JavaScript supports a large number of methods that can be used with strings. These methods can be roughly divided into two camps: string management and text format.

The string management methods include substring, indexOf, lastIndexOf, and toLowerCase. These are used to return or change the content of the string in some way. For instance, the substring method returns a specified portion of a string; the indexOf method determines the location of a character or group of characters in a string; and the toLowerCase method converts the string to lowercase. (As you can imagine, there’s also a toUpperCase method.)

String methods can be used directly on strings, or on variables that contain strings. Methods always use open and closed parentheses, even if the method doesn’t use parameters. For instance, to convert text to uppercase, you’d use one of the following:


let tempVar = "this text is now upper case".toUpperCase();

or


let myString = "this text is now upper case";
let tempVar = myString.toUpperCase();

Here’s a quick guide to String properties and methods.

The Math object

JavaScript’s Math object provides advanced arithmetic and trigonometric functions, expanding on JavaScript’s basic arithmetic operators (plus, minus, multiply, divide). When dealing with numbers, the Math object is very handy.

JavaScript’s Math object properties are treated as constants. In fact, the property names are all uppercase, following the usual convention of capitalizing variable constants. These properties return values that are often used, including pi and the square root of 2. The Math methods are used in mathematical and trigonometric calculations. Handy Math object methods object include ceil, floor, pow, exp (exponent), max, min, round, and random.

The Math object is static, so you don’t need to create a new one in order to use it. To access the properties and method of the Math object, you merely specify it along with the method or property you wish to use. For example, to return the value of pi, you’d type:


var pi = Math.PI;

Similarly, to use a math method you provide the name of the method along with the parameters you wish to use. To round the value of pi, for example, you’d use:


var pi = Math.PI;
var pieAreRound = Math.round(pi);       // displays 3

Note that you must specify the Math object by name for each method or property you wish to use. JavaScript does not recognize the keywords PI and round all by themselves. One exception is that you may use the with statement to associate the names of methods and properties with the Math object. This technique is a handy space saver when you must use several Math properties and methods. We could write the previous example as follows:


with (Math) {
        var pi = PI;
        var pieAreRound = round(pi);
        alert (pieAreRound)
}

Here’s a quick guide to Math properties and methods.

The Date object

Dates are a notoriously fussy bit of territory in the programming landscape. As of this writing, JavaScript is on the verge of adding a new Temporal API to help make them simpler. In the meantime, we use the Date object.

Dates are built around epoch timestamps. If you’re a veteran programmer, you’re probably familiar with this curious solution to time, which arbitrarily starts a millisecond clock at midnight on January 1, 1970. If you’re newer to development, you’ll soon become familiar with the idea. Basically, computer times begin on that date, and every timestamp before or after is denoted by adding or subtracting milliseconds. (When you use seconds to count, it’s known as Unix epoch time.)

We can also add time elements like days and hours. As an example, if you create a new date with let myDate = new Date(), you’ll get an object set to the current time:


let myDate = new Date();
myDate.getTime() // outputs: 1695329035652
myDate.getDay() // outputs: 4 (0 = sunday, 1 = monday, etc)

You can see that getTime() delivers the time in milliseconds since the epoch date of January 1, 1970. The other methods yield additional fields such as year. Commonly used methods are get and set, which obtain or set the corresponding value in the Date object:

  • get/setHours() returns the hour
  • get/setMinutes() returns the minutes
  • get/setSeconds() returns the seconds
  • get/setYear() returns the year (“96” is 1996)
  • get/setMonth() returns the month (“0” is January)
  • get/setDate() returns the day of the month
  • get/setDay() returns the day of the week (“0” is Sunday)

Constructing a new Date object can take several forms. To return an object containing the current date and time, you use the Date object without parameters, which you’ve seen.  Alternatively, you can specify a given date and time as part of the date constructor. Either of these methods is allowed—both set the new date object to January 1, 2024, at midnight local time.


let myDate = new Date ("January 1 2024 00:00:00")

let myDate = new Date(2024, 0, 1, 0, 0, 0);

The second example uses this format of

  • 2024: Year
  • 0: Month (January is represented by 0, February by 1, and so on)
  • 1: Day of the month
  • 0: Hour (midnight)
  • 0: Minute
  • 0: Second

To use a Date method, append the method to the date object you previously created. For example, to return the current year, use:


let now = new Date();
let yearNow = now.getFullYear();

Window and global

In the browser, you are always running inside the window object. In Node and Node-like environments like Bun and Deno, you are always running inside global. These act as the context of last resort. Usually, you shouldn’t put things into them—it’s bad design. But it’s important to know they are there, since they act as the container for everything, and hold many of the other built-in objects and functions, like console

Conclusion

At first blush, JavaScript’s army of objects can be dizzying, but many of them are highly specialized. You won’t often use them in a typical JavaScript application. JavaScript’s built-in objects are a different breed. Because they don’t depend on any external library, and because they provide such essential functionality, the built-in objects tend to be heavily used in most scenarios. Mastering them goes a long way in developing your overall JavaScript fluency.