How to use “readline()” function in JavaScript?

var names = ["David", "Cynthia", "Raymond", "Clayton", "Jennifer"]; putstr("Enter a name to search for: ");
var name = readline();
var position = names.indexOf(name);
if (position >= 0) {
print("Found " + name + " at position " + position);
} else {
       print(name + " not found in array.");
    }

1 Like

No, I run into Data Structures and Algorithm with JS books. It was not giving any information about Node’s. I just need help the second line in my sharing code. Thanks

only the second line. What is the functionality readline in the second line?

var names = ["David", "Cynthia", "Raymond", "Clayton", "Jennifer"]; putstr("Enter a name to search for: ");
var name = readline();
var position = names.indexOf(name);
if (position >= 0) {
print("Found " + name + " at position " + position);
} else {
       print(name + " not found in array.");
    }

1 Like

Hi @snntaylan,
This looks like code for SpiderMonkey, the Command Line JavaScript runtime environment from Mozilla.
readline() is their method to read stdin and print() is the stdout method.
If you come from web, you could almost compare readline to prompt(), the script simply pauses and waits until something comes from user input.

When you run this script in your console, the Spidermonkey runtime will start and a cursor will blink, waiting for your input (stdin). If you type or paste something and press enter (or get input from somewhere else) the script will continue with the line var position = names.indexOf(name);. Save the script to find_name.js.
If you have a Mac, SpiderMonkey comes preinstalled. Just open Terminal and write:

$ js find_name.js
Enter a name to search for: 

And when you type a name and press return:

Enter a name to search for: Johan
Johan not found in array. 
$ 
1 Like

some coding platforms like in Hackerrank it’s expected to be readLine() and not readline() which is the actual js syntax. I don’t know could be a glitch.