What is JavaScript?

JavaScript is a scripting landguage that can be used on a webpage to add dynamic aspects to it. For example, content can be changed using JavaScript, HTML attributes, elements can be accessed and values can be changed, and styles can be modified. It can also be used to call APIs to receive or send information to a backend.

The script tag

The script tag defines a section within the page where the JavaScript can be placed. The script tag can be placed both in the head and the body tags of the documents. The JavaScript functions can be defined within the script block or it can be called from an external location.

Defining Functions

The JavaScript functions defines a code block that executes in response to an event. An event occurs when the user does something, for example, the user can click on a button or on a div element or scroll to the bottom of the page, etc and JavaScript functions can be wriiten to respond to these events.


Access elements and attributes

Change values of elements and attributes

Define JavaScript in head element

Define JavaScript in body element

Add external JavaScript to a page

A function that shows current date and time

Modify Styles

Benefits of using an external JavaScript

JavaScript can be defined both on the page or called from an external location. There are some scenarios where it is better to create external file to store all the JavaScript functions and sometimes it might be better to store it on the current HTML page.

  • Having external makes the code cleaner. Therefore the HTML and JavaScript can be separated out. It is also easier if there are multiple developers defining HTML and javaScript.
  • Having external JavaScript helps in reusablity. If the code is on the same file, then the code needs to be copied over every HTML page where it is required. With an external file, all that ir required is that we need to refer to the same file. Updating the JavaScript file will be lot easier to maintain.
  • When the JavaScript is very specific to the page, for example, it deals with modifying certain elements within the page, it might easier to define it on the page.
  • External JavaScript file can also improve the site load speed of the HTML page if the same file is used on multiple pages.