- Create an HTML file
Create a new file with a .html
extension. For example, index.html
.
- Include JavaScript in the HTML file
- method 1 : using script tag
- method 2 : direct Html injection
<!doctype html>
<html>
<head>
<title>My First JavaScript</title>
<script src="location to file path">
//Method 2
</script>
</head>
<body>
<h1>Hello World!</h1>
<button onclick="displayAlert()">Click me</button>
<script>
//Method 2
function displayAlert() {
alert("Hello, JavaScript!");
}
</script>
</body>
</html>
- Variables and Data Types
JavaScript has different data types like string
, number
, boolean
, null
, undefined
, and object
.
let name = "John"; // string
let age = 20; // number
let isAdult = true; // boolean
let height; // undefined
let weight = null; // null
let person = { firstName: "John", lastName: "Doe" }; // object
- Arrays
An array is a special variable, which can hold more than one value at a time.
let fruits = ["Apple", "Banana", "Cherry"];
- Functions
Functions are blocks of code designed to perform a particular task.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("John")); // Hello, John
- Control Structures
Control structures like if
, else
, for
, while
, etc. are used to control the flow of execution.
let number = 10;
if (number > 5) {
console.log("Number is greater than 5");
} else {
console.log("Number is not greater than 5");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
- Objects
Objects are collections of key-value pairs.
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function () {
return "Hello, " + this.firstName;
},
};
console.log(person.greet()); // Hello, John