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.
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 hourget/setMinutes()returns the minutesget/setSeconds()returns the secondsget/setYear()returns the year (β96β is 1996)get/setMonth()returns the month (β0β is January)get/setDate()returns the day of the monthget/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.


