Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes
Lesson 1, Topic 9
In Progress

JavaScript: Built-in Objects

abeerairfan 27 Oct 2021
Lesson Progress
0% Complete

Aside from the console, JavaScript includes a number of other objects. You’ll eventually create your own objects, but for the time being, these built-in objects are ready-to-use features.

For example, if you need to perform more complex mathematical operations than arithmetic, JavaScript includes the Math object.

Objects have methods, which is fantastic! Let’s use the Math object’s built-in .random() method:

console.log(Math.random()); //Prints a random number between 0 and 1

In the above example, we called the .random() method by appending the object name with the dot operator, the method name, and opening and closing parentheses to the object name. This method randomly generates number between 0 (inclusive) to 1 (exclusive).

We could multiply this result by 100 to get a random number between 0 and 100:

console.log(Math.random()*100); // Prints a random decimal number between 0 and 100

The above example will most likely be evaluated to a decimal. To ensure that an answer is a whole number, we can use another useful Math method called Math.floor().

Math.floor() is a function that takes a decimal number and rounds it down to the nearest whole number. To round down a random number, use Math.floor() as shown below:

console.log(Math.floor(Math.random() * 100)); // Prints a random whole number between 0 and 1

In this case:

  • Math.random generates a random number between 0 and 100.
  • We then multiply that number by 100, so now we have a number between 0 and 100.
  • Then, Math.floor() rounds the number down to the nearest whole number.
  • console.log() prints the result on terminal.
%d bloggers like this: