Combined JavaScript Examples
Combined JavaScript Examples
1. Loops in JavaScript
Example from Basics File:
```javascript
for (let i = 1; i <= 6; i++) {
document.write("<h" + i + ">This is heading " + i + "</h" + i + ">");
}
```
Solution:
- Dynamically creates HTML headers `<h1>` through `<h6>`.
Solution:
- Iterates through an array and logs each element.
2. JavaScript Functions
Example from Basics File:
```javascript
function product(a, b) {
return a * b;
}
document.write(product(4, 3)); // Output: 12
```
Solution:
- Returns the product of two numbers.
Solution:
- Uses conditional statements to determine the appropriate greeting.
3. Events in JavaScript
Example from Basics File:
```html
<input type="button" value="Click me!" onclick="alert('Hello!')">
```
Solution:
- Executes an alert on button click.
Solution:
- Redirects the user to a new page on button click.
4. Variable Scope
Example from Basics File:
```javascript
var globalVar = 5;
function localScopeExample() {
let localVar = 10;
console.log(localVar); // Accessible locally
}
console.log(globalVar); // Accessible globally
```
Solution:
- Demonstrates global and local variable behavior.
Solution:
- Combines global and local variables for personalized output.
5. Function Expressions
Example from Basics File:
```javascript
let multiply = function (a, b) {
return a * b;
};
document.write(multiply(4, 3)); // Output: 12
```
Solution:
- Defines a function as an expression and uses it for multiplication.
Solution:
- Randomly selects a greeting from an array.
6. Arrays
Example from Objects File:
```javascript
var arr = [1, 2, 3];
arr.push(4); // Adds 4
arr.pop(); // Removes the last element
console.log(arr); // Output: [1, 2, 3]
```
Solution:
- Demonstrates adding and removing elements in arrays.
Solution:
- Iterates through an array and displays its elements.
7. String Methods
Example from Objects File:
```javascript
var str = "Hello, World!";
console.log(str.toUpperCase()); // HELLO, WORLD!
console.log(str.replace("World", "JavaScript")); // Hello, JavaScript!
```
Solution:
- Manipulates strings using `toUpperCase` and `replace`.
Solution:
- Combines string concatenation with dynamic input.