SoFunction
Updated on 2025-04-13

JavaScript Elementary Tutorial (Lesson 2) Page 2/7


Now that we have defined the variable, let's use it to do something.
    <script language="JavaScript">
    <!-- hide me
Here we introduce how to write variables and web pages in JavaScript.
    // here's how to use JavaScript to write out HTML
    ("<b>The monkey dances ");
    (secs_per_year);
    (" seconds per year.</b><p>");
Here are the points of interest about these three lines:
() Write insert words for web pages.
There are a lot of details in (), but at this point you just need to remember that you are between the <script> and </script> tags and must be displayed with ("blah!") characters in HTML quotes on the web page; characters outside the quotes are considered variables.
Note that in the first and third lines, the quotes are what we want to show, while secs_per_year has no quotes. So JavaScript thinks it is a variable and exchanges it for variable values. Fortunately, in the header file we define secs_per_year as a large number, so it can be displayed, otherwise JavaScript will report an error.
Any word in quotes is called a string and JavaScript does not compile it.
In this example, double quotes (") can also be used, single quotes ('), and the two are interchangeable. If the second line is
    ("secs_per_year"),JavaScript
secs_per_year will be displayed directly, instead of 31,536,000.
The difference between this example and characters is very important, so before we continue, make sure you have read this paragraph.
You can use () to write HTML language.
Pay attention to the <b>  and</b>  tags in the first and third lines.
This is the summary of this example. A common question for us is: "What usually appears in the header file and what appears in the body file?"
Generally, this doesn't matter much. The good habit is to put most JavaScript on the head of the page. This is because it is read first than the subject, so variables (such as secs_per_min) that appear in the subject are defined in the header. When secs_per_min is defined after JavaScript tries to execute (secs_per_min) command, JavaScript will report an error.
OK, now we are going to do an exercise about variables, but first pay attention to strings.
Previous page1234567Next pageRead the full text