Java Script
Java Script
1. Structure of JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script>
function greet() {
alert("Hello, JavaScript!");
}
</script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>
<script src="script.js"></script>
File script.js:
Variables Used to store data values let x = 10; let is used for variables that can be
using var, let, const const y = reassigned. const is used for constants that
20; cannot be reassigned. var is an older way of
var z = 30; declaring variables.
Data Different types: string, let str = str is a string, num is a number, and bool is a
Types number, boolean, object, "Hello"; boolean.
etc. let num =
25;
let bool =
true;
Control Structures
Conditionals Used for let x = 15; This checks if x is greater than 10.
(if-else) decision-making if (x > 10) { If true, it prints "Big"; otherwise,
console.log("Big"); it prints "Small".
} else {
console.log("Small");
}
For Loop Executes a block for (let i = 0; i < 5; i++) { The for loop runs 5 times,
of code a set console.log(i); printing the values of i from 0 to
number of times } 4.
While Loop Runs as long as a let i = 0; The while loop runs as long as i is
condition is true while (i < 5) { less than 5, incrementing i with
console.log(i); each iteration.
i++;
}
ES6 Arrow Concise const add = (a, b) => a + b; Arrow functions provide a more
Functions function syntax console.log(add(2, 3)); compact syntax for writing
functions.
Arrays Collection of let arr = [1, 2, 3]; Arrays hold multiple elements. The
elements arr.push(4); push method adds an item to the
console.log(arr); end of the array.
Array Functions like let doubled = arr.map(num The map method creates a new array
Methods map, filter, reduce => num * 2); by applying a function to each
console.log(doubled); element of the array.
Asynchronous JavaScript