1 // This is a comment.
2 // This is also a comment.
3 // This is Master Hun's New & Improved "Hello, World!" program.
4 var userName = "John Doe";
5 userName = prompt("What is your name?");
6 alert("Hello, " + userName + "!");
This is a short JavaScript program consisting of three lines of code. Line 4 creates a variable labeled userName. Line 5 "prompts" the user for their name. Line 6 pops up an alert box that says, "Hello, [insert user's name]!"
Lines 1 to 3 are examples of comments done badly. Comments are supposed to clearly explain what the code does.
Line 4 uses the var keyword to create a variable named userName. And the variable name is an example of Lower Camel Case.
Line 5 uses the prompt() function to pop up a dialog box to ask the user his/her name. Then assigns the string value into the userName variable.
Line 6 uses the alert() function to pop up an alert box which uses the string in the userName variable.
Note: #MasterHun tested the code with Scratchpad, Firefox's built-in JavaScript editor.
Kommentarer