Why is the prompt run anyway in javascript?

Asked

Viewed 68 times

2

I have the following very simple code

var name = window.prompt("Digite seu nome:");

The window.prompt method is inside a variable, why it runs if it is inside a variable, I did not put it outside of a variable so it can run??

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

3

"- The window.prompt method is inside a variable"

That statement is wrong! The right one is: the variable name receives the return of the method prompt.

This means you can receive and/or treat the value (the input) entered by the user later:

var name = window.prompt('Digite seu nome');
alert('O seu nome é '+name);

You can call the method without a variable receiving its value. But there are specific cases for this. Otherwise the user will make an entry in vain!

Take an example without the variable receiving (storing) the return:

if (window.prompt('Digite "SIM" para chamar a função foo') == 'SIM') {
    foo();
}

3

Window.prompt()

Window.prompt() displays a dialog box with an optional message asking the user to input some text.

Syntax

resultado = window.prompt(texto, valor);
  • resultado is a string containing the text typed by the user, or a null value.
  • texto is a string to display to the user. This parameter is optional and can be omitted if there is nothing to display in the prompt window.
  • valor is a string containing the default value displayed in the text input box. It is an optional parameter. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the character string "Undefined" is the default value.

That is, you are running the function window.prompt passing the parameter "Enter your name:" and is storing in the variable only the return of the function (which for this case is what the user type in the box).

To store the function with the sent parameter you must perform as follows:

var nome = function() { return window.prompt("Digite seu nome:"); };

And the execution would be:

nome();

var nome = function() { return window.prompt("Digite seu nome:"); };
console.log(nome());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.