JavaScript Syntax JAVASCRIPT

JavaScript Syntax  

JavaScript Syntax

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

var x, y, z;       // How to declare variables
x = 5; y = 6;      // How to assign values
z = x + y;         // How to compute values

The <script> Tag

In HTML, JavaScript code must be inserted between <script> and </script> tags.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.

Example

<script>
document.getElementById("demo").innerHTML = "My First JavaScript example";
</script>

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "My Paragraph changed.";
}
</script>
</head>
<body>

<h2>JavaScript in Head</h2>

<p id="demo">My Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

External JavaScript

Scripts can also be placed in external files also

External scripts are practical when the same code is used on many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

Example

<script src="myscript.js"></script>

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External JavaScript Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

To add several script files to one page  - use several script tags:

Example

<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

Download free E-book of JAVASCRIPT


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries