Monday, June 17, 2019

How To Write JavaScript

How To Write JavaScript

If you have ever used CSS before, you will find the whole part about including JavaScript will be a lot simpler to grasp. Here are Tizag's three important steps you should always follow when creating or using someone else's JavaScript code:

  1.     Use the script tag to tell the browser you are using JavaScript.
  2.     Write or download some JavaScript
  3.     Test the script!

There are so many different things that can go wrong with a script, be it human error, browser compatibility issues, or operating system differences. So, when using JavaScript, be sure that you test your script out on a wide variety of systems and most importantly, on different web browsers.
Your First JavaScript Script

To follow the classic examples of many programming tutorials, let's use JavaScript to print out "Hello World" to the browser. I know this isn't very interesting, but it will be a good way to explain all the overhead required to do something in JavaScript.
HTML & JavaScript Code:

<html>
<body>
<script type="text/JavaScript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>


Display:
Hello World!
Our first step was to tell the browser we were using a script with the <script> tag. Next we set the type of script equal to "text/JavaScript". You may notice that doing this is similar to the way you specify CSS, which is "text/css".

Next, we added an optional HTML comment that surrounds our JavaScript code. If a browser does not support JavaScript, it will not display our code in plain text to the user! The comment was ended with a "//-->" because "//" signifies a comment in JavaScript. We add that to prevent a browser from reading the end of the HTML comment in as a piece of JavaScript code.
JavaScript document.write

The final step of our script was to use a function called document.write, which writes a string into our HTML document. document.write can be used to write text, HTML, or a little of both. We passed the famous string of text to the function to spell out "Hello World!" which it printed to the screen.

Do not worry if you don't completely understand how document.write works, as we will be discussing functions in a later lesson.
Syntax

Looking at our JavaScript code above, notice that there is no semicolon at the end of the statement "document.write(Hello World!)". Why? JavaScript does not require that you use semicolons to signify the end of each statement.

If you are an experienced programmer and prefer to use semicolons, feel free to do so. JavaScript will not malfunction from ending semicolons. The only time it is necessary to use a semicolon is when you choose to smash two statements onto one line(i.e. two document.write statements on one line).

No comments:

Post a Comment