JavaScript 101 - The Basics

How to read input data from the console?

In JavaScript, to input data from the user, you use the prompt() function or the ES6 readLine(). In some online competitive challenges, its possible their JavaScript compiler would require you to use the readLine() function for user input. Let's go a little deeper into each of these functions' purposes.

In JavaScript, the prompt() function is used to ask the user for input:

let name = prompt("What is your name?");
console.log("Hello " + name + "!");

Now, if you type in the following line of code:

console.log(typeof name);

You will notice that prompt() returns the user input as a string. That means if we want to return an integer or a float data type from the prompt(), we'd have to convert the string.

With JavaScript's ES6, we have the following three functions that can be used to read input from a user:

  • readLine(prompt): Reads a string value from the user.

  • readInt(prompt): Reads an integer value from the user.

  • readFloat(prompt): Reads a float value from the user.

Next, we will demonstrate the use of these functions together with the output.

How to output the answer?

Given that we now know how to accept user input, we can display the desired output to the user with a console.log(). As demonstrated below:

let name = readLine("What is your name?");
let age = readInt("What is your age?");
console.log("Welcome " + name + "! You are " + age + " years old.");

A final note, the function can be used with no parameters being passed, as demonstrated below:

let str = readLine();
console.log(str);