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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read 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🧡

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more