Search code examples
javascriptnode.jsconfirm

confirm() function not defined in Javascript program


I am new to Javascript so forgive me if my query is too trivial. I am writing a simple program using the function "confirm()". Here it is:

if (confirm("Are you xyz?"))
{
console.log("Hello xyz, how are you?");
} else {
console.log("Then what is your name?");
}

But on running this I get the error: confirm is not defined. Do I need to install or call a package to make this confirm() function defined?


Solution

  • There's a very important difference between browser javascript and node.js. Browsers have a confirm function, while node does not. If you want to do something similar, you can use the readline module.

    const readline = require("readline");
    const interface = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    interface.question("Are you xyz? (y/n) ", function(ans) {
        if (ans == "y" || ans == "yes") {
            console.log("Hello there xyz.");
        } else {
            console.log("So what is your name?");
        }
        // pause the interface so the program can exit
        interface.pause();
    });