Progress pill
Intermediate JavaScript

Utility Objects

  • Other console Methods
  • The Math Object
JavaScript gives us some useful built-in objects that help us do things like debugging and math operations.

Other console Methods

You've already seen console.log, which prints values to the screen.
There are some other useful methods available on the console object that can help you debug your programs.

console.warn

Prints a message in yellow (or with a warning icon in some environments):
console.warn("This is just a warning.")

console.error

Prints a message in red, like an error:
console.error("Something went wrong!")

console.table

Displays an array or object as a table:
const users = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 } ] console.table(users)
This prints a table like:
┌─────────┬────────┬─────┐ │ (index) │ name │ age │ ├─────────┼────────┼─────┤ │ 0 │ 'Alice'│ 25 │ │ 1 │ 'Bob' │ 30 │ └─────────┴────────┴─────┘
This can be useful to visualize structured data.

console.time and console.timeEnd

You can measure how long something takes:
console.time("timer") for (let i = 0; i < 1000000; i++) {} console.timeEnd("timer")
This prints something like:
timer: 2.379ms
Useful for some simple performance testing.

The Math Object

JavaScript gives you a Math object with useful methods for doing calculations.

Math.random()

Returns a random number between 0 (inclusive) and 1 (exclusive):
const r = Math.random() console.log(r)
Example output:
0.4387429859

Math.floor() and Math.ceil()

  • Math.floor(n) rounds down to the nearest integer
  • Math.ceil(n) rounds up to the nearest integer
console.log(Math.floor(4.9)) // 4 console.log(Math.ceil(4.1)) // 5

Math.round()

Rounds to the nearest integer:
console.log(Math.round(4.4)) // 4 console.log(Math.round(4.6)) // 5

Math.max() and Math.min()

Returns the largest or smallest value from a list of numbers:
console.log(Math.max(5, 9, 3)) // 9 console.log(Math.min(5, 9, 3)) // 3

Math.pow() and Math.sqrt()

  • Math.pow(a, b) gives you a to the power of b
  • Math.sqrt(n) gives you the square root of n
console.log(Math.pow(2, 3)) // 8 console.log(Math.sqrt(16)) // 4