Learn/JavaScript/3. Reading input and arithmetic
Lesson 3 of 15
Sign in

JavaScript, lesson 3

Reading input and arithmetic

Most programs need data from outside. In this course the data arrives on standard input (stdin): the tests type some text into your program, and your program reads it.

Reading stdin in Node.js

Node.js has a built-in module called fs (file system). Its readFileSync function reads a whole file at once. Standard input is file descriptor 0, so passing 0 reads everything the user typed until the input ends:

require("fs") loads the module. The "utf8" argument asks for a string; without it you would get raw bytes (a Buffer). This reads lines in one go, which is perfect for programs whose input is fully known when they start. Many people shorten it to one line:

2 exercises to try what you just read.

Exercise 1

Add two numbers

Press Ctrl Enter or Check to test your code.

Exercise 2

Movie marathon

Press Ctrl Enter or Check to test your code.

all

Splitting input into pieces

The input is one long string, for example "12\n30\n". Two string methods break it apart:

  • trim() removes spaces and line breaks from both ends.
  • split(separator) cuts a string into an array of parts.

When numbers are on one line separated by spaces, split on any run of whitespace with the regular expression /\s+/:

Text to numbers

"12" is a string, not a number. Adding two strings joins them: "12" + "30" is "1230". Convert first with Number():

Number() insists the whole string is a number. parseInt("12kg", 10) and parseFloat("3.5kg") are more forgiving and read the leading number, stopping at the first character that does not fit. Always pass 10 to parseInt so it reads decimal digits.

Arithmetic operators

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
%remainder7 % 21
**power7 ** 249

Division always produces a decimal when needed. For whole-number division use Math.floor(7 / 2) (which gives 3) or Math.trunc, which rounds toward zero and so differs for negative numbers. The remainder operator keeps the sign of the left side: -7 % 3 is -1.

Shortcut operators update a variable in place: total += 5, count -= 1, price *= 2, and i++ adds one.

Rounding for display

toFixed(digits) formats a number with a fixed number of decimals and returns a string:

Math.round, Math.floor and Math.ceil round to whole numbers and return numbers.

Further reading

  • Node.js docs: fs.readFileSync
  • MDN: Number
  • MDN: Expressions and operators
  • MDN: String.prototype.split

The input has two integers, one per line. Print their sum.

Sample input:

Sample output:

You plan a movie marathon and know the total running time in minutes. Print how long that is in hours and minutes, in the form H h M min.

The input is one line with a whole number of minutes (0 or more).

Sample input:

Sample output:

const fs = require("fs");
const input = fs.readFileSync(0, "utf8");
const input = require("fs").readFileSync(0, "utf8");
const lines = input.trim().split("\n");   // ["12", "30"]
const first = lines[0];                    // "12"  (arrays count from 0)
const parts = "4   7 9".trim().split(/\s+/);  // ["4", "7", "9"]
const a = Number("12");     // 12
const b = Number(" 3.5 ");  // 3.5 (surrounding spaces are fine)
const bad = Number("12kg"); // NaN, "not a number"
const avg = 10 / 3;
console.log(avg.toFixed(2));   // 3.33
console.log((2.5).toFixed(0)); // 3
2
3
5
135
2 h 15 min