DEV Community

aryan015
aryan015

Posted on

🧡How to take input in javascript using console (codechef)

You might have always struggled with javascript to take input from console. I also encountered such situations in competitive programming. You don't have such function in JS but node.js. We will take use of input stream(stdin). Remember that everything received from console considered as a string even numbers.

process.stdin.setEncoding('utf8'); // it sets the encoding
// try this snippet without setting encoding (homework)
process.stdin.on('data',function(input){
  console.log(input) // your output
})
Enter fullscreen mode Exit fullscreen mode

note:It is a pain🍑 in javascript to take input🤷‍♀️. You might need on-the-go ready snippet in competitive programming.

input

// add this number and return the result
//10 11 12
process.stdin.setEncoding('utf8');
process.stdin.on('data',function(input){
  let strArray = input.split(" "); // ['10','11','12']
// Convert each string to a number and sum them up
let sum = strArray.reduce((acc, num) => acc + Number(num), 0);
console.log(sum) // whatever the sum is
})
Enter fullscreen mode Exit fullscreen mode

output

33
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (5)

Collapse
 
9opsec profile image
9opsec •

I'm getting "process is not defined".

Collapse
 
aryan015 profile image
aryan015 •

process is node specific. Will run in only node environment (not js)

Collapse
 
9opsec profile image
9opsec •

OK thanks.

Thread Thread
 
aryan015 profile image
aryan015 •

install node. try node filename.js. and it will execute.

Thread Thread
 
aryan015 profile image
aryan015 •

it is not available in browser environment🧡

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more