JavaScript Introduction
Getting Started with JavaScript
1. What is JavaScript?
JavaScript is a programming language used to create interactive and dynamic web pages. While HTML provides structure and CSS provides styling, JavaScript adds behavior to websites.
Example:
- Click a button and show a message
- Validate form input
- Update content without refreshing the page
2. Where JavaScript is Used
- Web development
- Mobile applications
- Server-side development (Node.js)
- Games
- Desktop applications
3. Adding JavaScript to HTML
Inline JavaScript
<button onclick="alert('Hello!')">Click Me</button>
Internal JavaScript
<script>
console.log("Hello JavaScript");
</script>
External JavaScript
<script src="script.js"></script>
4. Your First JavaScript Program
console.log("Welcome to JavaScript Learning");
5. Real Life Example: Greeting Application
This example greets the user when they enter their name.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Greeting App</title>
</head>
<body>
<h2>Greeting Application</h2>
<input type="text" id="name" placeholder="Enter your name">
<button onclick="greetUser()">Greet</button>
<p id="message"></p>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
function greetUser() {
let name = document.getElementById("name").value;
document.getElementById("message").innerText = "Hello " + name + "! Welcome to JavaScript.";
}
Run Code
6. How This Example Works
- User enters their name in the input box.
- When the button is clicked, the function
greetUser()runs. - JavaScript reads the value from the input field.
- The message is displayed on the page.
7. Practice Exercise
Create a small application that:
- Asks the user for their favorite color
- Displays "Your favorite color is ___"
8. What Students Learned
- What JavaScript is
- How to add JavaScript to HTML
- Basic interaction with HTML elements
- Writing a simple function
Next Chapter
Chapter 2: Variables, Data Types, and Operators