JavaScript Introduction
What is JavaScript?
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. JavaScript enables interactive web pages and is an essential part of web applications.
What Can JavaScript Do?
JavaScript can:
- Change HTML content
- Change HTML attributes
- Change CSS styles
- Hide and show HTML elements
- Validate form input
- Create animations
- Handle user events (clicks, keyboard input, etc.)
- Make web pages interactive
How to Add JavaScript
1. Inline JavaScript
Add JavaScript directly in HTML using the <script> tag:
Example
<button onclick="alert('Hello, World!')">Click Me</button>
2. Internal JavaScript
Add JavaScript in a <script> element in the HTML document:
Example
<script>
function greet() {
alert('Hello, World!');
}
</script>
<button onclick="greet()">Click Me</button>
3. External JavaScript
Link to an external JavaScript file using the src attribute:
Example
<script src="script.js"></script>
Your First JavaScript Program
Example
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<h1>JavaScript Example</h1>
<button onclick="changeText()">Click Me</button>
<p id="demo">This text will change.</p>
<script>
function changeText() {
document.getElementById('demo').innerHTML = 'Hello, JavaScript!';
}
</script>
</body>
</html>
JavaScript Output
JavaScript can display data in different ways:
Using alert()
Example
alert('Hello, World!');
Writing to HTML
Example
document.write('Hello, World!');
Writing to an HTML Element
Example
document.getElementById('demo').innerHTML = 'Hello, World!';
Writing to the Console
Example
console.log('Hello, World!');
Next Steps
Now that you understand the basics of JavaScript, you're ready to learn about JavaScript Syntax.