Introduction to JavaScript:- JavaScript is a programming language that makes web pages interactive. Think of it as the magic behind all the cool stuff you see on websites!
Table of Contents
1. What is JavaScript?
JavaScript is a language that helps you add behaviour to web pages. It’s used to make things like sliders, forms, and interactive maps work.
2. How to Add JavaScript to Your Web Page
There are three ways to include JavaScript in your HTML files:
- Inline JavaScript: Write it directly inside an HTML tag.
<button onclick="alert('Hello!')">Click Me!</button>
- Internal JavaScript: Put it inside the
<script>
tag within your HTML file.
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
<script>
function myFunction() {
alert('Hello!');
}
</script>
</head>
<body>
<button onclick="myFunction()">Click Me!</button>
</body>
</html>
Output

- External JavaScript: Link an external JavaScript file to your HTML.
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="myFunction()">Click Me!</button>
</body>
</html>
Create a separate file named script.js
:
function myFunction() {
alert('Hello!');
}
3. Basic Rules and Variables
JavaScript has rules for writing code (syntax). Variables are used to store information.
// This is a comment
var name = "John"; // 'name' is a variable that holds the value "John"
let age = 20; // 'let' also declares a variable
const pi = 3.14; // 'const' declares a constant variable
4. Data Types and Math
JavaScript can work with different types of data, like:
- String: Text. Example:
"Hello"
- Number: Numbers. Example:
25
- Boolean: True or false. Example:
true
,false
- Array: A list of items. Example:
[1, 2, 3]
- Object: A collection of properties. Example:
{name: "John", age: 20}
It can also do the math:
let a = 5;
let b = 10;
let sum = a + b; // sum is 15
5. Functions
Functions are pieces of code that do something. You call them when you need them.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Outputs: Hello, Alice!
6. Making Decisions
JavaScript can make decisions using if
statements.
let age = 20;
if (age > 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
7. Changing Web Pages with JavaScript
You can change the content of a web page with JavaScript.
// Change the text of an element with id="demo"
document.getElementById("demo").innerHTML = "Hello, World!";
8. Responding to User Actions
JavaScript can react to user actions like clicks and key presses.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});