The Computer Gal Logo - Laptop with coffee and plants
Using Strings and Variables in a Function
If you would like to receive weekly emails with articles like this one, email Nora

This is a simple JavaScript exercise that will show you the difference between working with a "hardcoded value" and using a variable.

  1. Create an HTML file called JavaScriptString.html
  2. Type this inside the <body> tag.
      <script language="JavaScript">
        alert("Hello");
       </script>
    </body>
  3. Take out the " " around Hello. Open the file in both IE and Mozilla.
  4. Above the alert() line, type var Message = "Hello".
  5. Change alert ("Hello") to alert(Message);. Open again in your browsers.

NOTES:

  1. A word or a group of words with " " is called a String.
  2. alert() is a function. It requires a string as a parameter or argument.
  3. When you removed the " " around Hello, you changed the argument from a string to a variable, but there was no variable defined. So, JavaScript couldn't do what you expected.
  4. var word; is called declaring a variable. You are telling the computer to reserve some memory space that you will fill.
  5. var Message ="Hello"; is defining a variable. You are placing a value into the memory space you declared (set aside) earlier.

Related Articles

  1. Using a Text Editor and a Browser to Create a Web Page
  2. What is JavaScript?
  3. Using a Pre-defined Function in JavaScript
  4. Variables, Math, Concatenation and Overloaded Operators
  5. Using a Prompt Box and Outputting to the Screen
  6. Basics about Forms
  7. Adding JavaScript to a Form

 

Nora McDougall-Collins | Missoula, Montana 59801 | 406.253.4045 | info@thecomputergal.com
© 2009, Nora McDougall