1. document.
write
What it does: Writes content directly to the webpage when the script runs.
Example:
javascript
document.write("Hello, World!");
Use case: It’s simple and great for learning, but not recommended for modern web
development because it overwrites the entire webpage if used after the page loads.
2. var, let, and const
What they do: These are used to declare variables.
o var: The old way to declare variables (global or function-scoped).
o let: The modern way to declare variables (block-scoped).
o const: Used for variables whose values don’t change (constant).
Example:
javascript
var age = 18; // Can be reassigned and is function-scoped
let name = "Adil"; // Can be reassigned and is block-scoped
const country = "Pakistan"; // Cannot be reassigned
3. prompt
What it does: Displays a dialog box to get input from the user.
Example:
javascript
var name = prompt("What is your name?");
document.write("Hello, " + name + "!");
Use case: Useful for basic interaction with the user during learning.
4. alert
What it does: Displays a pop-up message box.
Example:
javascript
alert("Welcome to the website!");
Use case: Good for showing simple notifications, but it interrupts the user
experience.
5. console.log
What it does: Logs messages to the browser’s console (for debugging).
Example:
javascript
console.log("This is a debug message.");
Use case: Preferred for debugging instead of using document.write.
6. typeof
What it does: Returns the data type of a variable.
Example:
javascript
var age = 18;
console.log(typeof age); // Output: "number"
Use case: To check what type of data a variable holds.
7. Functions
What they do: Reusable blocks of code that perform specific tasks.
Example:
javascript
function greet(name) {
return "Hello, " + name + "!";
}
document.write(greet("Adil"));
Use case: To avoid repeating code and organize logic.
8. Loops
What they do: Repeat a block of code multiple times.
Types:
o for: Loop with a counter.
o while: Loop until a condition is false.
o do-while: Executes at least once before checking the condition.
Example (for loop):
javascript
for (var i = 1; i <= 5; i++) {
document.write("Number: " + i + "<br>");
}
9. Conditions (if, else, else if)
What they do: Execute different blocks of code based on conditions.
Example:
javascript
var age = 20;
if (age < 18) {
document.write("You are a minor.");
} else {
document.write("You are an adult.");
}
10. Events
What they do: Allow interaction with HTML elements (e.g., clicks, hovers).
Example:
javascript
function sayHello() {
alert("Hello!");
}
</script>
<button onclick="sayHello()">Click Me</button>
11. Arrays
What they do: Store multiple values in one variable.
Example:
javascript
var fruits = ["Apple", "Banana", "Cherry"];
document.write(fruits[0]); // Output: Apple
12. Objects
What they do: Store data in key-value pairs.
Example:
javascript
var student = {
name: "Adil",
age: 18,
grade: "A"
};
document.write(student.name); // Output: Adil
13. Math Object
What it does: Provides mathematical functions and constants.
Examples:
javascript
document.write(Math.sqrt(16)); // Square root: 4
document.write(Math.random()); // Random number between 0 and 1
14. Comments
What they do: Explain code without affecting its execution.
Types:
o Single-line: // This is a comment
o Multi-line:
javascript
/* This is
a multi-line comment */
15. DOM Manipulation
What it does: Lets you interact with and change HTML content dynamically.
Example:
javascript
document.getElementById("myDiv").innerHTML = "New Content!";
html
<div id="myDiv">Original Content</div>
Example 1: Simple Arithmetic
javascript
<script>
var num1 = 15;
var num2 = 5;
var result = num1 - num2; // Subtract num2 from num1
document.write(result); // Output: 10
</script>
Explanation: This code subtracts num2 from num1 and displays the result using document.write.
Example 2: Multiplication
javascript
<script>
var num1 = 8;
var num2 = 3;
var result = num1 * num2; // Multiply num1 by num2
document.write(result); // Output: 24
</script>
Explanation: The * operator is used to multiply two numbers, and the result is displayed.
Example 3: Division
javascript
<script>
var num1 = 20;
var num2 = 4;
var result = num1 / num2; // Divide num1 by num2
document.write(result); // Output: 5
</script>
Explanation: The / operator divides num1 by num2, and the result is displayed.
Example 4: Modulus
javascript
<script>
var num1 = 17;
var num2 = 5;
var remainder = num1 % num2; // Find the remainder when num1 is divided by num2
document.write(remainder); // Output: 2
</script>
Explanation: The % operator gives the remainder of a division.
Example 5: String Concatenation
javascript
<script>
var firstName = "Adil";
var lastName = "Qasmi";
var fullName = firstName + " " + lastName; // Combine strings with a space in between
document.write(fullName); // Output: Adil Qasmi
</script>
Explanation: Strings are combined using the + operator.
Example 6: If Statement
javascript
<script>
var age = 18;
if (age >= 18) {
document.write("You are eligible to vote."); // Output if condition is true
} else {
document.write("You are not eligible to vote."); // Output if condition is false
}
</script>
Explanation: The if-else statement checks a condition and executes code based on whether it
is true or false.
Example 7: For Loop
javascript
<script>
for (var i = 1; i <= 5; i++) {
document.write(i + "<br>"); // Output numbers 1 to 5, each on a new line
}
</script>
Explanation: The for loop repeats code, incrementing i from 1 to 5.
Example 8: Arrays
javascript
<script>
var fruits = ["Apple", "Banana", "Cherry"];
document.write(fruits[0]); // Output: Apple
</script>
Explanation: Arrays store multiple values. You access values using their index (starting from
0).
Example 9: Functions
javascript
<script>
function greet(name) {
return "Hello, " + name + "!";
}
document.write(greet("Adil")); // Output: Hello, Adil!
</script>
Explanation: Functions perform reusable tasks. This function takes a name and returns a
greeting.
Example 10: Prompt and Alert
javascript
<script>
var name = prompt("What is your name?"); // Ask the user for their name
alert("Hello, " + name + "!"); // Display a greeting in an alert box
</script>
Explanation: The prompt function collects user input, and alert displays a message.
Example 11: While Loop
javascript
<script>
var count = 1;
while (count <= 5) {
document.write("Count is: " + count + "<br>");
count++;
}
</script>
Explanation: The while loop keeps running as long as the condition (count <= 5) is true. The
variable count increments by 1 in each iteration.
Example 12: Switch Statement
javascript
<script>
var day = 3;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Invalid day");
}
</script>
Explanation: The switch statement checks the value of day and executes the corresponding
case. The break prevents the execution of the next cases.
Example 13: Ternary Operator
javascript
<script>
var age = 20;
var message = (age >= 18) ? "Adult" : "Minor";
document.write(message); // Output: Adult
</script>
Explanation: The ternary operator ? : is a shorthand for if-else statements.
Example 14: Random Numbers
javascript
<script>
var randomNumber = Math.floor(Math.random() * 10) + 1;
document.write("Random number: " + randomNumber);
</script>
Explanation: Math.random() generates a random decimal between 0 and 1. Multiplying it by
10 and using Math.floor() gives a random whole number between 1 and 10.
Example 15: String Length
javascript
<script>
var text = "Hello, World!";
document.write("The length of the text is: " + text.length);
</script>
Explanation: The .length property returns the number of characters in a string.
Example 16: Array Methods
javascript
<script>
var colors = ["Red", "Green", "Blue"];
colors.push("Yellow"); // Add an item to the end
colors.pop(); // Remove the last item
document.write(colors); // Output: Red,Green,Blue
</script>
Explanation: The push method adds an item to an array, while pop removes the last item.
Example 17: Object
javascript
<script>
var student = {
name: "Adil",
age: 18,
grade: "A"
};
document.write("Name: " + student.name + ", Grade: " + student.grade);
</script>
Explanation: Objects store data as key-value pairs. You can access values using
objectName.key.
Example 18: Event Listener
javascript
<script>
function showMessage() {
alert("Button clicked!");
}
</script>
<button onclick="showMessage()">Click Me</button>
Explanation: The onclick event triggers the showMessage function when the button is clicked.
Example 19: Date Object
javascript
<script>
var today = new Date();
document.write("Today's date is: " + today.toDateString());
</script>
Explanation: The Date object is used to work with dates and times. The toDateString() method
formats the date as a readable string.
Example 20: Set Timeout
javascript
<script>
setTimeout(function() {
document.write("This message appears after 3 seconds!");
}, 3000);
</script>
Explanation: The setTimeout function delays the execution of code by a specified time (in
milliseconds).
== compare value only
=== also checks data type
> greater than
>= greater than or equal to
< less than
<= less than or equal to
!= not equal to
&& and
Example:
<script>
var age = prompt("Please enter your age")
if(age >= 15 && age <= 20)
{document.write("We can give you admission")}
else
{document.write("We can't give you admission")}
</script>
|| or
% Gives remainder