JavaScript is a versatile, high-level programming language primarily used to create interactive and dynamic content on websites. Unlike HTML and CSS, which are used to structure and style web pages, JavaScript adds behavior to the web pages, allowing them to respond to user actions, validate form data, create animations, and much more. JavaScript is an essential part of web development, often working in conjunction with HTML and CSS.
Key Features of JavaScript
Interactivity: Allows you to create interactive elements on your website (e.g., forms that check input before submission, buttons that perform actions).
Dynamic Content: Can manipulate the DOM (Document Object Model) to change the content and structure of the web page dynamically.
Client-Side: Runs on the user's browser, providing a fast and responsive user experience.
Versatile: Can be used for a wide range of applications, from simple scripts to complex web applications.
Explanation of the Example
Inline JavaScript:
< script> tag: The JavaScript code is included within the < script> tags inside the HTML file.
Function definition: function showMessage() { ... } defines a function that displays an alert box.
Event handling: The onclick attribute in the < button> element calls the showMessage function when the button is clicked.
External JavaScript:
External file: The JavaScript code is saved in a separate file (script.js).
Event listener: document.addEventListener('DOMContentLoaded', function() { ... }); ensures that the JavaScript code runs only after the HTML document has been fully loaded.
Button event listener: document.getElementById('myButton').addEventListener('click', function() { ... }); adds a click event listener to the button, which triggers the alert when the button is clicked.