0% found this document useful (0 votes)
4 views

Class notes 2 (1)

The document provides an overview of JavaScript and jQuery, covering key concepts such as objects, functions, classes, promises, and jQuery effects. It includes examples of code snippets, explanations of methods like apply(), bind(), and call(), as well as jQuery functionalities like animations and event handling. Additionally, it addresses common university exam questions related to these topics.

Uploaded by

herix65476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Class notes 2 (1)

The document provides an overview of JavaScript and jQuery, covering key concepts such as objects, functions, classes, promises, and jQuery effects. It includes examples of code snippets, explanations of methods like apply(), bind(), and call(), as well as jQuery functionalities like animations and event handling. Additionally, it addresses common university exam questions related to these topics.

Uploaded by

herix65476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Tab 1

1. Introduction to JavaScript
JavaScript is a dynamic programming language used for web development, enabling
interactivity on web pages. It is a loosely typed language and supports both object-oriented
and functional programming paradigms.

Example: Basic JavaScript Code

console.log("Hello, JavaScript!"); // Output: Hello, JavaScript!

2. Objects in JavaScript
Objects are key-value pairs that store data and functions (methods).

a. Object Creation

There are multiple ways to create objects in JavaScript:

1. Using Object Literal


let person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Output: Hello, my name is Alice

2. Using new Object()


let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.display = function() {
console.log(`${this.brand} ${this.model}`);
};
car.display(); // Output: Toyota Camry
3. Using Object.create()
let animal = {
type: "Dog",
sound: function() {
console.log("Bark!");
}
};
let pet = Object.create(animal);
pet.type = "Golden Retriever";
pet.sound(); // Output: Bark!

b. Object Methods

Methods are functions inside objects.

let student = {
name: "John",
getName: function() {
return this.name;
}
};
console.log(student.getName()); // Output: John

c. Object Constructor Function


function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
let person1 = new Person("Bob", 30);
person1.greet(); // Output: Hello, my name is Bob

3. apply(), bind(), call()


These methods are used to control the value of this in function execution.

a. call()

Executes a function with a specific this value.

let person = { name: "Alice" };

function introduce(city) {
console.log(`Hello, I am ${this.name} from ${city}`);
}

introduce.call(person, "New York");


// Output: Hello, I am Alice from New York

b. apply()

Same as call() but takes arguments as an array.

introduce.apply(person, ["Los Angeles"]);


// Output: Hello, I am Alice from Los Angeles

c. bind()

Returns a new function with this bound.

let boundFunction = introduce.bind(person, "Chicago");


boundFunction();
// Output: Hello, I am Alice from Chicago

4. Functions in JavaScript
Functions are reusable blocks of code.

a. Function Syntax
function greet(name) {
return "Hello " + name;
}
console.log(greet("John")); // Output: Hello John

b. Function Hoisting

Function declarations are moved to the top during execution.

sayHello(); // Works even before definition


function sayHello() {
console.log("Hello!");
}

c. Arrow Functions

Shorter syntax for writing functions.

const add = (a, b) => a + b;


console.log(add(2, 3)); // Output: 5

d. Nested Functions

Functions inside other functions.

function outer() {
function inner() {
console.log("Inside inner function");
}
inner();
}
outer();

e. IIFE (Immediately Invoked Function Expression)

Executes immediately after definition.

(function() {
console.log("I am an IIFE!");
})(); // Output: I am an IIFE!

f. Callback Functions

A function passed as an argument.

function greetUser(name, callback) {


console.log("Hello, " + name);
callback();
}

function done() {
console.log("Task Completed");
}

greetUser("Alice", done);

5. Classes in JavaScript
Classes provide an OOP approach.

a. Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}

class Dog extends Animal {


speak() {
console.log(`${this.name} barks`);
}
}
let dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks

b. Shadowing Method

A method in a child class with the same name as in the parent class.

c. Private Methods (#)


class Person {
#secret; // Private property
constructor(name, secret) {
this.name = name;
this.#secret = secret;
}
getSecret() {
return this.#secret;
}
}
let p = new Person("John", "Hidden");
console.log(p.getSecret()); // Output: Hidden

d. Static Methods

Methods that belong to the class, not instances.

class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(5, 10)); // Output: 15

6. Promises
Used for asynchronous operations.
a. Creating a Promise
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) resolve("Task completed");
else reject("Task failed");
});

b. Handling .then, .catch, .finally


promise
.then((message) => console.log(message)) // Output: Task completed
.catch((error) => console.log(error))
.finally(() => console.log("Execution finished"));

c. Promise.all()

Waits for multiple promises.

let p1 = Promise.resolve("First");
let p2 = Promise.resolve("Second");
let p3 = Promise.resolve("Third");

Promise.all([p1, p2, p3]).then(console.log);


// Output: ["First", "Second", "Third"]

d. Promise.any()

Returns the first resolved promise.

let p4 = Promise.reject("Failed");
let p5 = Promise.resolve("Success");
Promise.any([p4, p5]).then(console.log); // Output: Success

e. Chaining Promises
new Promise((resolve) => resolve(2))
.then((num) => num * 2)
.then((num) => num * 3)
.then(console.log); // Output: 12

f. async/await

Cleaner syntax for Promises.

async function fetchData() {


let data = await Promise.resolve("Fetched Data");
console.log(data);
}
fetchData(); // Output: Fetched Data

1. Introduction to jQuery
jQuery is a lightweight, fast, and feature-rich JavaScript library that simplifies HTML document
traversal, event handling, animations, and AJAX interactions.

🔹 Why use jQuery?​


✅ Simplifies DOM manipulation​
✅ Provides cross-browser compatibility​
✅ Supports AJAX and animations​
✅ Reduces code complexity
Example: Basic jQuery Setup

html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Example</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="btn">Click Me</button>
<p id="text">Hello, jQuery!</p>

<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#text").text("Button Clicked!");
});
});
</script>
</body>
</html>

📝 Explanation:
●​ $() selects elements.
●​ .ready() ensures the script runs only after the document loads.
●​ .click() adds an event listener.

2. jQuery Effects
jQuery provides built-in effects like hide, show, fade, slide, and toggle.

a. Hide & Show


javascript
CopyEdit
$("#hideBtn").click(function(){
$("#box").hide(); // Hides the element
});

$("#showBtn").click(function(){
$("#box").show(); // Shows the element
});

b. Toggle
javascript
CopyEdit
$("#toggleBtn").click(function(){
$("#box").toggle(); // Toggles visibility
});

c. Fade Effects
javascript
CopyEdit
$("#fadeIn").click(function(){
$("#box").fadeIn(); // Fades in the element
});

$("#fadeOut").click(function(){
$("#box").fadeOut(); // Fades out the element
});

d. Slide Effects
javascript
CopyEdit
$("#slideUp").click(function(){
$("#box").slideUp(); // Slides up
});

$("#slideDown").click(function(){
$("#box").slideDown(); // Slides down
});

3. jQuery Callbacks
A callback function executes after a function completes execution.

javascript
CopyEdit
$("#fadeBtn").click(function(){
$("#box").fadeOut(1000, function(){
alert("Fade out completed!");
});
});

📝 Explanation: The alert appears after fading out.

4. jQuery Method Chaining


Method chaining allows multiple jQuery methods to be executed on the same element.

javascript
CopyEdit
$("#chainBtn").click(function(){
$("#box").css("background-color",
"blue").slideUp(1000).slideDown(1000);
});

📝 Explanation: The element's background changes to blue, slides up, and then slides down.

5. jQuery noConflict()
If multiple libraries use $, noConflict() prevents conflicts.

html
CopyEdit
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var jq = jQuery.noConflict();
jq(document).ready(function(){
jq("#btn").click(function(){
jq("#text").text("No Conflict Mode!");
});
});
</script>

📝 Explanation:
●​ $ is replaced with jq to avoid conflicts with other libraries.

6. jQuery Animation
The .animate() function creates custom animations.

javascript
CopyEdit
$("#animateBtn").click(function(){
$("#box").animate({left: "200px", opacity: "0.5"}, 1000);
});

📝 Explanation: Moves the element 200px to the right and reduces opacity over 1 second.

7. jQuery Traversing
Traversing allows navigating the DOM tree to find elements.

a. Parent & Children


javascript
CopyEdit
$("#parentBtn").click(function(){
$("#child").parent().css("border", "2px solid red");
});

$("#childBtn").click(function(){
$("#parent").children().css("color", "blue");
});

b. Siblings
$("#siblingBtn").click(function(){
$("#child").siblings().css("background", "yellow");
});
c. Closest & Find
$("#closestBtn").click(function(){
$("#child").closest("div").css("border", "2px solid green");
});

$("#findBtn").click(function(){
$("#parent").find("p").css("font-weight", "bold");
});
Tab 2
🔹 JavaScript Concepts
1️⃣ Introduction to JavaScript

●​ JavaScript is a client-side scripting language used for dynamic and interactive web
pages.
●​ It is an interpreted, event-driven, and loosely typed language.
●​ Can be used for both front-end (DOM manipulation) and back-end (Node.js)
development.

📌 University Exam Question


💡 What are the key features of JavaScript?​
✅ Solution:
1.​ Lightweight and interpreted language.
2.​ Supports event-driven programming.
3.​ Provides built-in objects (Array, Date, Math, etc.).
4.​ Supports functional and object-oriented programming.
5.​ Cross-platform compatibility.

2️⃣ Objects in JavaScript

a) Object Creation

●​ Objects can be created using:


○​ Object literals: { key: value }
○​ Constructor function: new Object()
○​ Class-based objects (ES6 classes)

b) Object Methods

●​ Methods are functions inside objects.


●​ Defined as key: function() {}.
●​ Can access properties using this.

c) Object Constructor Function

●​ Function used to create multiple objects with the same structure.

d) Apply, Bind, Call


●​ call(): Calls a function with a given this value.
●​ apply(): Similar to call but accepts arguments as an array.
●​ bind(): Returns a new function with this permanently set.

📌 University Exam Question


💡 What is the difference between call, apply, and bind?​
✅ Solution:
1.​ call() – Calls a function with parameters individually.
2.​ apply() – Calls a function with parameters in an array.
3.​ bind() – Returns a new function with this bound.

3️⃣ Functions in JavaScript

a) Syntax
js
CopyEdit
function add(a, b) {
return a + b;
}

b) Function Hoisting

●​ JavaScript moves function declarations to the top before execution.

c) Arrow Functions

●​ Shorter syntax for functions.

js
CopyEdit
const sum = (a, b) => a + b;

d) Nested Functions

●​ Functions inside functions.

e) IIFE (Immediately Invoked Function Expression)

●​ Executes immediately after definition.


js
CopyEdit
(function () {
console.log("IIFE executed");
})();

f) Callback Functions

●​ A function passed as an argument to another function.

js
CopyEdit
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}

📌 University Exam Question


💡 What is function hoisting in JavaScript?​
✅ Solution:
1.​ JavaScript moves function declarations to the top before execution.
2.​ Allows calling functions before defining them.

4️⃣ Classes in JavaScript

a) Inheritance

●​ One class extends another.

js
CopyEdit
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}

b) Shadowing Method

●​ Child class overrides the parent’s method.

c) Private Methods

●​ Methods prefixed with # are private.

js
CopyEdit
class Person {
#privateMethod() {
console.log("Private method");
}
}

d) Static Methods

●​ Methods that belong to the class, not instances.

js
CopyEdit
class MathUtil {
static add(a, b) {
return a + b;
}
}

📌 University Exam Question


💡 What is the difference between private and static methods?​
✅ Solution:
1.​ Private methods (#methodName) are only accessible within the class.
2.​ Static methods (static methodName()) belong to the class, not instances.
5️⃣ Promises in JavaScript

●​ Handle asynchronous operations.

a) Promise Creation
js
CopyEdit
let myPromise = new Promise((resolve, reject) => {
let success = true;
success ? resolve("Success!") : reject("Error!");
});

b) Error Handling

●​ Using .catch() to handle errors.

c) .then, .catch, .finally

●​ .then(): Runs if resolved.


●​ .catch(): Runs if rejected.
●​ .finally(): Runs always.

d) Promise.all and Promise.any

●​ Promise.all(): Waits for all promises to resolve.


●​ Promise.any(): Resolves when any one resolves.

e) Async Await
js
CopyEdit
async function fetchData() {
let data = await fetch("https://api.example.com");
return data.json();
}

📌 University Exam Question


💡 What is the difference between async-await and promises?​
✅ Solution:
1.​ Promises use .then() and .catch().
2.​ Async-await makes asynchronous code look synchronous.

🔹 jQuery Concepts
1️⃣ Introduction to jQuery

●​ A JavaScript library for easier DOM manipulation and AJAX requests.

2️⃣ jQuery Effects

●​ Predefined animations like fadeIn(), slideDown(), etc.

js
CopyEdit
$("#btn").click(function() {
$("#box").fadeOut();
});

📌 University Exam Question


💡 Name some jQuery effects and their use.​
✅ Solution:
1.​ fadeIn(), fadeOut() – Shows/hides elements.
2.​ slideUp(), slideDown() – Collapses/expands elements.

3️⃣ jQuery Callback

●​ Ensures a function runs after another.

js
CopyEdit
$("#box").fadeOut(500, function() {
alert("Animation Done");
});
📌 University Exam Question
💡 What is a jQuery callback function?​
✅ Solution:
1.​ Function executed after another function.
2.​ Ensures code runs in sequence.

4️⃣ Method Chaining

●​ Calls multiple jQuery methods on the same element.

js
CopyEdit
$("#box").slideUp().fadeIn();

📌 University Exam Question


💡 What is method chaining in jQuery?​
✅ Solution:
1.​ Combining multiple jQuery methods into a single statement.
2.​ Increases performance.

5️⃣ noConflict()

●​ Prevents conflicts with other libraries.

js
CopyEdit
var jq = $.noConflict();
jq("#box").hide();

📌 University Exam Question


💡 What is the use of noConflict() in jQuery?​
✅ Solution:
1.​ Resolves conflicts with $ in other libraries.
2.​ Allows renaming jQuery to another variable.

6️⃣ jQuery Animation

●​ Custom animations using .animate().

js
CopyEdit
$("#box").animate({width: "300px"});

📌 University Exam Question


💡 How does the animate() function work in jQuery?​
✅ Solution:
1.​ Allows custom animations.
2.​ Accepts CSS properties and duration.

7️⃣ jQuery Traversing

●​ Selecting elements based on hierarchy.

js
CopyEdit
$("ul li:first").css("color", "red");

📌 University Exam Question


💡 What is traversing in jQuery?​
✅ Solution:
1.​ Moving up/down/selecting elements in DOM.
2.​ Methods: parent(), children(), siblings().

You might also like