header_logo
Post thumbnail
JAVASCRIPT

How to Find the Cube of a Number Using JavaScript

By Arun Kumar

In this post, we’ll explore a simple mathematical problem: finding the cube of a number. This is a beginner-friendly task, great for understanding basic input/output and arithmetic operations in JavaScript.

Table of contents


  1. Problem Statement
  2. Sample
  3. Step-by-Step Explanation
  4. JavaScript Solution (Node.js / Coding Platforms)
  5. How the Code Works
  6. Summary
  7. Conclusion

Problem Statement

You are given a single positive integer N.

Input:

A single line containing a positive integer N.

Output:

A single line containing the cube of N (i.e., N × N × N or N³).

Sample

Input:

2

Output:

8

Why?
Because: 2 × 2 × 2 = 8

Step-by-Step Explanation

Here’s how you should approach this:

  1. Read the input number.
  2. Calculate the cube using multiplication or the exponentiation operator (**).
  3. Print the result.

JavaScript Solution (Node.js / Coding Platforms)

Here’s a basic JavaScript script that does exactly that:

const readline = require(‘readline’);

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.on(‘line’, function(line) {
    const N = parseInt(line);      // Convert input to an integer
    const cube = N ** 3;           // Calculate cube
    console.log(cube);             // Output result
    rl.close();                    // Close input stream
});

How the Code Works

  • We use Node.js’s readline module to accept input.
  • The user enters a number (say 2).
  • parseInt(line) ensures the input is treated as a number, not a string.
  • N ** 3 calculates the cube of N.
  • Finally, we print the result using console.log().

Note: The exponentiation operator in JavaScript. You could also use Math.pow(N, 3) if preferred.

Summary

This problem is great for practicing:

  • Reading input
  • Doing basic arithmetic
  • Outputting results

If you want to learn and become proficient in JavaScript, the JavaScript Course in 100 days by GUVI is the perfect place to start. It offers a structured, hands-on learning path—from basics like string manipulation to building full-fledged web apps—all taught by industry experts.

Conclusion

Finding the cube of a number is a simple yet effective exercise for beginners to get comfortable with basic input/output handling and arithmetic operations in JavaScript. In this problem, we learned how to:

  • Read user input using Node.js (readline module)
  • Convert input strings to numbers using parseInt
  • Use exponentiation (**) to calculate the cube
  • Display the result with console.log

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button