× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Using JavaScript Prompts

Victor Igbokwe
Nov 21, 2015
<p><strong>JavaScript `prompts`</strong></p> <p> </p> <p>Prompts are useful in JavaScript when you'd like to quickly collect some howbeit textual information from the user.</p> <p>Here's an example of using a prompt.</p> <pre><code class="language-javascript">var name = prompt("What is your name?"); alert("Your name is " + name);</code></pre> <p>When we run the code above, it shows an input box asking the user for their name. The value entered by the user is stored in the variable `<em><strong>name</strong></em>`.</p> <p>This value is always a string. <em>Even if we asked for the user's age, we'll still be given a `<strong>string`</strong>.</em></p> <pre><code class="language-javascript">var age = prompt("What is your age?"); var agePlus1 = age + 1; alert("Your age plus 1 is: " + agePlus1);</code></pre> <p>`<em><strong>age</strong></em>` above, even though we intended for it to be a <em><strong>number</strong></em>, is a <strong><em>string</em></strong><em> </em>because that's what prompt always gives us regardless. So assume we entered <strong>25</strong> as age, <strong>age + 1</strong> will give us <strong>251 </strong>instead of our expected <strong>26</strong>.</p> <p>Some developers use this prompt as <em><strong>window.prompt </strong></em>since <em><strong>window</strong></em> is part of the global object, it's absolutely legal to do this, but easier to use the shorter version right?</p> <p>So, whenever you feel like collecting quick information from the user, just <strong>prompt()</strong> them.</p>
comments powered by Disqus