Where to Put Your JavaScript in HTML Files
JavaScript code needs to be placed within <script>
and </script>
tags in your HTML file.
These tags can be placed either within the <head>
or the <body>
section.
<head>
: Placing the script in the<head>
section means it will load before the rest of the page content.<body>
: Placing the script at the bottom of the<body>
section generally improves page load speed as the browser can render the visible content first and then execute the JavaScript.
Using External JavaScript Files
JavaScript code doesn't necessarily have to be written directly within your HTML file. You can use an external JavaScript file and link to it using the src
attribute within the <script>
tag.
For example:
HTML
<script src="myScript.js"></script>
Why Use External JavaScript Files?
- Improved Readability: Separating HTML and JavaScript improves the readability and maintainability of your code
- Enhanced Performance: External JavaScript files can improve page load speed as the browser can start rendering the HTML while the JavaScript file is being loaded in the background
JavaScript Functions and Events
- Functions: A JavaScript function is a block of code designed to perform a specific task. It is only executed when it is called.
- Events: Events are actions that occur in a web browser, such as a user clicking a button, hovering over an element, or typing in a field. JavaScript can be used to "listen" for these events and trigger specific actions when they occur.
Semicolons (;)
In JavaScript, it's good practice to end each statement with a semicolon (;). While JavaScript might sometimes interpret code without semicolons, it's best to use them consistently for better readability and to avoid potential errors.
White Space
JavaScript is not sensitive to whitespace. This means you can use spaces and tabs freely to improve code readability without affecting its functionality.
- e.g.:
- 1+1=2 is the same as
- 1 + 1 = 2
Important Keywords
var
/let
: Used to declare variables.let
is generally preferred overvar
due to its block scoping.const
: Used to declare constants, variables whose values cannot be changed after they are assigned.if
: Used to execute a block of code if a specified condition is true.switch
: Used to execute a block of code depending on different cases.for
: Used to loop through a block of code a specified number of times.function
: Used to define a function.return
: Used to exit a function and optionally return a value.