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
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
Share Improve this question asked May 7, 2020 at 7:22 Mounika BathinaMounika Bathina 1434 silver badges14 bronze badges 4- 1 The + before is for converting it to a number, but that's not the reason of your error. – Radu Diță Commented May 7, 2020 at 7:25
-
1
+(...)
means type convert to int. But your error says that there is no function namedreadLine
– Justinas Commented May 7, 2020 at 7:25 -
2
const readLine = require("readline")
– xdeepakv Commented May 7, 2020 at 7:32 -
what is
readLine
here ?? – xdeepakv Commented May 7, 2020 at 7:34
3 Answers
Reset to default 5You are missing following
const readLine = require('readline');
Basically, readLine
doesnt e 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 a separated
and sum.
More info: https://nodejs/api/readline.html
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(a 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}`);
});