
How to Find the Cube of a Number Using JavaScript
May 28, 2025 1 Min Read 347 Views
(Last Updated)
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
- Problem Statement
- Sample
- Step-by-Step Explanation
- JavaScript Solution (Node.js / Coding Platforms)
- How the Code Works
- Summary
- 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:
- Read the input number.
- Calculate the cube using multiplication or the exponentiation operator (**).
- 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
Did you enjoy this article?