Search code examples
javascriptpromptconsole.log

Why does printing this variable show a prompt, instead of an error message?


Please why does console.log(theMessage) show a popup prompt, instead of: "You typed" + textTypedIntoPrompt.

Or even some error message related to it?

New to programming and just trying to understand why this program works the way that does.

Thanks.

var textTypedIntoPrompt = prompt ("Type some text");

var theMessage = "You typed" + textTypedIntoPrompt;

console.log(theMessage);

Solution

  • it's not the console.log which open the popup prompt, it's the prompt function

    the log is then done in the console as shown in the snippets below

    var textTypedIntoPrompt = prompt("Type some text");
    var theMessage = "You typed : " + textTypedIntoPrompt;
    console.log(theMessage);

    here's a detailled explanation of what happens

    var textTypedIntoPrompt =                              
    // create a variable named textTypedIntoPrompt
                              prompt("Type some text");    
    // open the popup prompt
    // the popup prompt freeze the execution until the prompt was confirmed or dismissed
    // once the prompt is confirmed/dismissed the function returns
    // either what the user wrote (if confirmed) or null (if dismissed)
    
    // when you're here textTypedIntoPrompt contains the input
    // and your browser already forgot it came from a prompt
    
    var theMessage =                                       
    // then you create a variable named theMessage
                     "You typed : " + textTypedIntoPrompt; 
    // and you assign to it the string 'you typed : ' followed by the value of textTypedIntoPrompt
    // (which is the return value of prompt) 
    
    console.log(theMessage);
    // finally you print this string into the console 
    // use ctrl+shift+k to open the console in most browsers
    

    and finally a snippet proving console.log doesn't open a prompt

    console.log("didn't open a prompt :)")

    while this one proves prompt does open a prompt (as it's name is telling us)

    prompt("I opened a prompt", "you can also set a default value")
    // the return value is not saved into a variable so it is lost