JavaScript Syntax JAVASCRIPT
- JavaScript Introduction
- JavaScript Syntax
- JavaScript innerHTML
- JavaScript document.write()
- Javascript - window.alert()
- JavaScript - console.log()
- JavaScript Comments
- JavaScript Variables
- JavaScript Operators
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Conditions
- JavaScript Switch
- JavaScript Loop For
- JavaScript While Loop
- JavaScript Break and Continue
- JavaScript Type Conversion
- JavaScript Errors
- JavaScript Scope
- JavaScript this Keyword
- JavaScript Classes
- JavaScript Debugging
- JavaScript - Changing CSS
- JavaScript JSON
JavaScript Syntax
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
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:
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="myScript2.js"></script>