const a = +(readLine()) console.log(a) gives an error
const a = +(readLine()) ^ ReferenceError: readLine is not defined How to fix it ? What is the purpose of + sign before the readLine() function
43 Answers
You are missing following
const readLine = require('readline'); Basically, readLine doesnt come out of the box. You need to import the module before using it. If you add that line on the top of your script, it should get rid of readline error.
+ is basically converting the line which you read to a number. Reason for using it is because, by default when you read line it is a string and + tells the nodejs interpreter to use it as integer. Integer is one of the primitive types of JavaScript. If you don't need it to be a number, then you can remove +.
+ means conversion to a numeric value. ReferenceError means that you haven't defined readLine function. Ensure that you haven't made a typo or you haven't forgotten to import the corresponding module.
Here you are missing readline module to import. Below is the sample, how you can take user input, and work on the input.
Take numbers coma separated and sum.
Sum function:
const sum = (...numbers) => numbers.reduce((s, i) => s+=i,0) console.log(sum(1, 2)) // 3 console.log(sum(0, 5)) // 5 console.log(sum(-1, 6, 1)) // 6+ Plus is to convert string to number. You can also use Number class to convert
String to Number:
const num = Number("6") console.log(num == (+"6")) // true Sample:
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const sum = (...numbers) => numbers.reduce((s, i) => s+=i,0) const readNumbers = () => { return new Promise((r) => { rl.question("Please enter you numbers(coma separated): ", (answer) => { const numbers = answer.split(",").map((x) => +x) // + to convert string to number r(sum(...numbers)); // sum all number rl.close(); }); }); }; readNumbers().then((sum) => { console.log(`Sum: ${sum}`); }); 2