Skip to Content
👆 We offer 1-on-1 classes as well check now
Web BasicsJavaScript BasicsIntroduction to JavaScript

Introduction to JavaScript

JavaScript is a programming language that brings websites to life. It allows you to add interactivity, animations, and dynamic content to your web pages, making them much more engaging than static HTML and CSS alone.

What is JavaScript?

JavaScript (often shortened to JS) is a scripting language that runs in your web browser. It’s interpreted, meaning the browser reads and executes the code line by line. JavaScript lets you manipulate the content, structure, and style of a web page, and it can also interact with other websites and servers. Think of it as the “behavior” of a webpage.

Basic Example

Let’s start with a simple example that displays an alert box when a button is clicked.

<!DOCTYPE html> <html> <head> <title>JavaScript Example</title> </head> <body> <button onclick="showAlert()">Click Me!</button> <script> function showAlert() { alert("Hello, JavaScript!"); } </script> </body> </html>

Explanation:

  • <!DOCTYPE html>: Declares the document as HTML5.
  • <button onclick="showAlert()">: Creates a button. onclick is an event that triggers the showAlert() function when clicked.
  • <script>: This tag contains our JavaScript code.
  • function showAlert() { ... }: Defines a function named showAlert.
  • alert("Hello, JavaScript!");: This line displays a popup box with the message “Hello, JavaScript!”.

Practical Usage

JavaScript is used to create many interactive features on websites. Here’s a more practical example of changing text on a webpage when a button is clicked:

<!DOCTYPE html> <html> <head> <title>Text Changer</title> </head> <body> <p id="myText">This text will change.</p> <button onclick="changeText()">Change Text</button> <script> function changeText() { document.getElementById("myText").innerHTML = "Text changed by JavaScript!"; } </script> </body> </html>

Explanation:

  • <p id="myText">: Creates a paragraph with the ID “myText”. The ID allows us to target this specific element with JavaScript.
  • document.getElementById("myText"): This JavaScript code finds the HTML element with the ID “myText”.
  • .innerHTML = "Text changed by JavaScript!";: This line changes the content of the paragraph to the new text.

Key Takeaways

  • JavaScript adds interactivity: It makes web pages dynamic and responsive.
  • JavaScript runs in the browser: It doesn’t require separate software to run.
  • You can manipulate HTML and CSS with JavaScript: Change content, style, and structure.
  • JavaScript uses events: Like button clicks, which trigger specific actions.
Last updated on