JavaScript Basic Revision
Lesson 1: Introduction
JavaScript is a programming language used to make web pages interactive.
It runs on the browser and can manipulate HTML and CSS dynamically.
Example: Displaying an Alert
alert("Welcome to JavaScript!");
Output: A pop-up alert saying "Welcome to JavaScript!"
Lesson 2: Hello World
The first step in learning JavaScript is writing a simple "Hello World" program.
Example:
console.log("Hello, World!");
Output:
Hello, World!
console.log()
prints messages to the browser's console.
Lesson 3: Arrays
Arrays store multiple values in a single variable.
Example:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]);
Output:
Apple
Indexing starts at 0.
Lesson 4: Loops
Loops execute a block of code multiple times.
Example: For Loop
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Lesson 5: Objects
Objects store key-value pairs.
Example:
let person = {
name: "John",
age: 25
};
console.log(person.name);
Output:
John
Lesson 6: Functions
Functions allow reusable code.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
Output:
Hello, Alice!
Lesson 7: Closure
A closure is a function inside another function that remembers its parent’s variables.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
let increment = outer();
increment();
increment();
Output:
1
2
The
inner
function rememberscount
even afterouter
has executed.
Lesson 8: Promises
Promises are used to handle asynchronous operations in JavaScript.
They have three states:
Pending: Initial state, not yet resolved or rejected.
Resolved (Fulfilled): Operation completed successfully.
Rejected: Operation failed.
Example 1: Basic Promise
let promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("Promise Resolved!");
} else {
reject("Promise Rejected!");
}
}, 2000);
});
promise.then(response => console.log(response))
.catch(error => console.log(error));
Output after 2 seconds:
Promise Resolved!
.then()
executes when the promise is resolved..catch()
handles errors when the promise is rejected.
Example 2: Chaining Promises
function firstTask() {
return new Promise(resolve => {
setTimeout(() => resolve("First task done!"), 1000);
});
}
function secondTask() {
return new Promise(resolve => {
setTimeout(() => resolve("Second task done!"), 1000);
});
}
firstTask().then(response => {
console.log(response);
return secondTask();
}).then(response => console.log(response));
Output:
First task done!
Second task done!
This demonstrates executing tasks sequentially.
Lesson 9: Async/Await
async
functions return a promise.await
pauses execution until the promise resolves.
Example 1: Fetching Data
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
}
fetchData();
Output: (Example JSON Response)
{
"userId": 1,
"id": 1,
"title": "sample title",
"body": "sample body text"
}
await
ensures data is retrieved before continuing.
Example 2: Handling Errors
async function fetchWithErrorHandling() {
try {
let response = await fetch('https://wrongurl.com');
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Error fetching data", error);
}
}
fetchWithErrorHandling();
Output:
Error fetching data TypeError: Failed to fetch
try...catch
handles errors gracefully.
Lesson 10: JavaScript this
Keyword
The this
keyword in JavaScript refers to the object that is executing the current function. The value of this
depends on where it is used.
1. this
in Global Context
Output:
In a browser, this
refers to the window
object.
2. this
in an Object Method
Output:
Here, this.name
refers to Alice
because this
points to the person
object.
3. this
in a Function (Strict Mode)
Output:
undefined
(because strict mode prevents this
from referring to window
).
4. this
in Arrow Functions
Arrow functions do not have their own this
. They inherit this
from their surrounding scope.
Output:
undefined
(since this
refers to the outer scope, which is window
).
Lesson 11: JavaScript Form Validation
Form validation ensures that users provide valid input before submitting a form.
1. Simple Form Validation
Explanation:
-
The form calls
validateForm()
on submission. -
If the input is empty, it shows an alert and prevents submission.
2. Checking Input Length
Lesson 12: Regular Expressions (RegEx
) in JavaScript
Regular Expressions help in pattern matching and string validation.
1. Testing a Simple Pattern
Output:
The .test()
method checks if "hello"
exists in the string.
2. Validating a Phone Number
Output:
The pattern ensures the number contains exactly 10 digits.
3. Extracting Words from a String
Output:
It extracts words from the sentence.
Lesson 13: Email Validation using JavaScript
Email validation ensures a user enters a properly formatted email.
1. Basic Email Validation
2. Checking Email with a Form
This ensures only valid emails are accepted.
__________________________________________________________
Lesson 14: Callbacks
A callback function is a function passed as an argument to another function.
Example:
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function done() {
console.log("Callback executed.");
}
greet("Alice", done);
Output:
Hello, Alice
Callback executed.
------------------------------------------------------------------------
Lesson 15: Error Handling
try...catch
is used to handle errors in JavaScript.
Example:
try {
let num = undefined;
console.log(num.length);
} catch (error) {
console.log("Error caught: " + error.message);
}
Output:
Error caught: Cannot read properties of undefined
Lesson 16: Event Loop
The JavaScript event loop handles asynchronous tasks and executes callbacks.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout Callback");
}, 0);
console.log("End");
Output:
Start
End
Timeout Callback
Even though the timeout is 0, the callback runs after synchronous code.
___________________________________________________________________
Lesson 17: JavaScript DOM Tutorial
The Document Object Model (DOM) represents an HTML document as a tree structure.
JavaScript manipulates the DOM to modify webpages dynamically.
Selecting Elements
Example 1: Changing Content
document.getElementById("demo").innerHTML = "Hello, DOM!";
Example 2: Changing Style
document.getElementById("demo").style.color = "red";
Creating and Appending Elements
Example 3: Adding a New Element
let newPara = document.createElement("p");
newPara.innerText = "This is a new paragraph";
document.body.appendChild(newPara);
Output:
A new paragraph appears on the webpage.
Event Listeners
Example 4: Button Click Event
document.getElementById("myButton").addEventListener("click", function() {
alert("Button Clicked!");
});
Listens for a click event and triggers an alert.
Modifying Classes
Example 5: Toggling Class
document.getElementById("box").classList.toggle("highlight");
Toggles a CSS class for styling.
Comments
Post a Comment