diff --git a/Ch 1 Practice Set.js b/Ch 1 Practice Set.js index ca7571b..987b16e 100644 --- a/Ch 1 Practice Set.js +++ b/Ch 1 Practice Set.js @@ -1,72 +1,72 @@ -//Ch 1 Variable -> Practice Set - -// Q1) Create a Variable of Type String And try To Add a Number To It. - - -let a = "Darshan"; -let b = 10; - -console.log(a + b); - -// Output: Darshan10 - - -// Q2) Use typeof Operator To Find Data-type of the First Question of the Last Answer. - - -console.log(typeof (a + b)); - -// Output: String - - -// Q3) Create a Const Object in JavaScript. Can You Change It to Hold A Number Latter? - - -const c = { - name: "Darshan", - author: "CrptoMinds", - isPrincipal: false -} - -c = 1; -// Output: Assignment to Constant Variable -> Ans Is No - - -// Q4) Try To Add a New Key In Q3 Const Object. Were You Able To Do It? - - -const c1 = { - name: "Darshan", - author: "CrptoMinds", - isPrincipal: false -} - -c1['friend'] = "Krupali"; - -//const c1 -> Point Object -> We Can Change Value Inside The Object -> We Can't Make New c1 Objact Again -> Because Of Constant -console.log(c1); - -// Output: -// { -// name: 'Darshan', -// author: 'CrptoMinds', -// isPrincipal: false, -// friend: 'Krupali' -// } - - -// Q4) Write A JS Program To Create a Word-Meaning Dictionary Of 5 Words. - - -const dict = { - appreciate: "recognize the full worth of ", - ataraxia: "a state of freedom from emotional disturbance", - yakka: "Work, especially hard work." - -} - -console.log(dict.yakka); -console.log(dict['yakka']); - -// Output: Work, especially hard work. +//Ch 1 Variable -> Practice Set + +// Q1) Create a Variable of Type String And try To Add a Number To It. + + +let a = "Darshan"; +let b = 10; + +console.log(a + b); + +// Output: Darshan10 + + +// Q2) Use typeof Operator To Find Data-type of the First Question of the Last Answer. + + +console.log(typeof (a + b)); + +// Output: String + + +// Q3) Create a Const Object in JavaScript. Can You Change It to Hold A Number Latter? + + +const c = { + name: "Darshan", + author: "CrptoMinds", + isPrincipal: false +} + +c = 1; +// Output: Assignment to Constant Variable -> Ans Is No + + +// Q4) Try To Add a New Key In Q3 Const Object. Were You Able To Do It? + + +const c1 = { + name: "Darshan", + author: "CrptoMinds", + isPrincipal: false +} + +c1['friend'] = "Krupali"; + +//const c1 -> Point Object -> We Can Change Value Inside The Object -> We Can't Make New c1 Objact Again -> Because Of Constant +console.log(c1); + +// Output: +// { +// name: 'Darshan', +// author: 'CrptoMinds', +// isPrincipal: false, +// friend: 'Krupali' +// } + + +// Q4) Write A JS Program To Create a Word-Meaning Dictionary Of 5 Words. + + +const dict = { + appreciate: "recognize the full worth of ", + ataraxia: "a state of freedom from emotional disturbance", + yakka: "Work, especially hard work." + +} + +console.log(dict.yakka); +console.log(dict['yakka']); + +// Output: Work, especially hard work. // Work, especially hard work. \ No newline at end of file diff --git a/Ch 1 Variable.js b/Ch 1 Variable.js index 98cc240..e1314b7 100644 --- a/Ch 1 Variable.js +++ b/Ch 1 Variable.js @@ -1,137 +1,137 @@ -// Variable Declaration: -// To declare a variable in JavaScript: -// Before ES6 -> var was used -> After ES6 -> let is used -// const is used to define constant -> throughout the program value not changed - -// Let, Const -> Used To Block Scope Variable Declaration -// Var -> Globally Scoped -// Let Can Be Updated But Not Re-declared -//Const -> Neither Updated Nor Re-declared -// Var -> Can Be Updated And Re-declared -// Var & Let Is Initialized With Undefined -> Const Are Not -> -var dp; -let ap; -const hp; //Error - -var myVariable; // Declaration using var -let anotherVariable; // Declaration using let -const PI = 3.14159; // Declaration using const - -// JS is Case Sensitive - -// You can also declare and assign a value to a variable in a single line. - -//JavaScript Data-Type -//Object Is Non Primitive Data-Type -// Primitive -> Null, Number, String, Symbol, Undefined, Boolean, Bigint -> Fundamental Data-Type -> nn bb ss u - - -let y = BigInt("265"); -let x = Symbol("I Am Symbol"); -let s = null; //Define Null - -// Type -console.log(typeof x); - -//Object -> In Python -> Dictionary -//ES6 -> ECMAScript -> Modern JavaScript -const item = { - name: "CryptoMinds", - age: "12" - //Key: Value -} - -console.log(item["age"]); //Look Up - -//Scope -> Alt + Click -> Multiple Cursor In Replit -//var - -var b = 11; -var b = 13; // Allow To Use - -{ - var b = 15; - console.log(b); -} -console.log(b); - -//Output -// 15 -// 15 - -//let - -let b = 11; - -{ - let b = 15; - console.log(b); -} -console.log(b); - -//Output -// 15 -// 11 - - -let c = 16; -c = 17; //Update - - -let d = 16; -let d = 17; //Error - - - - - - -var myNumber = 42; -let myString = "JavaScript"; -const myConstant = true; - -// Variable Naming: -// JavaScript variable names can include letters, digits, underscores, and dollar signs. They must start with a letter, underscore, or dollar sign (but not a digit). JavaScript is case-sensitive, so myVariable and myvariable are considered different variables. - -var firstName; -let age; -const PI = 3.14; - - - -// Better Practice to use let and Const -// Mostly Use Const -// JS Allow to Change Variable Type In Run Time -> Only One - - -function myFunction() { - var x = 10; // Function-scoped variable - if (x > 5) { - let y = 20; // Block-scoped variable - console.log(x + y); - } - console.log(x); // Accessible - console.log(y); // Error: y is not defined -} - - -// Variable Hoisting: -// JavaScript has a concept called "hoisting," where variable and function declarations are moved to the top of their respective scopes during the compilation phase. Variables declared with var are hoisted but are not initialized until the line where they are defined. This can sometimes lead to unexpected behavior. - - -console.log(x); // Undefined -var x = 10; - - -// Variable Constants: -// Variables declared with const are constants, meaning their value cannot be reassigned once it is set. However, it's important to note that const does not make objects or arrays immutable. It only prevents the reassignment of the variable itself. - - -const PI = 3.14; -PI = 3.14159; // Error: Assignment To Constant Variable - -const myArray = [1, 2, 3]; -myArray.push(4); // Valid, Since The Array Itself Is Mutable - -// Conclusion: +// Variable Declaration: +// To declare a variable in JavaScript: +// Before ES6 -> var was used -> After ES6 -> let is used +// const is used to define constant -> throughout the program value not changed + +// Let, Const -> Used To Block Scope Variable Declaration +// Var -> Globally Scoped +// Let Can Be Updated But Not Re-declared +//Const -> Neither Updated Nor Re-declared +// Var -> Can Be Updated And Re-declared +// Var & Let Is Initialized With Undefined -> Const Are Not +var dp; +let ap; +const hp; //Error + +var myVariable; // Declaration using var +let anotherVariable; // Declaration using let +const PI = 3.14159; // Declaration using const + +// JS is Case Sensitive + +// You can also declare and assign a value to a variable in a single line. + +//JavaScript Data-Type +//Object Is Non Primitive Data-Type +// Primitive -> Null, Number, String, Symbol, Undefined, Boolean, Bigint -> Fundamental Data-Type -> nn bb ss u + + +let y = BigInt("265"); +let x = Symbol("I Am Symbol"); +let s = null; //Define Null + +// Type +console.log(typeof x); + +//Object -> In Python -> Dictionary +//ES6 -> ECMAScript -> Modern JavaScript +const item = { + name: "CryptoMinds", + age: "12" + //Key: Value +} + +console.log(item["age"]); //Look Up + +//Scope -> Alt + Click -> Multiple Cursor In Replit +//var + +var b = 11; +var b = 13; // Allow To Use + +{ + var b = 15; + console.log(b); +} +console.log(b); + +//Output +// 15 +// 15 + +//let + +let b = 11; + +{ + let b = 15; + console.log(b); +} +console.log(b); + +//Output +// 15 +// 11 + + +let c = 16; +c = 17; //Update + + +let d = 16; +let d = 17; //Error + + + + + + +var myNumber = 42; +let myString = "JavaScript"; +const myConstant = true; + +// Variable Naming: +// JavaScript variable names can include letters, digits, underscores, and dollar signs. They must start with a letter, underscore, or dollar sign (but not a digit). JavaScript is case-sensitive, so myVariable and myvariable are considered different variables. + +var firstName; +let age; +const PI = 3.14; + + + +// Better Practice to use let and Const +// Mostly Use Const +// JS Allow to Change Variable Type In Run Time -> Only One + + +function myFunction() { + var x = 10; // Function-scoped variable + if (x > 5) { + let y = 20; // Block-scoped variable + console.log(x + y); + } + console.log(x); // Accessible + console.log(y); // Error: y is not defined +} + + +// Variable Hoisting: +// JavaScript has a concept called "hoisting," where variable and function declarations are moved to the top of their respective scopes during the compilation phase. Variables declared with var are hoisted but are not initialized until the line where they are defined. This can sometimes lead to unexpected behavior. + + +console.log(x); // Undefined +var x = 10; + + +// Variable Constants: +// Variables declared with const are constants, meaning their value cannot be reassigned once it is set. However, it's important to note that const does not make objects or arrays immutable. It only prevents the reassignment of the variable itself. + + +const PI = 3.14; +PI = 3.14159; // Error: Assignment To Constant Variable + +const myArray = [1, 2, 3]; +myArray.push(4); // Valid, Since The Array Itself Is Mutable + +// Conclusion: // JavaScript variables play a crucial role in storing and manipulating data within a program. By understanding variable declaration, assignment, naming, scope, and the differences between var, let, and const, developers can effectively work with variables to create dynamic and interactive JavaScript applications. \ No newline at end of file diff --git a/Ch 10 Network Request And Storing Data.js b/Ch 10 Network Request And Storing Data.js new file mode 100644 index 0000000..12dbaa1 --- /dev/null +++ b/Ch 10 Network Request And Storing Data.js @@ -0,0 +1,291 @@ +// Fetch API +// The Fetch API provides a simple way to fetch resources (for example images, documents, or streams) over the internet + +// JavaScript Can Be Used To Send And Retrieve Information From The Network When Needed (AJAX) + +// AJAX Used Earlier -> Now JSON Is Widely Used + +// AJAX -> Asynchronous JavaScript And XML + +// Fetch API + +// Fetch Is Used To Get Data Over The Internet + +// let promise = fetch(URL, [options]) +// Without Option A GET Request Is Sent + +// Getting The Response Is A 2-Stage Process + +// 1. An Object Of Response Class Containing "Status" And "Ok" Properties +// Status - The HTTP Status Code, eg 200 +// Ok - Boolean, True If The HTTP Status Code Is 200-299 + +// 2. After That We Need To Call Another Method To Access The Body In Different Formats + +// Response.text() - Read The Response As Text +// Response.json() - Parse The Response As JSON + +// Other Methods Include - Response.formData(), Response.blob(), Response.arrayBuffer() + +// Note - We Can Use Only One Body Method. For Example If We Have Used Response.text() Then We Cannot Use Response.json() + +// Response Headers + +// The Response Headers Are Available In Response.headers + +// Request Headers +// To Set A Request Header In Fetch, We Can Use The Headers Option + +// let res = fetch(url, { +// header: { +// Authentication: 'Secret' +// } +// }); + + +// POST Request + +// let p = fetch("https://api.rainviewer.com/public/weather-maps.json") +// p.then((response) => { +// console.log(response.status) +// console.log(response.ok) +// console.log(response.headers) +// return response.json() +// }).then(data => { +// console.log(data) +// }) +// Why Two .then Is Mentioned Above? +// Response Contain Two Properties - Status And Ok +// Data Is The Actual Result Of The Request + +// POST Request +// To Make Post Request, We Need To Use Fetch Options +// Method -> HTTP Method, E.g POST +// Body -> The Request Body + +// const createTodo = async (todo) => { +// let options = { +// method: "POST", +// headers: { +// "Content-type": "application/json" +// }, +// body: JSON.stringify(todo), +// } +// let p = await fetch('https://jsonplaceholder.typicode.com/posts', options) +// let response = await p.json() +// return response +// } + +// const getTodo = async (id) => { +// let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id) +// let r = await response.json() +// return r +// } + +// const mainFunc = async () => { +// let todo = { +// title: 'Harry2', +// body: 'bhai2', +// userId: 1100, +// } +// let todor = await createTodo(todo) +// console.log(todor) +// console.log(await getTodo(101)) +// } + +// mainFunc() + +// let response = await fetch('/url', { +// method: 'POST', +// headers: { +// 'Content-Type': 'application/json' +// }, +// body: JSON.stringify({ +// title: 'foo', +// body: 'bar', +// userId: 1, +// }) +// }) + +// let result = await response.json() + +// JavaScript Cookies +// Cookies Are Small Strings Of Data Stored By The Client Side Stored In Browser +// In JavaScript, Document.cookie Property Can Be Used To Access Cookies + +// Cookies Are Set By Web Server Using Set-Cookie HTTP Header. Next Time When The Request Is Sent To The Same Domain, The Browser Sends The Cookie Using Cookie HTTP Header In The Request. That Way The Server Knows Who Sent The Request. + +// We Can Also Access Cookies Using document.cookie Property +// alert(document.cookie) -> Contain Key Value Pairs Decoded + +// Key Value Pair Are Separated By Delimited By ; -> Key = Pair; + +// Writing A Cookie +// An Assignment To Document.cookie Is Treated Specially In A Way That Write Operation Doesn't Touch Other Cookie + +// document.cookie = "name=harry1122334400" +// Updates Only Cookie Named User To Harry + +// Bahot Chota Sa Data Store Karneka Tarika +// console.log(document.cookie) +// document.cookie = "name=harry1122334400" +// document.cookie = "name2=harry11223344002" // Set Call +// document.cookie = "name=harry" // Old Is Updated +// let key = prompt("enter your key") +// let value = prompt("enter your value") +// document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}` +// console.log(document.cookie) + +// Encode URI Component -> This Function Encodes A Set Of Special Characters In A Way That The Component Can Be Decoded Using DecodeURI + +// This Function Helps Keep The Valid Formatting. It Is Used Like This + +// document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}` + +// This Way Spacial Character Are Encoded + +// Cookies Option + +// Cookies Have Several Options Which Can Be Provided After Key=Value To A Set Call Like This : + +// document.cookie = "user=harry;path=/a;expires=Tue,29 March 204" +// path -> Which Domain The Cookie Will Be Available On +// document.cookie = "user=harry;path=/a;expires=Tue,29 March 2041 12:00:33 GMT" +// Set Only One Cookies With Path And Expires +// document.cookies -> Can Set Only One Cookie At A Time Other Are Option + + +// Path Option Makes The Cookie Available Only At The /a and /a/b ................ Path. -> Not Available At /b But Available At /a/b +// Expires At -> Date When Cookie Will Be Expired. Time Stamp In GMT + +// Note : +// 1. The Name And Value Pair After EncodeURI Component Can Be Up To 4KB +// 2. Total No Of Cookies Per Domain Is Limited To Arbitrary Number Around 20+ (Exact Number Is Browser Dependent) +// 3. Cookies Are Sent With Each Request To The Server, So The Server Can Learn Who Sent The Request + +// Local Storage +// Local Storage Is Web Storage Object Which Are Not Sent To Server With Each Request +// Data Survives Page Refresh And Even After Full Restart + +// These Are Method Provided By Local Storage + +// 1. localStorage.setItem(key, value) -> Store Key Value Pair Or Update The Value If Key Is Already Present +// 2. localStorage.getItem(key) -> Get The Value By Key +// 3. localStorage.removeItem(key) -> Remove The Key Value Pair +// 4. localStorage.clear() -> Clear The Entire Local Storage +// 5. localStorage.key(index) -> Get The Key On A Given Position +// 6. localStorage.length -> The Number Of Stored Items +// We Can Use Both Key And Value As String + +// let key = prompt("Enter key you want to set") +// let value = prompt("Enter value you want to set") + +// localStorage.setItem(key, value) + +// console.log(`The value at ${key} is ${localStorage.getItem(key)}`) + +// if (key == "red" || key == "blue") { +// localStorage.removeItem(key) +// } + +// if (key == 0) { +// localStorage.clear() +// } +// console.log(localStorage.length) + +// We Can Get And Set Values Like An Object +// localStorage.one = 1 +// alert(localStorage.one) +// delete localStorage.one + +// Note: +// 1. Both Key And Value Must Be String +// 2. We Can Use The Two JSON Methods To Store Objects In Local Storage + +// JSON.stringify(object) -> Converts Objects To JSON Strings +// JSON.parse(string) -> Converts String To Objects (Must Be Valid JSON) + +// Session Storage +// Session Storage Exists For Only One Session. Data Survives Refresh But Not Close Of Browser + +// Used Less As Compared To Local Storage +// Properties And Method Are Same As Local Storage But: +// 1. Session Storage Data Survives Page Refresh But Not Close Of Browser +// It Exists Only Within The Current Browser Tab. Another Tab With Same Page Will Have Empty Session Storage + +// 2. The Data Survives Page Refresh, But Not Closing / Opening Of Browser + +// Storage Event +// When The Data Gets Updated In Local Storage Or Session Storage, Storage Event Triggered With These Properties: +// 1. key -> The Key +// 2. oldValue -> Previous Value +// 3. newValue -> New Value +// 4. url -> Page URL +// 5. storageArea -> local or session + +// We Can Listen The OnStorage Event Of Window Which Is Triggered When Updates Are Made To The Same Storage From Other Documents + +// sessionStorage.getItem("name") +// sessionStorage.clear() +// sessionStorage.removeItem("name") +// sessionStorage.setItem("name", "harry") +// sessionStorage.removeItem("name") + +// Dusri Tab Dusra Page Different Session Storage + +// window.onstorage = (e) => { +// alert("changed") +// console.log(e) +// } + +// Practice Set + +// Q1 Use a Free API From The Internet And Feed Your App With Live Data + +// Q2 Create A Note Saving App Which Stores Your Note To localStorage + +// Q3 Repeat Q2 And Fetch The Note Which User Entered In The Previous Question + +// Q4 Delete The Note In The Previous Question + + +let url = "https://kontests.net/api/v1/all" +let response = fetch(url) +response.then((v) => { + return v.json() +}).then((contests) => { + console.log(contests) + ihtml = "" + for (item in contests) { + console.log(contests[item]) + ihtml += ` +
+ ... +
+
${contests[item].name}
+

Status is ${contests[item].status} and site is ${contests[item].site}

+

In 24 Hours? ${contests[item].in_24_hours}

+

Starts at: ${contests[item].start_time} +

Starts at: ${contests[item].end_time} + Visit Contest +

+
+ ` + } + cardContainer.innerHTML = ihtml +}) + +/* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */ +// let n = localStorage.getItem("note") +// alert("Your note is " + n) + +// let a = prompt("Enter your note") +// if (a) { +// localStorage.setItem("note", a) +// } + +// let c = confirm("Do you want to delete your note?") +// if (c) { +// localStorage.removeItem("note") +// alert("Note deleted successfully!") +// } diff --git a/Ch 11 Object Oriented Programing.js b/Ch 11 Object Oriented Programing.js new file mode 100644 index 0000000..4e0f5d2 --- /dev/null +++ b/Ch 11 Object Oriented Programing.js @@ -0,0 +1,486 @@ +// [[Prototype]] +// First Priority Object Method Ki Than Nahi Mila To Prototype Ka Method Use Karo +// JavaScript Object Have A Special Property Called Prototype That Is Either Null Or Reference To Another Object + +// When We Try To Read A Property From An Object And It's Missing, JavaScript Will Take It From Its Prototype. This Is Called Prototypal Inheritance. + +// let a = { +// name2: "Harry", +// language: "JavaScript", +// run: () => { +// alert("self run") +// } +// } +// console.log(a) + + +// let p = { +// run: () => { +// alert("run") +// } +// } + +// p.__proto__ = { +// name: "Jackie" +// } + +// a.__proto__ = p +// a.run() +// console.log(a.name) + +// Setting Prototype +// We Can Set Prototype By Setting __proto__ Property On Any Object. Now If We Read A Property From That Object, JavaScript Will Take It From The Object Itself And If It's Missing, JavaScript + +// If We Have A Method In Object, It Will Be Called From Object. If Its Missing In Object And Present In Prototype, It Will Be Called From Prototype. + +// Classes And Objects + +// In OOP A Class Is An Extensible Program Code Template For Creating Objects, Providing Initial Value For State (Member Variables) And Implementation Of Behavior (Member Functions) + +// Syntax: +// class ClassName { +// constructor() { +// // initialise +// } +// // Function +// method_name() { +// // code +// } +// } + +// class RailwayForm { +// submit() { +// alert(this.name + ": Your form is submitted for train number: " + this.trainno) +// } +// cancel() { +// alert(this.name + ": This form is cancelled for train number: " + this.trainno) +// } +// fill(givenname, trainno) { +// this.name = givenname +// Object Associated Property = Input Me A Rahi Value +// this.trainno = trainno +// } +// } + +// // Create a form for Harry +// let harryForm = new RailwayForm() +// // Fill the form with Harry's details +// harryForm.fill("Harry", 145316) + +// // Create a forms for Rohan +// let rohanForm1 = new RailwayForm() +// let rohanForm2 = new RailwayForm() +// // Fill the forms with Rohan's details +// rohanForm1.fill("Rohan", 222420) +// rohanForm2.fill("Rohan", 2229211) + +// harryForm.submit() +// rohanForm1.submit() +// rohanForm2.submit() +// rohanForm1.cancel() + +// We Can Than Use New Class() To Create An Object + +// Constructor Method +// A Constructor Is A Special Method Which Is Automatically Called When An Object Is Created. -> Its Used To Initialize The Object. + +// Old + +// class RailwayForm { +// constructor(givenname, trainno) { +// console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno) +// this.name = givenname +// this.trainno = trainno +// } + +// submit() { +// alert(this.name + ": Your form is submitted for train number: " + this.trainno) +// } +// cancel() { +// alert(this.name + ": This form is cancelled for train number: " + this.trainno) +// } +// } + +// // Create & fill a form for Harry +// let harryForm = new RailwayForm("Harry", 145316) +// // No need to Fill the form with Harry's details +// // harryForm.fill() + +// // Create & fill a forms for Rohan +// let rohanForm1 = new RailwayForm("Rohan", 222420) +// let rohanForm2 = new RailwayForm("Rohan", 2229211) + + + +// harryForm.submit() +// rohanForm1.submit() +// rohanForm2.submit() +// rohanForm1.cancel() + +// New + +// class RailwayForm { +// constructor(givenname, trainno, address) { +// console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno) +// this.name = givenname +// this.trainno = trainno +// this.address = address +// } + +// preview() { +// alert(this.name + ": Your form is for Train number: " + this.trainno + " and your address is " + this.address) +// } + +// submit() { +// alert(this.name + ": Your form is submitted for train number: " + this.trainno) +// } + +// cancel() { +// alert(this.name + ": This form is cancelled for train number: " + this.trainno) +// this.trainno = 0 +// } +// } + +// let harryForm = new RailwayForm("Harry", 13488, "420, Pacific Ocean, Ocean, Bihar - 0000555") +// harryForm.preview() +// harryForm.submit() +// harryForm.cancel() +// harryForm.preview() + + +// Class Inheritance + +// Class Inheritance Is A Way For One Class To Inherit All The Methods And Properties From Another Class. In JavaScript, It Is Done By Using Extends Keyword. + +// class Animal { +// constructor(name, color) { +// this.name = name +// this.color = color +// } +// run() { +// console.log(this.name + " is running!") +// } +// shout() { +// console.log(this.name + " is barking!") +// } +// } + +// class Monkey extends Animal { +// eatBanana() { +// console.log(this.name + " is eating banana") +// } +// hide() { +// console.log(`${this.name} is hiding`) +// } +// } + +// let ani = new Animal("Bruno", "white") +// let m = new Monkey("Chimpu", "orange") + +// ani.shout() +// m.eatBanana() +// m.hide() +// // ani.hide() //This will throw an error + +// Extend Keyword + +// Extend Keyword Is Used To Extend Another Class. + + +// Class Child extends Parent + +// Parent Classes Is The Class From Which Other Class Inherits. +// class Animal { +// constructor(name, color) { +// this.name = name +// this.color = color +// } +// run() { +// console.log(this.name + " is running") +// } +// shout() { +// console.log(this.name + " is shouting") +// } +// } +// // Child Class +// class Monkey extends Animal { +// eatBanana() { +// console.log(this.name + " is eating banana") +// } +// } + +// Method Overriding +// Method Overriding Is A Feature In OOP Language Where A Child Class Can Override A Parent Method. + +// class Employee { +// constructor(name) { +// console.log(`${name} - Employee's constructor is here`) +// this.name = name +// } +// login() { +// console.log(`Employee has logged in`); +// } + +// logout() { +// console.log(`Employee has logged out`); +// } + +// requestLeaves(leaves) { +// console.log(`Employee has requested ${leaves} leaves - Auto approved`) +// } +// } + +// class Programmer extends Employee { +// constructor(name) { +// super(name) +// console.log(`This is a newly written constructor`) +// } +// // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically +// // super(...args) +// // } +// requestCoffee(x) { +// console.log(`Employee has requested ${x} coffees`) +// } +// requestLeaves(leaves) { +// super.requestLeaves(4) +// console.log("One extra is granted") +// // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`) + +// } +// } + +// let e = new Programmer("Harry") +// e.login() +// e.requestLeaves(3) + +// If We Create Our Own Implimentstion Of Run Method In Child Class, It Will Be Overridden. + +// Super Kewword +// Super Keyword Is Used To Call The Parent Class Constructor. +// When We Override A Method In Child Class, We Use Super Keyword To Call The Parent Class Method. + +// super(a,b) -> Call Parent Class Constructor + + +// Overriding Constructor + +// With A Constructor, Things Are Bit Tricky/ Different. According To The Specifications , If A Class Extends Another Class And Has No Constructor. Than The Child Class Will Have A Constructor Automatically. -> By Default Its Generated By The JS Engine. + +// Default One +// constructor(...args){ ---> If there is no constructor in the child class, this is created automatically +// // super(...args) +// // } + +// Constructor In Inheriting Classes Mus Call Super (...) And Do It Before Using This. +// We Can Also Use super.method() In Child Class To Call Parent Class Method. + +// class Employee { +// constructor(name) { +// console.log(`${name} - Employee's constructor is here`) +// this.name = name +// } +// login() { +// console.log(`Employee has logged in`); +// } + +// logout() { +// console.log(`Employee has logged out`); +// } + +// requestLeaves(leaves) { +// console.log(`Employee has requested ${leaves} leaves - Auto approved`) +// } +// } + +// class Programmer extends Employee { +// constructor(name) { +// super(name) +// console.log(`This is a newly written constructor`) +// } +// // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically +// // super(...args) +// // } +// requestCoffee(x) { +// console.log(`Employee has requested ${x} coffees`) +// } +// requestLeaves(leaves) { +// super.requestLeaves(4) +// console.log("One extra is granted") +// // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`) + +// } +// } + +// let e = new Programmer("Harry") +// e.login() +// e.requestLeaves(3) + + +// Static Methods +// Static Methods Are Methods Which Are Associated With A Class And Not With Any Instance Of It. + +// Static Method Are Used To Implement Logic Which Does Not Rely On Instance. + +// Static Method Are Used To Implement Function That Belong To A Class As A Whole. And Not To Any Particular Object. + +// We Can Assign Single Static Method; + +// Syntax: + +// class follow { +// static method() { +// console.log("This is a static method") +// } +// } + +// follow.method() + +// Static Methods Aren't Available For Individual Object + +// class Animal { +// constructor(name) { +// this.name = Animal.capitalize(name) +// } +// walk() { +// alert("Animal " + this.name + " is walking") +// } +// static capitalize(name) { +// return name.charAt(0).toUpperCase() + name.substr(1, name.length) +// } +// } + +// j = new Animal("jack") +// j.walk() +// console.log(j.capitalize("thisa")) // --- > this doesnt work + +// Getters And Setters + +// Getters And Setters Are Special Methods Which Are Used To Get And Set The Values Of An Object's Properties. + +// class Person { +// constructor(name) { +// this.name = name +// } +// fly() { +// console.log("I am flying") +// } +// get name() { +// return this._name +// } +// set name(newName) { +// this._name = newName +// } +// } + +// class Animal { +// constructor(name) { +// this._name = name +// } +// fly() { +// console.log("Mai ud rha hu") +// } +// get name() { +// return this._name +// } + +// set name(newName) { +// this._name = newName +// } + +// } + +// class Rabbit extends Animal { +// eatCarrot() { +// console.log("Eating carrot") +// } +// } + +// let a = new Rabbit("Bruno") +// a.fly() +// console.log(a.name) +// a.name = "Jack" +// console.log(a.name) +// let c = 56 + +// console.log(a instanceof Animal) +// console.log(a instanceof Rabbit) +// console.log(c instanceof Animal) + + +// InstanceOf Operator +// InstanceOf Operator Is Used To Check If An Object Is An Instance Of A Class. +// Object It Belongs To Certain Class Or Not? +// It Return True If Obj Belongs To The Class Or Any Other Class Inherited From It. +// Syntax: + +// instanceof + +// Practice Set + +// Q1 Create A Class To Create A Complex Number. Create A Constructor To Set The Real And Imaginary Parts. + +// Q2 Write A Method To Add Two Complex Numbers In The Above Class. + +// Q3 Create A Class Student From A Class Human. Override A Method And See Changes. + +// Q4 See If Student Is An Instance Of Human Using InstanceOf Keyword. + +// Q5 Use Getters And Setters To Set And Get The Real And Imaginary Parts Of The Complex Number. + + +// class Complex { +// constructor(real, imaginary) { +// this.real = real +// this.imaginary = imaginary +// } +// add(num) { +// this.real = this.real + num.real +// this.imaginary = this.imaginary + num.imaginary + +// } + +// get real() { +// return this._real +// } + +// get imaginary() { +// return this._imaginary +// } + +// set imaginary(newImaginary) { +// this._imaginary = newImaginary +// } + +// set real(newReal) { +// this._real = newReal +// } +// } + +// let a = new Complex(2, 4) +// console.log(a.real, a.imaginary) +// a.real = 10 +// a.imaginary = 10 +// let b = new Complex(6, 2) +// a.add(b) +// console.log(`${a.real}+${a.imaginary}i`) + +// class Human { +// constructor(name, favfood) { +// this.name = name +// this.favfood = favfood +// } +// walk() { +// console.log(this.name + "Human is walking") +// } +// } + +// class Student extends Human { +// walk() { +// console.log(this.name + ": Student is walking") +// } +// } + +// let o = new Student("Harry", "Bhindi") +// o.walk() + +// console.log(o instanceof Human) \ No newline at end of file diff --git a/Ch 12 Advanced JavaScript.js b/Ch 12 Advanced JavaScript.js new file mode 100644 index 0000000..bc29d1c --- /dev/null +++ b/Ch 12 Advanced JavaScript.js @@ -0,0 +1,296 @@ +// IIFE -> Immediately Invoked Function Expression + +// IIFE Is A JavaScript Function That Runs As Soon As It Is Defined +// (function() { +// console.log("IIFE"); +// })(); + +// // It is used to avoid polluting the global namespace, execute an async-await, etc. + +// let a = () => { +// return new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve(456) +// }, 4000) +// }) +// } + +// (async () => { +// let b = await a() +// console.log(b) +// let c = await a() +// console.log(c) +// let d = await a() +// console.log(d) +// })() + + +// console.log(d) // Throws error + +// Destructuring And Spread Operator +// Destructuring Assignment Is Used To Unpack Values From An Array, Or Properties From An Object, Into Dedicated Variables, In JavaScript. + +// let arr = [3, 5, 8, 9, 12, 14] +// No need to do this: +// let a = arr[0] +// let b = arr[1] +// let [a, b, c, d, ...rest] = arr +// console.log(a, b, c, d, rest) +// let [a, , b, ...rest] = arr +// console.log(a, b, rest) +// let { a, b } = { a: 1, b: 5 } +// console.log(a, b) + +// [10, x,....rest] =[10, 20, 30, 40, 50, 60] +// x will be 20 rest will be [30, 40, 50, 60] + +// Spread Operator + +// Spread Syntax Allow An Iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) +// let arr1 = [3, 5, 8] +// let obj1 = { ...arr1 } +// console.log(obj1) + +// function sum(v1, v2, v3) { +// return v1 + v2 + v3 +// } + +// console.log(sum(...arr1)) + +// let obj2 = { +// name: "Harry", +// company: "Company xyz", +// address: "XYZ" +// } + +// console.log({ ...obj2, name: "John", company: "ABC" }) +// console.log({ name: "John", company: "ABC", ...obj2 }) // This will print the obj2 object without changing any values +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax + +// Local, Global And Function Scope In JavaScript +// var -> Global Scope +// let and const -> Block Scope +// Function Scope -> The variable declared inside a function, becomes local to the function. + +// let p = 9 +// function ax() { +// let a = 8; +// console.log(p) +// console.log(a) +// } + +// ax() +// console.log(p) +// console.log(a) + + +// Hoisting In JavaScript +// Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution + +// let a; +// Following two lines will run successfully due to JavaScript hoisting +// console.log(a) +// greet() +// var greet = function() { +// console.log("Good morning") +// } + +// var a = 9; // Declaration hoisted to the top but initialization is not +// console.log(a) + +// Hoisting With Let And Var +// let and const are not hoisted +// console.log(num); +// let num = 6; -> Throws an error +// var num = 6; -> Doesn't throw an error +// const num = 6; -> Throws an error + +// Function Expression And Class Expression Are Not Hoisted +// Function Expression Me = Sign Ata He + +// Closer Set + +// A Closer Is A Function With Lexical Environment + +// function init() { +// var name = 'Mozilla'; // name is a local variable created by init +// function displayName() { +// // displayName() is the inner function, a closure +// console.log(name); // use variable declared in the parent function +// } +// name = "Harry" +// return displayName; +// } +// let c = init(); +// c() + + +// function returnFunc() { +// const x = () => { +// let a = 1 +// console.log(a) +// const y = () => { +// // let a = 2 +// console.log(a) +// const z = () => { +// // let a = 3 +// console.log(a) +// } +// z() +// } +// a = 999 +// y() +// } +// return x +// } + +// let a = returnFunc() +// a() + +// Closure -> Function + Its Lexical Environment +// Reference Milta He + +// Lexical Environment -> The Environment Of The Function -> Mere Pass Nahi He To Mere Pass Ka Environment Me Ase Check Karega + +// Arrow Function + +// const sayHello = name => { +// console.log("greeting" + " " + name) +// console.log("hi") +// } + +// const x = { +// name: "Harry", +// role: "Js Developer", +// exp: 30, +// show: function() { +// // let that = this +// // console.log(this) +// setTimeout(() => { +// // console.log(`The name is ${that.name}\nThe role is ${that.role}`) +// console.log(`The name is ${this.name}\nThe role is ${this.role}`) +// }, 2000) +// } +// } +// sayHello("Harry", "Good Afternoon") +// console.log(x.name, x.exp) +// x.show() + +// Arrow Function Uses Lexical This + +// Practice Set + +// const a = async (text, n = 2) => { +// return new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve(text) +// }, 1000 * n) +// }) +// } + +// ( +// async () => { +// let text = await a("Hello") +// console.log(text) +// text = await a("World") +// console.log(text) +// } +// )() + +// function sum(a, b, c) { +// return a + b + c +// } + +// let x = [1, 3, 5] +// console.log(sum(...x)); + +// (async () => { +// let text = await a("I am resolving after 1 second", 1) +// console.log(text) +// text = await a("I am resolving after 4 seconds", 4) +// console.log(text) +// } +// )() + +// function simpleInterest(p, r, t) { +// return (p * r * t) / 100; +// } + +// console.log(simpleInterest(100, 5, 1)) + +// Regex Expression Or Regular Expression +// https://regexr.com/ +// const regex = /(Harry){2}/gi +// const text = "Harryharry is a very very nice awesome nice very boy" +// console.log(text.replace(regex, "VERY")) + +// Event Loop + +// Asynchronous CallBack +// Sometimes the JavaScript code can take a lot of time and this can block the +// page re render +// JavaScript has asynchronous callbacks for non blocking behavior +// JavaScript runtime can do only one thing at a time +// Browser gives us other things which work along with the runtime like Web +// APIs. +// In node.js these are available as C++ APIs + +// setTimeout(function timer() { +// console.log('You clicked the button!'); +// }, 2000); + +// console.log("Hi!"); + +// setTimeout(function timeout() { +// console.log("Click the button!"); +// }, 5000); + +// console.log("Welcome to loupe."); + +// Task Queue +// JavaScript can do only one thing at a time +// The rest are queued to the task queue waiting to be executed +// When we run setTimeout, webapis will run a timer and push the function +// provided to setTimeout to the task queue once the timer evis +// These tasks will be pushed to the stack where they can executed + +// Event Loop + +// JavaScript has a runtime model based on an event loop, which is responsible +// for executing the code, collecting and processing events, and executing queued +// sub-tasks +// The event loop pushes the tasks from the task queue to the call stack +// setTimeout(func1, 0) can be used to defer a function until all the pending tasks +// (so far) have been executed +// We can see how these things work in action by visiting +// For Understanding Call Stack In Js :http://latentflip.com/loupe/ + +// Module In JS + + +// const hello = ()=>{ +// console.log("Hello Harry") +// } + +// const ahello = (name)=>{ +// console.log("Hello " + name) +// } + +// module.exports = {hello, ahello};// same as below line +// // module.exports = {hello: hello, ahello: ahello}; + +// // ES6 Modules +// export const hello = ()=>{ +// console.log("Hello Harry") +// } + +// export const ahello = (name)=>{ +// console.log("Hello " + name) +// } + +// const harry = ()=>{ +// console.log("Hello " + "Harry") +// } + +// export default harry; diff --git a/Ch 2 Expression & Conditional Statement Practice Set.js b/Ch 2 Expression & Conditional Statement Practice Set.js index f531b6d..f75d743 100644 --- a/Ch 2 Expression & Conditional Statement Practice Set.js +++ b/Ch 2 Expression & Conditional Statement Practice Set.js @@ -1,67 +1,67 @@ -// Ch 2 Expression & Conditional Statement Practice Set - - -// Q1) Use Logical Operator To Find Whether The Age Of a Person Lies Between 10 & 20. - -let age = 15; - -if (age >= 10 && age <= 20) { - console.log("The age is between 10 and 20."); -} else { - console.log("The age is not between 10 and 20."); -} - - -// Q2) Demonstrate The Use Of Switch Statement In JS With an Example. - -let day = 3; -let dayName; - -switch (day) { - case 1: - dayName = "Monday"; - break; - case 2: - dayName = "Tuesday"; - break; - case 3: - dayName = "Wednesday"; - break; - case 4: - dayName = "Thursday"; - break; - case 5: - dayName = "Friday"; - break; - case 6: - dayName = "Saturday"; - break; - case 7: - dayName = "Sunday"; - break; - default: - dayName = "Invalid day"; -} - -console.log(dayName); - - -// Q3) Write JS Program To Find Whether the Number Is Divisible By 2 And 3. - -let number = 12; - -if (number % 2 === 0 && number % 3 === 0) { - console.log(number + " is divisible by both 2 and 3."); -} else { - console.log(number + " is not divisible by both 2 and 3."); -} - - -// Q4) Print "You Can Drive" Or "You Can't Drive" Based On Age Being Greater Than 18 Using Ternary Operator - -let age = 20; -let canDrive = age > 18 ? "You can drive." : "You can't drive."; - -console.log(canDrive); - - +// Ch 2 Expression & Conditional Statement Practice Set + + +// Q1) Use Logical Operator To Find Whether The Age Of a Person Lies Between 10 & 20. + +let age = 15; + +if (age >= 10 && age <= 20) { + console.log("The age is between 10 and 20."); +} else { + console.log("The age is not between 10 and 20."); +} + + +// Q2) Demonstrate The Use Of Switch Statement In JS With an Example. + +let day = 3; +let dayName; + +switch (day) { + case 1: + dayName = "Monday"; + break; + case 2: + dayName = "Tuesday"; + break; + case 3: + dayName = "Wednesday"; + break; + case 4: + dayName = "Thursday"; + break; + case 5: + dayName = "Friday"; + break; + case 6: + dayName = "Saturday"; + break; + case 7: + dayName = "Sunday"; + break; + default: + dayName = "Invalid day"; +} + +console.log(dayName); + + +// Q3) Write JS Program To Find Whether the Number Is Divisible By 2 And 3. + +let number = 12; + +if (number % 2 === 0 && number % 3 === 0) { + console.log(number + " is divisible by both 2 and 3."); +} else { + console.log(number + " is not divisible by both 2 and 3."); +} + + +// Q4) Print "You Can Drive" Or "You Can't Drive" Based On Age Being Greater Than 18 Using Ternary Operator + +let age = 20; +let canDrive = age > 18 ? "You can drive." : "You can't drive."; + +console.log(canDrive); + + diff --git a/Ch 2 Expression & Conditional Statement.js b/Ch 2 Expression & Conditional Statement.js index 71e2014..e3d0ba4 100644 --- a/Ch 2 Expression & Conditional Statement.js +++ b/Ch 2 Expression & Conditional Statement.js @@ -1,247 +1,247 @@ -// Arithmetic Operators -// + Addition -// - Subtraction -// * Multiplication -// ** Exponential -// / Division -// % Modulus -// ++ Increment -// -- Decrement - -// -> Example -// Arithmetic Operators - -let addition = 5 + 2; // 7 -let subtraction = 8 - 3; // 5 -let multiplication = 4 * 3; // 12 -let exponentiation = 2 ** 4; // 16 -let division = 10 / 2; // 5 -let modulus = 9 % 2; // 1 -let increment = 5; -increment++; // 6 -let decrement = 10; -decrement--; // 9 - - -// Assignment Operators -// = X = Y -// += X = X + Y -// -= X = X - Y -// *= X = X * Y -// /= X = X / Y -// %= X = X % Y -// **= X = X ** Y - -// -> Example -// Assignment Operators -let x = 5; -x += 3; // equivalent to x = x + 3 -x -= 2; // equivalent to x = x - 2 -x *= 4; // equivalent to x = x * 4 -x /= 2; // equivalent to x = x / 2 -x %= 3; // equivalent to x = x % 3 -x **= 2; // equivalent to x = x ** 2 - - -// Comparison Operators -// == Equal To -// != Not Equal To -// === Equal Value And Type -// !== Not Equal Value Or Type -// > Greater Than -// < Less Than -// >= Greater Than Or Equal To -// <= Less Than Or Equal To -// ? Ternary Operator - -// -> Example -// Comparison Operators -let isEqual = (5 == 5); // true -let isNotEqual = (5 != 3); // true -let isEqualValueAndType = (5 === '5'); // false -let isNotEqualValueOrType = (5 !== '5'); // true -let isGreaterThan = (10 > 5); // true -let isLessThan = (3 < 7); // true -let isGreaterThanOrEqual = (8 >= 8); // true -let isLessThanOrEqual = (4 <= 2); // false - - -// Logical Operators -// && Logical And -// || Logical Or -// ! Logical Not - -// -> Example -// Logical Operators -let logicalAnd = (true && false); // false -let logicalOr = (true || false); // true -let logicalNot = !true; // false - - - -// Bitwise Operators -// Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding bits. The result is 1 if both bits are 1; otherwise, it is 0. - -// Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1; otherwise, it is 0. - -// Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits. The result is 1 if the bits are different; otherwise, it is 0. - -// Bitwise NOT (~): Flips the bits of a number. It converts each 0 to 1 and each 1 to 0. - -// Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions. This operation effectively multiplies the number by 2 to the power of the specified shift amount. - -// Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions. This operation effectively divides the number by 2 to the power of the specified shift amount. - -// Zero-fill Right Shift (>>>): Similar to the right shift operator (>>), but it always fills in the shifted positions with zeros. This is known as the zero-fill right shift. - -// Bitwise operators are commonly used in JavaScript for low-level manipulation of binary data, creating flags, and optimizing certain calculations. However, they are not frequently used in general-purpose programming and should be used judiciously due to their complexity and potential for confusion. - -// It's important to note that JavaScript treats numeric values as 32-bit signed integers when performing bitwise operations. To perform bitwise operations on larger numbers, consider using additional techniques or external libraries. - -// I hope these notes help you understand the basics of bitwise operators in JavaScript! - -// -> Example -// Bitwise Operators -let bitwiseAND = 5 & 3; // 1 -let bitwiseOR = 5 | 3; // 7 -let bitwiseXOR = 5 ^ 3; // 6 -let bitwiseNOT = ~5; // -6 -let leftShift = 5 << 2; // 20 -let rightShift = 5 >> 1; // 2 -let zeroFillRightShift = 5 >>> 1; // 2 - - -// Comments - -// Single Line Comment - -/* Multi Line Comment */ - - -// Conditional Statement -// 3 Types Of Conditional Statement Are Available -// If Statement -// If....Else Statement -// If....Else If....Else Statement - -// If Statement - -// if(condition){ -// //Execute This Code -// } -> Execute Till Condition True - -// -> Example -let x = 10; - -if (x > 5) { - console.log("x is greater than 5"); // This block will be executed since the condition is true -} - - - -// If....Else Statement - -// if(condition){ -// //Execute This Code If Condition Is True -// } -// else { -// //Execute This Code If Condition Is False -// } - -// -> Example - -let age = 18; - -if (age >= 18) { - console.log("You are eligible to vote."); // This block will be executed since the condition is true -} else { - console.log("You are not eligible to vote."); // This block will be executed if the condition is false -} - - - -// If....Else If Statement -// -> Sometime We Required To Check Condition Again And Again. - -// if (condition1) { -// // Code To Be Executed If Condition1 Is True -// } else if (condition2) { -// // Code To Be Executed If Condition2 Is True -// } else { -// // Code To Be Executed If All Conditions Are False -// } - -// -> Example - -let num = 5; - -if (num > 0) { - console.log("Number is positive."); -} else if (num < 0) { - console.log("Number is negative."); -} else { - console.log("Number is zero."); -} - - -// JavaScript Ternary Operator - -// The ternary operator, also known as the conditional operator, provides a concise way to write conditional expressions in JavaScript. - -// It is represented by the syntax: condition ? expression1 : expression2. -> True : False - -// The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed. - -// -> Usage and Benefits: - -// The ternary operator is often used as a shorthand alternative to if...else statements when there are simple conditions and expressions involved. - -// It makes the code more concise and readable, especially for shorter conditional statements. - -// It can be used to assign a value to a variable based on a condition without the need for a separate if statement. - -// Examples: - -// Assigning a value based on a condition: - - -let dp = 18; -let message = (dp >= 18) ? "You are an adult" : "You are not an adult"; - - - -// Returning a value from a function based on a condition: - -function checkEvenOrOdd(num) { - return (num % 2 === 0) ? "Even" : "Odd"; -} - - -// Nesting ternary operators (though it's recommended to keep it simple for readability): - -let nums = 10; -let result = (nums > 0) ? "Positive" : (nums < 0) ? "Negative" : "Zero"; - - -// While the ternary operator can make code more concise, it should be used judiciously to maintain code readability. Complex conditions or expressions may be better suited for if...else statements. - -// Avoid nesting too many ternary operators, as it can make the code harder to understand and maintain. - -// Use appropriate spacing and formatting to enhance the readability of ternary expressions. - -// Remember, a ternary operator is a powerful tool for writing conditional expressions in a concise manner. However, it's important to strike a balance between readability and simplicity when using it in your JavaScript code. - - -// Prefix Increment: - -let x = 5; -let result = ++x; // Increment x by 1 and assign the new value to result -console.log(result); // Output: 6 -console.log(x); // Output: 6 - -// Postfix Increment: - -let y = 5; -let result = y++; // Assign the current value of y to result, then increment y by 1 -console.log(result); // Output: 5 -console.log(y); // Output: 6 +// Arithmetic Operators +// + Addition +// - Subtraction +// * Multiplication +// ** Exponential +// / Division +// % Modulus +// ++ Increment +// -- Decrement + +// -> Example +// Arithmetic Operators + +let addition = 5 + 2; // 7 +let subtraction = 8 - 3; // 5 +let multiplication = 4 * 3; // 12 +let exponentiation = 2 ** 4; // 16 +let division = 10 / 2; // 5 +let modulus = 9 % 2; // 1 +let increment = 5; +increment++; // 6 +let decrement = 10; +decrement--; // 9 + + +// Assignment Operators +// = X = Y +// += X = X + Y +// -= X = X - Y +// *= X = X * Y +// /= X = X / Y +// %= X = X % Y +// **= X = X ** Y + +// -> Example +// Assignment Operators +let x = 5; +x += 3; // equivalent to x = x + 3 +x -= 2; // equivalent to x = x - 2 +x *= 4; // equivalent to x = x * 4 +x /= 2; // equivalent to x = x / 2 +x %= 3; // equivalent to x = x % 3 +x **= 2; // equivalent to x = x ** 2 + + +// Comparison Operators +// == Equal To +// != Not Equal To +// === Equal Value And Type +// !== Not Equal Value Or Type +// > Greater Than +// < Less Than +// >= Greater Than Or Equal To +// <= Less Than Or Equal To +// ? Ternary Operator + +// -> Example +// Comparison Operators +let isEqual = (5 == 5); // true +let isNotEqual = (5 != 3); // true +let isEqualValueAndType = (5 === '5'); // false +let isNotEqualValueOrType = (5 !== '5'); // true +let isGreaterThan = (10 > 5); // true +let isLessThan = (3 < 7); // true +let isGreaterThanOrEqual = (8 >= 8); // true +let isLessThanOrEqual = (4 <= 2); // false + + +// Logical Operators +// && Logical And +// || Logical Or +// ! Logical Not + +// -> Example +// Logical Operators +let logicalAnd = (true && false); // false +let logicalOr = (true || false); // true +let logicalNot = !true; // false + + + +// Bitwise Operators +// Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding bits. The result is 1 if both bits are 1; otherwise, it is 0. + +// Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1; otherwise, it is 0. + +// Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits. The result is 1 if the bits are different; otherwise, it is 0. + +// Bitwise NOT (~): Flips the bits of a number. It converts each 0 to 1 and each 1 to 0. + +// Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions. This operation effectively multiplies the number by 2 to the power of the specified shift amount. + +// Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions. This operation effectively divides the number by 2 to the power of the specified shift amount. + +// Zero-fill Right Shift (>>>): Similar to the right shift operator (>>), but it always fills in the shifted positions with zeros. This is known as the zero-fill right shift. + +// Bitwise operators are commonly used in JavaScript for low-level manipulation of binary data, creating flags, and optimizing certain calculations. However, they are not frequently used in general-purpose programming and should be used judiciously due to their complexity and potential for confusion. + +// It's important to note that JavaScript treats numeric values as 32-bit signed integers when performing bitwise operations. To perform bitwise operations on larger numbers, consider using additional techniques or external libraries. + +// I hope these notes help you understand the basics of bitwise operators in JavaScript! + +// -> Example +// Bitwise Operators +let bitwiseAND = 5 & 3; // 1 +let bitwiseOR = 5 | 3; // 7 +let bitwiseXOR = 5 ^ 3; // 6 +let bitwiseNOT = ~5; // -6 +let leftShift = 5 << 2; // 20 +let rightShift = 5 >> 1; // 2 +let zeroFillRightShift = 5 >>> 1; // 2 + + +// Comments + +// Single Line Comment + +/* Multi Line Comment */ + + +// Conditional Statement +// 3 Types Of Conditional Statement Are Available +// If Statement +// If....Else Statement +// If....Else If....Else Statement + +// If Statement + +// if(condition){ +// //Execute This Code +// } -> Execute Till Condition True + +// -> Example +let x = 10; + +if (x > 5) { + console.log("x is greater than 5"); // This block will be executed since the condition is true +} + + + +// If....Else Statement + +// if(condition){ +// //Execute This Code If Condition Is True +// } +// else { +// //Execute This Code If Condition Is False +// } + +// -> Example + +let age = 18; + +if (age >= 18) { + console.log("You are eligible to vote."); // This block will be executed since the condition is true +} else { + console.log("You are not eligible to vote."); // This block will be executed if the condition is false +} + + + +// If....Else If Statement +// -> Sometime We Required To Check Condition Again And Again. + +// if (condition1) { +// // Code To Be Executed If Condition1 Is True +// } else if (condition2) { +// // Code To Be Executed If Condition2 Is True +// } else { +// // Code To Be Executed If All Conditions Are False +// } + +// -> Example + +let num = 5; + +if (num > 0) { + console.log("Number is positive."); +} else if (num < 0) { + console.log("Number is negative."); +} else { + console.log("Number is zero."); +} + + +// JavaScript Ternary Operator + +// The ternary operator, also known as the conditional operator, provides a concise way to write conditional expressions in JavaScript. + +// It is represented by the syntax: condition ? expression1 : expression2. -> True : False + +// The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed. + +// -> Usage and Benefits: + +// The ternary operator is often used as a shorthand alternative to if...else statements when there are simple conditions and expressions involved. + +// It makes the code more concise and readable, especially for shorter conditional statements. + +// It can be used to assign a value to a variable based on a condition without the need for a separate if statement. + +// Examples: + +// Assigning a value based on a condition: + + +let dp = 18; +let message = (dp >= 18) ? "You are an adult" : "You are not an adult"; + + + +// Returning a value from a function based on a condition: + +function checkEvenOrOdd(num) { + return (num % 2 === 0) ? "Even" : "Odd"; +} + + +// Nesting ternary operators (though it's recommended to keep it simple for readability): + +let nums = 10; +let result = (nums > 0) ? "Positive" : (nums < 0) ? "Negative" : "Zero"; + + +// While the ternary operator can make code more concise, it should be used judiciously to maintain code readability. Complex conditions or expressions may be better suited for if...else statements. + +// Avoid nesting too many ternary operators, as it can make the code harder to understand and maintain. + +// Use appropriate spacing and formatting to enhance the readability of ternary expressions. + +// Remember, a ternary operator is a powerful tool for writing conditional expressions in a concise manner. However, it's important to strike a balance between readability and simplicity when using it in your JavaScript code. + + +// Prefix Increment: + +let x = 5; +let result = ++x; // Increment x by 1 and assign the new value to result +console.log(result); // Output: 6 +console.log(x); // Output: 6 + +// Postfix Increment: + +let y = 5; +let result = y++; // Assign the current value of y to result, then increment y by 1 +console.log(result); // Output: 5 +console.log(y); // Output: 6 diff --git a/Ch 3 Loops & Functions Practice Set.js b/Ch 3 Loops And Functions Practice Set.js similarity index 96% rename from Ch 3 Loops & Functions Practice Set.js rename to Ch 3 Loops And Functions Practice Set.js index e9ae2e0..a512f33 100644 --- a/Ch 3 Loops & Functions Practice Set.js +++ b/Ch 3 Loops And Functions Practice Set.js @@ -1,114 +1,114 @@ -// Q1) Write A Program To Print Marks Of Student In An Object Using For Loop -const marks = { - dp: 100, - ap: 99, - hp: 98 -}; - -for (let student in marks) { - console.log(`${student}: ${marks[student]}`); -} - -// Output -// dp: 100 -// ap: 99 -// hp: 98 - -// Q2) Write A Program In Q1 Using Using For In Loop -const marks = { - dp: 100, - ap: 99, - hp: 98 -}; - -for (let student in marks) { - console.log(`${student}: ${marks[student]}`); -} - -// Output -// dp: 100 -// ap: 99 -// hp: 98 - - -// Q3) Write A Program To Print "Try Again" Until The User Enter The Correct Number - -let correctNumber = 7; -let userNumber; - -do { - userNumber = parseInt(prompt('Enter a number:')); - if (userNumber !== correctNumber) { - console.log('Try again'); - } -} while (userNumber !== correctNumber); - -// This program will keep prompting the user to enter a number until they enter the correct number (in this case, 7). - -// Q4) Write A Function To Find the Mean Of 5 Numbers - -function findMean(num1, num2, num3, num4, num5) { - const sum = num1 + num2 + num3 + num4 + num5; - const mean = sum / 5; - return mean; -} - -const result = findMean(10, 20, 30, 40, 50); -console.log('Mean:', result); - -// Output - -// Mean: 30 - -// Q5)Write a function named multiplyByTwo that takes a number as an argument and returns the result of multiplying that number by 2. - -function multiplyByTwo(num) { - return num * 2; -} - -// Q6)Write a function named reverseString that takes a string as an argument and returns the reverse of that string. - -function reverseString(str) { - return str.split('').reverse().join(''); -} - -// Q7)Write a function named printEvenNumbers that takes a number as an argument and prints all the even numbers from 0 to that number. - -function printEvenNumbers(num) { - for (let i = 0; i <= num; i++) { - if (i % 2 === 0) { - console.log(i); - } - } -} - -// Q8) Write a function named calculateFactorial that takes a number as an argument and returns the factorial of that number. - -function calculateFactorial(num) { - if (num === 0 || num === 1) { - return 1; - } - - let factorial = 1; - for (let i = 2; i <= num; i++) { - factorial *= i; - } - - return factorial; -} - -// Q9) Write a function named countOccurrences that takes an array of numbers and a target number as arguments and returns the number of times the target number appears in the array. - -function countOccurrences(arr, target) { - let count = 0; - for (let num of arr) { - if (num === target) { - count++; - } - } - return count; -} - -// Q10) What is an arrow function in JavaScript? - +// Q1) Write A Program To Print Marks Of Student In An Object Using For Loop +const marks = { + dp: 100, + ap: 99, + hp: 98 +}; + +for (let student in marks) { + console.log(`${student}: ${marks[student]}`); +} + +// Output +// dp: 100 +// ap: 99 +// hp: 98 + +// Q2) Write A Program In Q1 Using Using For In Loop +const marks = { + dp: 100, + ap: 99, + hp: 98 +}; + +for (let student in marks) { + console.log(`${student}: ${marks[student]}`); +} + +// Output +// dp: 100 +// ap: 99 +// hp: 98 + + +// Q3) Write A Program To Print "Try Again" Until The User Enter The Correct Number + +let correctNumber = 7; +let userNumber; + +do { + userNumber = parseInt(prompt('Enter a number:')); + if (userNumber !== correctNumber) { + console.log('Try again'); + } +} while (userNumber !== correctNumber); + +// This program will keep prompting the user to enter a number until they enter the correct number (in this case, 7). + +// Q4) Write A Function To Find the Mean Of 5 Numbers + +function findMean(num1, num2, num3, num4, num5) { + const sum = num1 + num2 + num3 + num4 + num5; + const mean = sum / 5; + return mean; +} + +const result = findMean(10, 20, 30, 40, 50); +console.log('Mean:', result); + +// Output + +// Mean: 30 + +// Q5)Write a function named multiplyByTwo that takes a number as an argument and returns the result of multiplying that number by 2. + +function multiplyByTwo(num) { + return num * 2; +} + +// Q6)Write a function named reverseString that takes a string as an argument and returns the reverse of that string. + +function reverseString(str) { + return str.split('').reverse().join(''); +} + +// Q7)Write a function named printEvenNumbers that takes a number as an argument and prints all the even numbers from 0 to that number. + +function printEvenNumbers(num) { + for (let i = 0; i <= num; i++) { + if (i % 2 === 0) { + console.log(i); + } + } +} + +// Q8) Write a function named calculateFactorial that takes a number as an argument and returns the factorial of that number. + +function calculateFactorial(num) { + if (num === 0 || num === 1) { + return 1; + } + + let factorial = 1; + for (let i = 2; i <= num; i++) { + factorial *= i; + } + + return factorial; +} + +// Q9) Write a function named countOccurrences that takes an array of numbers and a target number as arguments and returns the number of times the target number appears in the array. + +function countOccurrences(arr, target) { + let count = 0; + for (let num of arr) { + if (num === target) { + count++; + } + } + return count; +} + +// Q10) What is an arrow function in JavaScript? + // An arrow function is a shorter syntax for writing function expressions. It uses the => arrow token and does not bind its own this value. It is often used for writing concise and inline functions. \ No newline at end of file diff --git a/Ch 3 Loops & Functions.js b/Ch 3 Loops And Functions.js similarity index 96% rename from Ch 3 Loops & Functions.js rename to Ch 3 Loops And Functions.js index 55bd2f0..f95c583 100644 --- a/Ch 3 Loops & Functions.js +++ b/Ch 3 Loops And Functions.js @@ -1,167 +1,167 @@ -// Loops & Functions -// Loops and functions are essential concepts in JavaScript programming that help to create efficient and reusable code. - - -// Types Of Loops -//For Loop -> Loop a Block Of Code No Of Time -//For In Loop -> Loop Through The Key Of An Object -//For Of Loop -> Loop Through The Value Of An Object -//While Loop -> Loop Of Block Based On Specific Condition -// Do...While Loop -> While Loop Variant Which Run a At Least Once - - -// For Loop -// Syntax -// for(Statement1;Statement2;Statement3){ -// // Code To Be Executed -// } -// Statement1 -> Executed One Time -// Statement2 -> Condition Based -> Based On This Loop Body Will Be Executed -// Statement3 -> Executed Every Time The Loop Body Is Executed - - -// Example -for (let i = 0; i < 5; i++) { - console.log(i); // prints numbers from 0 to 4 -} - - -// For In Loop -//Loop Through The Key Of An Object -// For In Loop Works With Array Also - -// Example -const person = { - name: 'John', - age: 30, - occupation: 'Developer' - // key:'value' -}; - -for (let key in person) { //(let a in person) -> console.log(a); - console.log(key); // prints "name", "age", "occupation" - console.log(person[key]); // prints the corresponding values "John", 30, "Developer" -} - - -// For Of Loop -// Loop Through The Value Of An Object -// Object Must Be Iterable - -// Example -const fruits = ['apple', 'banana', 'orange']; - -for (let fruit of fruits) { - console.log(fruit); // prints "apple", "banana", "orange" -} - -const message = 'Hello'; - -for (let char of message) { - console.log(char); // prints "H", "e", "l", "l", "o" -} - - -// While Loop -// If Condition Never False -> Loop Will Never End -> Crush JS Run Time -// Also Called In Infinite Loop -> Don't Try This Circus - -// Syntax -// while(condition){ -// // Code To Be Executed -// } - -// Example -let i = 0; -while (i < 5) { - console.log(i); // prints numbers from 0 to 4 - i++; -} - - -// ALT + SHIFT + DOWN ARROW KEY -> Replicate Selected Code - - -// Do.....While Loop -// Do...While Loop -> While Loop Variant Which Run a At Least Once -// Syntax - -// do { -// // Code To Be Executed -// } while(Condition) - -// Example -let i = 0; -do { - console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once - i++; -} while (i < 5); - -let i = 6; -do { - console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once - i++; -} while (i < 5); - -// Output -> 6 - - -// Functions -// Functions are reusable blocks of code that perform a specific task. They help in organizing code, improving reusability, and reducing redundancy. A function can accept parameters (inputs) and return a value. - - // function myfun(parameter1, parameter2){ - // //Code -> Parameter Behave As Local Variables - // } - -// myfun(6,7); -> Function Invocation -// A. Function declaration: -// B function declaration defines a named function that can be called later in the code. - -// Example -function greet(name) { - console.log(`Hello, ${name}!`); -} - -greet("John"); // prints "Hello, John!" -greet("Sarah"); // prints "Hello, Sarah!" - -// Function expression: -// A function expression assigns a function to a variable. It can be anonymous or named. - -const greet = function (name) { - console.log(`Hello, ${name}!`); -}; - -greet("John"); // prints "Hello, John!" -greet("Sarah"); // prints "Hello, Sarah!" - -// Arrow function: -// Arrow functions provide a concise syntax for writing functions. They are anonymous and lexically bind the this value. - -const greet = (name) => { - console.log(`Hello, ${name}!`); -}; - -greet("John"); // prints "Hello, John!" -greet("Sarah"); // prints "Hello, Sarah!" - -// Returning a value: -// Functions can return a value using the return statement. The returned value can be stored in a variable or used directly. - -function add(a, b) { - return a + b; -} - -const result = add(3, 4); -console.log(result); // prints 7 - -// Default parameters: -// Default parameters allow you to assign default values to function parameters if no argument is passed. - - -function multiply(a, b = 1) { - return a * b; -} - -console.log(multiply(5)); // prints 5 -console.log(multiply(5, 2)); // prints 10 +// Loops & Functions +// Loops and functions are essential concepts in JavaScript programming that help to create efficient and reusable code. + + +// Types Of Loops +//For Loop -> Loop a Block Of Code No Of Time +//For In Loop -> Loop Through The Key Of An Object +//For Of Loop -> Loop Through The Value Of An Object +//While Loop -> Loop Of Block Based On Specific Condition +// Do...While Loop -> While Loop Variant Which Run a At Least Once + + +// For Loop +// Syntax +// for(Statement1;Statement2;Statement3){ +// // Code To Be Executed +// } +// Statement1 -> Executed One Time +// Statement2 -> Condition Based -> Based On This Loop Body Will Be Executed +// Statement3 -> Executed Every Time The Loop Body Is Executed + + +// Example +for (let i = 0; i < 5; i++) { + console.log(i); // prints numbers from 0 to 4 +} + + +// For In Loop +//Loop Through The Key Of An Object +// For In Loop Works With Array Also + +// Example +const person = { + name: 'John', + age: 30, + occupation: 'Developer' + // key:'value' +}; + +for (let key in person) { //(let a in person) -> console.log(a); + console.log(key); // prints "name", "age", "occupation" + console.log(person[key]); // prints the corresponding values "John", 30, "Developer" +} + + +// For Of Loop +// Loop Through The Value Of An Object +// Object Must Be Iterable + +// Example +const fruits = ['apple', 'banana', 'orange']; + +for (let fruit of fruits) { + console.log(fruit); // prints "apple", "banana", "orange" +} + +const message = 'Hello'; + +for (let char of message) { + console.log(char); // prints "H", "e", "l", "l", "o" +} + + +// While Loop +// If Condition Never False -> Loop Will Never End -> Crush JS Run Time +// Also Called In Infinite Loop -> Don't Try This Circus + +// Syntax +// while(condition){ +// // Code To Be Executed +// } + +// Example +let i = 0; +while (i < 5) { + console.log(i); // prints numbers from 0 to 4 + i++; +} + + +// ALT + SHIFT + DOWN ARROW KEY -> Replicate Selected Code + + +// Do.....While Loop +// Do...While Loop -> While Loop Variant Which Run a At Least Once +// Syntax + +// do { +// // Code To Be Executed +// } while(Condition) + +// Example +let i = 0; +do { + console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once + i++; +} while (i < 5); + +let i = 6; +do { + console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once + i++; +} while (i < 5); + +// Output -> 6 + + +// Functions +// Functions are reusable blocks of code that perform a specific task. They help in organizing code, improving reusability, and reducing redundancy. A function can accept parameters (inputs) and return a value. + + // function myfun(parameter1, parameter2){ + // //Code -> Parameter Behave As Local Variables + // } + +// myfun(6,7); -> Function Invocation +// A. Function declaration: +// B function declaration defines a named function that can be called later in the code. + +// Example +function greet(name) { + console.log(`Hello, ${name}!`); +} + +greet("John"); // prints "Hello, John!" +greet("Sarah"); // prints "Hello, Sarah!" + +// Function expression: +// A function expression assigns a function to a variable. It can be anonymous or named. + +const greet = function (name) { + console.log(`Hello, ${name}!`); +}; + +greet("John"); // prints "Hello, John!" +greet("Sarah"); // prints "Hello, Sarah!" + +// Arrow function: +// Arrow functions provide a concise syntax for writing functions. They are anonymous and lexically bind the this value. + +const greet = (name) => { + console.log(`Hello, ${name}!`); +}; + +greet("John"); // prints "Hello, John!" +greet("Sarah"); // prints "Hello, Sarah!" + +// Returning a value: +// Functions can return a value using the return statement. The returned value can be stored in a variable or used directly. + +function add(a, b) { + return a + b; +} + +const result = add(3, 4); +console.log(result); // prints 7 + +// Default parameters: +// Default parameters allow you to assign default values to function parameters if no argument is passed. + + +function multiply(a, b = 1) { + return a * b; +} + +console.log(multiply(5)); // prints 5 +console.log(multiply(5, 2)); // prints 10 diff --git a/Ch 4 String Practice Set.js b/Ch 4 String Practice Set.js index 2d52083..2fbcd6c 100644 --- a/Ch 4 String Practice Set.js +++ b/Ch 4 String Practice Set.js @@ -1,93 +1,93 @@ -// Ch 4 String Practice Set - -// Q1)Write a program that counts the number of characters in a given string. - - - -// const str = "Hello, World!"; -// const count = str.length; -// console.log(count); // Output: 13 - - -// Q2)Write a program that checks if a string contains a specific substring. - - - -// const str = "Hello, World!"; -// const substring = "World"; -// const containsSubstring = str.includes(substring); -// console.log(containsSubstring); // Output: true - - - -// Q3)Write a program that converts a string to uppercase. - - - -// const str = "Hello, World!"; -// const uppercaseStr = str.toUpperCase(); -// console.log(uppercaseStr); // Output: HELLO, WORLD! - - - -// Q4)Write a program that extracts a portion of a string based on start and end indexes. - - - -// const str = "Hello, World!"; -// const extractedStr = str.slice(7, 12); -// console.log(extractedStr); // Output: World - - -// Q5)Write a program that replaces a specific substring with another substring. - - - -// const str = "Hello, John!"; -// const newStr = str.replace("John", "Alice"); -// console.log(newStr); // Output: Hello, Alice! - - - -// Q6)Write a program that splits a string into an array of substrings based on a delimiter. - - - -// const str = "Hello, World!"; -// const arr = str.split(","); -// console.log(arr); // Output: ["Hello", " World!"] - -// Q7)Write a program that checks if a string starts with a specific character or substring. - - - -// const str = "Hello, World!"; -// const startsWithHello = str.startsWith("Hello"); -// console.log(startsWithHello); // Output: true - - -// Q8)Write a program that checks if a string ends with a specific character or substring. - - - -// const str = "Hello, World!"; -// const endsWithWorld = str.endsWith("World!"); -// console.log(endsWithWorld); // Output: true - - -// Q9)Write a program that trims whitespace from the beginning and end of a string. - - - -// const str = " Hello, World! "; -// const trimmedStr = str.trim(); -// console.log(trimmedStr); // Output: Hello, World! - - -// Q10)Write a program that checks if a string is empty. - - - -// const str = ""; -// const isEmpty = str.length === 0; +// Ch 4 String Practice Set + +// Q1)Write a program that counts the number of characters in a given string. + + + +// const str = "Hello, World!"; +// const count = str.length; +// console.log(count); // Output: 13 + + +// Q2)Write a program that checks if a string contains a specific substring. + + + +// const str = "Hello, World!"; +// const substring = "World"; +// const containsSubstring = str.includes(substring); +// console.log(containsSubstring); // Output: true + + + +// Q3)Write a program that converts a string to uppercase. + + + +// const str = "Hello, World!"; +// const uppercaseStr = str.toUpperCase(); +// console.log(uppercaseStr); // Output: HELLO, WORLD! + + + +// Q4)Write a program that extracts a portion of a string based on start and end indexes. + + + +// const str = "Hello, World!"; +// const extractedStr = str.slice(7, 12); +// console.log(extractedStr); // Output: World + + +// Q5)Write a program that replaces a specific substring with another substring. + + + +// const str = "Hello, John!"; +// const newStr = str.replace("John", "Alice"); +// console.log(newStr); // Output: Hello, Alice! + + + +// Q6)Write a program that splits a string into an array of substrings based on a delimiter. + + + +// const str = "Hello, World!"; +// const arr = str.split(","); +// console.log(arr); // Output: ["Hello", " World!"] + +// Q7)Write a program that checks if a string starts with a specific character or substring. + + + +// const str = "Hello, World!"; +// const startsWithHello = str.startsWith("Hello"); +// console.log(startsWithHello); // Output: true + + +// Q8)Write a program that checks if a string ends with a specific character or substring. + + + +// const str = "Hello, World!"; +// const endsWithWorld = str.endsWith("World!"); +// console.log(endsWithWorld); // Output: true + + +// Q9)Write a program that trims whitespace from the beginning and end of a string. + + + +// const str = " Hello, World! "; +// const trimmedStr = str.trim(); +// console.log(trimmedStr); // Output: Hello, World! + + +// Q10)Write a program that checks if a string is empty. + + + +// const str = ""; +// const isEmpty = str.length === 0; // console.log(isEmpty); // Output: true \ No newline at end of file diff --git a/Ch 4 String.js b/Ch 4 String.js index 44bb25c..225a313 100644 --- a/Ch 4 String.js +++ b/Ch 4 String.js @@ -1,215 +1,183 @@ -// String - -// A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are immutable, meaning that once created, they cannot be changed. However, string methods can be used to manipulate and extract information from strings. - -// String are Used To Store And Manipulate Text - -// String -> Collection Of Characters - -// Single Quotes -> let name = 'dp'; -// Double Quotes -> let name = "dp"; - -let name = "dp"; -// console.log(name[3]); -> undefined - - -// Template Literals - -// After ES6 -> Template Literals Came In Use -> Use Back Tic - -let boy1 = "hmm" -let boy2 = 'ok' - -// Print Hmm nice ok -// let sentence = `boy1 "nice" 'is' boy2` -> We a Make String -> Use Single Or Double Quotes Both Usage Possible If String Made Through Back Tic - -// String Interpolation -let sentence = `${boy1} nice ${boy2}` -console.log(sentence) -// hmm nice ok - -let fruit = `Bana\'na` -> Bana'na -console.log(fruit) - -// \' -> Escape Character -> Count As One Character -// \n -> New Line -// \t -> Tab -// \r -> Carrige Return - - -// String Method & Properties -// Accessing Characters: -// Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0. - -// const message = 'Hello'; -// console.log(message[0]); // Output: H -// console.log(message[3]); // Output: l - -// String Concatenation: -// Strings can be concatenated using the + operator or the concat() method. - - -// const firstName = 'John'; -// const lastName = 'Doe'; -// const fullName = firstName + ' ' + lastName; -// console.log(fullName); // Output: John Doe - -// // Using concat() -// const message = 'Hello, '; -// const name = 'John'; -// const greeting = message.concat(name); -// console.log(greeting); // Output: Hello, John - -// Finding Substrings: -// The indexOf() method returns the index of the first occurrence of a substring within a string. It returns -1 if the substring is not found. - -// const message = 'Hello, world!'; -// console.log(message.indexOf('world')); // Output: 7 -// console.log(message.indexOf('open')); // Output: -1 - - -// Extracting Substrings: -// The slice() method extracts a portion of a string based on the start and end indexes. - -// const message = 'Hello, world!'; -// console.log(message.slice(0, 5)); // Output: Hello -// console.log(message.slice(7)); // Output: world! - -// Replacing Substrings: -// The replace() method replaces a specified substring with another substring. - -// const message = 'Hello, John!'; -// console.log(message.replace('John', 'Alice')); // Output: Hello, Alice! - -// Splitting Strings: -// The split() method splits a string into an array of substrings based on a specified delimiter. - -// const message = 'Hello, World!'; -// console.log(message.split(' ')); // Output: ["Hello,", "World!"] - - -// Checking if a String Contains a Substring: -// The includes() method checks if a string contains a specified substring and returns true or false. - -// const message = 'Hello, World!'; -// console.log(message.includes('World')); // Output: true -// console.log(message.includes('open')); // Output: false - -// String Length: -// The length property returns the number of characters in a string. - -// const message = 'Hello, world!'; -// console.log(message.length); // Output: 13 - -// String Slice: -// The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string. - -// const message = 'Hello, world!'; -// console.log(message.slice(7)); // Output: world! -// console.log(message.slice(0, 5)); // Output: Hello - - -// String Substring: -// The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string. - - -// const message = 'Hello, world!'; -// console.log(message.substring(7)); // Output: world! -// console.log(message.substring(0, 5)); // Output: Hello - - -// String Substr: -// The substr() method extracts a portion of a string based on the start index and length. It returns a new string. - - -// const message = 'Hello, world!'; -// console.log(message.substr(7)); // Output: world! -// console.log(message.substr(0, 5)); // Output: Hello - -// String Replace: - -// The replace() method replaces a specified substring with another substring. It returns a new string. - -// const message = 'Hello, John!'; -// console.log(message.replace('John', 'Alice')); // Output: Hello, Alice! - -// String ReplaceAll: -// The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021) - - -// const message = 'Hello, John! John is a good guy.'; -// console.log(message.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy. - -// String toUpperCase and toLowerCase: -// The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string. - - -// const message = 'Hello, world!'; -// console.log(message.toUpperCase()); // Output: HELLO, WORLD! -// console.log(message.toLowerCase()); // Output: hello, world! - - -// String Concatenation: -// The concat() method concatenates two or more strings and returns a new string. - - -// const firstName = 'John'; -// const lastName = 'Doe'; -// console.log(firstName.concat(' ', lastName)); // Output: John Doe - - -// String Trim: -// The trim() method removes whitespace from both ends of a string and returns a new string. - -// const message = ' Hello, world! '; -// console.log(message.trim()); // Output: Hello, world! - - -// String TrimStart and TrimEnd: -// The trimStart() and trimEnd() methods remove whitespace from the beginning and end of a string, respectively. They return a new string. (Available from ECMAScript 2021) - -// const message = ' Hello, world! '; -// console.log(message.trimStart()); // Output: Hello, world! -// console.log(message.trimEnd()); // Output: Hello, world! - -// String PadStart and PadEnd: -// The padStart() and padEnd() methods pad a string with a specified character to a given length. They return a new string. (Available from ECMAScript 2017) - -// const message = 'Hello'; -// console.log(message.padStart(10, '*')); // Output: *****Hello -// console.log(message.padEnd(10, '-')); // Output: Hello----- - - -// String CharAt and CharCodeAt: -// The charAt() method returns the character at a specified index in a string. -// The charCodeAt() method returns the Unicode value of the character at a specified index in a string. - -// const message = 'Hello'; -// console.log(message.charAt(0)); // Output: H -// console.log(message.charCodeAt(0)); // Output: 72 - - -// String Split: -// The split() method splits a string into an array of substrings based on a specified delimiter. - -// const message = 'Hello, World!'; -// console.log(message.split(',')); // Output: ["Hello", " World!"] - -// Method -// String length -// String slice() -// String substring() -// String substr() -// String replace() -// String replaceAll() -// String toUpperCase() -// String toLowerCase() -// String concat() -// String trim() -// String trimStart() -// String trimEnd() -// String padStart() -// String padEnd() -// String charAt() -// String charCodeAt() -// String split() \ No newline at end of file +// Strings + +// A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are immutable, meaning that once created, they cannot be changed. However, string methods can be used to manipulate and extract information from strings. + +// Strings are used to store and manipulate text + +// String -> Collection of characters + +// Single Quotes -> let name = 'dp'; +// Double Quotes -> let name = "dp"; + +let name = "dp"; +// console.log(name[3]); -> undefined + +// Template Literals + +// After ES6, Template Literals came into use, utilizing backticks (`). + +let boy1 = "hmm"; +let boy2 = 'ok'; + +// Print "hmm nice ok" +// let sentence = `boy1 "nice" 'is' boy2` -> We make a string using single or double quotes, both usage possible if string is made through backticks + +// String Interpolation +let sentence = `${boy1} nice ${boy2}`; +console.log(sentence); // Output: hmm nice ok + +let fruit = `Bana\'na`; // Bana'na +console.log(fruit); + +// \' -> Escape character -> Count as one character +// \n -> New line +// \t -> Tab +// \r -> Carriage return + +// String Methods & Properties + +// Accessing Characters: +// Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0. + +const message = 'Hello'; +console.log(message[0]); // Output: H +console.log(message[3]); // Output: l + +// String Concatenation: +// Strings can be concatenated using the + operator or the concat() method. + +const firstName = 'John'; +const lastName = 'Doe'; +const fullName = firstName + ' ' + lastName; +console.log(fullName); // Output: John Doe + +// Using concat() +const greetingMessage = 'Hello, '; +const nameConcat = 'John'; +const greeting = greetingMessage.concat(nameConcat); +console.log(greeting); // Output: Hello, John + +// Finding Substrings: +// The indexOf() method returns the index of the first occurrence of a substring within a string. It returns -1 if the substring is not found. + +const welcomeMessage = 'Hello, world!'; +console.log(welcomeMessage.indexOf('world')); // Output: 7 +console.log(welcomeMessage.indexOf('open')); // Output: -1 + +// Extracting Substrings: +// The slice() method extracts a portion of a string based on the start and end indexes. + +console.log(welcomeMessage.slice(0, 5)); // Output: Hello +console.log(welcomeMessage.slice(7)); // Output: world! + +// Replacing Substrings: +// The replace() method replaces a specified substring with another substring. + +const personalizedMessage = 'Hello, John!'; +console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice! + +// Splitting Strings: +// The split() method splits a string into an array of substrings based on a specified delimiter. + +console.log(welcomeMessage.split(' ')); // Output: ["Hello,", "world!"] + +// Checking if a String Contains a Substring: +// The includes() method checks if a string contains a specified substring and returns true or false. + +console.log(welcomeMessage.includes('World')); // Output: true +console.log(welcomeMessage.includes('open')); // Output: false + +// String Length: +// The length property returns the number of characters in a string. + +console.log(welcomeMessage.length); // Output: 13 + +// String Slice: +// The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string. + +console.log(welcomeMessage.slice(7)); // Output: world! +console.log(welcomeMessage.slice(0, 5)); // Output: Hello + +// String Substring: +// The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string. + +console.log(welcomeMessage.substring(7)); // Output: world! +console.log(welcomeMessage.substring(0, 5)); // Output: Hello + +// String Substr: +// The substr() method extracts a portion of a string based on the start index and length. It returns a new string. + +console.log(welcomeMessage.substr(7)); // Output: world! +console.log(welcomeMessage.substr(0, 5)); // Output: Hello + +// String Replace: +// The replace() method replaces a specified substring with another substring. It returns a new string. + +console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice! + +// String ReplaceAll: +// The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021) + +const repetitiveMessage = 'Hello, John! John is a good guy.'; +console.log(repetitiveMessage.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy. + +// String toUpperCase and toLowerCase: +// The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string. + +console.log(welcomeMessage.toUpperCase()); // Output: HELLO, WORLD! +console.log(welcomeMessage.toLowerCase()); // Output: hello, world! + +// String Concatenation: +// The concat() method concatenates two or more strings and returns a new string. + +console.log(firstName.concat(' ', lastName)); // Output: John Doe + +// String Trim: +// The trim() method removes whitespace from both ends of a string and returns a new string. + +const messageWithWhitespace = ' Hello, world! '; +console.log(messageWithWhitespace.trim()); // Output: Hello, world! + +// String TrimStart and TrimEnd: +// The trimStart() and trimEnd() methods remove whitespace from the beginning and end of a string, respectively. They return a new string. (Available from ECMAScript 2021) + +console.log(messageWithWhitespace.trimStart()); // Output: Hello, world! +console.log(messageWithWhitespace.trimEnd()); // Output: Hello, world! + +// String PadStart and PadEnd: +// The padStart() and padEnd() methods pad a string with a specified character to a given length. They return a new string. (Available from ECMAScript 2017) + +const paddedMessage = 'Hello'; +console.log(paddedMessage.padStart(10, '*')); // Output: *****Hello +console.log(paddedMessage.padEnd(10, '-')); // Output: Hello----- + +// String CharAt and CharCodeAt: +// The charAt() method returns the character at a specified index in a string. +// The charCodeAt() method returns the Unicode value of the character at a specified index in a string. + +console.log(message.charAt(0)); // Output: H +console.log(message.charCodeAt(0)); // Output: 72 + +// String Split: +// The split() method splits a string into an array of substrings based on a specified delimiter. + +console.log(welcomeMessage.split(',')); // Output: ["Hello", " World!"] + + // Method summary: + // String length + // String slice() + // String substring() + // String substr() + // String replace() + // String replaceAll() + // String toUpperCase() + // String toLowerCase() + // String concat() + // String trim() + // String trimStart() + // String trimEnd() + // String padStart() + // String padEnd() + // String charAt() + // String charCodeAt() + // String split() \ No newline at end of file diff --git a/Ch 5 Array Practice Set.js b/Ch 5 Array Practice Set.js index a10238c..b99d883 100644 --- a/Ch 5 Array Practice Set.js +++ b/Ch 5 Array Practice Set.js @@ -1,96 +1,96 @@ -// Ch 5 Array Practice Set - - - -// Q1)How do you create an empty array in JavaScript? - -// Answer: - -// const emptyArray = []; - - -// Q2)How do you check if an array is empty in JavaScript? - -// Answer: - -// const array = []; - -// if (array.length === 0) { -// console.log("The array is empty"); -// } else { -// console.log("The array is not empty"); -// } - - -// Q3)How do you add elements to the end of an array in JavaScript? - -// Answer: - -// const array = [1, 2, 3]; -// array.push(4, 5); -// console.log(array); // Output: [1, 2, 3, 4, 5] - - -// Q4)How do you access an element at a specific index in an array? - -// Answer: - -// const array = [1, 2, 3]; -// const element = array[1]; -// console.log(element); // Output: 2 - - -// Q5)How do you remove the last element from an array in JavaScript? - -// Answer: - -// const array = [1, 2, 3]; -// const removedElement = array.pop(); -// console.log(array); // Output: [1, 2] -// console.log(removedElement); // Output: 3 - - -// Q6)How do you find the index of a specific element in an array? - -// Answer: - -// const array = [1, 2, 3, 4, 5]; -// const index = array.indexOf(3); -// console.log(index); // Output: 2 - - -// Q7)How do you concatenate two arrays in JavaScript? - -// Answer: - -// const array1 = [1, 2, 3]; -// const array2 = [4, 5, 6]; -// const concatenatedArray = array1.concat(array2); -// console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6] - - -// Q8)How do you check if an element exists in an array? - -// Answer: - -// const array = [1, 2, 3, 4, 5]; -// const elementExists = array.includes(3); -// console.log(elementExists); // Output: true - - -// Q9)How do you find the maximum value in an array? - -// Answer: - -// const array = [4, 2, 7, 5, 1]; -// const max = Math.max(...array); -// console.log(max); // Output: 7 - - -// Q10)How do you reverse the order of elements in an array? - -// Answer: - -// const array = [1, 2, 3, 4, 5]; -// array.reverse(); +// Ch 5 Array Practice Set + + + +// Q1)How do you create an empty array in JavaScript? + +// Answer: + +// const emptyArray = []; + + +// Q2)How do you check if an array is empty in JavaScript? + +// Answer: + +// const array = []; + +// if (array.length === 0) { +// console.log("The array is empty"); +// } else { +// console.log("The array is not empty"); +// } + + +// Q3)How do you add elements to the end of an array in JavaScript? + +// Answer: + +// const array = [1, 2, 3]; +// array.push(4, 5); +// console.log(array); // Output: [1, 2, 3, 4, 5] + + +// Q4)How do you access an element at a specific index in an array? + +// Answer: + +// const array = [1, 2, 3]; +// const element = array[1]; +// console.log(element); // Output: 2 + + +// Q5)How do you remove the last element from an array in JavaScript? + +// Answer: + +// const array = [1, 2, 3]; +// const removedElement = array.pop(); +// console.log(array); // Output: [1, 2] +// console.log(removedElement); // Output: 3 + + +// Q6)How do you find the index of a specific element in an array? + +// Answer: + +// const array = [1, 2, 3, 4, 5]; +// const index = array.indexOf(3); +// console.log(index); // Output: 2 + + +// Q7)How do you concatenate two arrays in JavaScript? + +// Answer: + +// const array1 = [1, 2, 3]; +// const array2 = [4, 5, 6]; +// const concatenatedArray = array1.concat(array2); +// console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6] + + +// Q8)How do you check if an element exists in an array? + +// Answer: + +// const array = [1, 2, 3, 4, 5]; +// const elementExists = array.includes(3); +// console.log(elementExists); // Output: true + + +// Q9)How do you find the maximum value in an array? + +// Answer: + +// const array = [4, 2, 7, 5, 1]; +// const max = Math.max(...array); +// console.log(max); // Output: 7 + + +// Q10)How do you reverse the order of elements in an array? + +// Answer: + +// const array = [1, 2, 3, 4, 5]; +// array.reverse(); // console.log(array); // Output: [5, 4, 3, 2, 1] \ No newline at end of file diff --git a/Ch 5 Array.js b/Ch 5 Array.js index b5e20d9..e3153d6 100644 --- a/Ch 5 Array.js +++ b/Ch 5 Array.js @@ -1,489 +1,578 @@ -// Ch 5 Array -//Array Are Mutable -// In JS Array Are Object -//An array is a data structure in JavaScript used to store multiple values in a single variable. - -// Array Constructor: - -const fruits = ['apple', 'banana', 'orange', 7]; - -const numbers = new Array(1, 2, 3, 4, 5); - - -// Accessing Array Elements - -console.log(fruits[0]); // Output: apple -console.log(fruits[1]); // Output: banana -console.log(fruits[2]); // Output: orange - -// Modifying Array Elements - -fruits[1] = 'grape'; // Modifying the second element -console.log(fruits); // Output: ['apple', 'grape', 'orange'] - -// Array Length - -console.log(fruits.length); // Output: 3 - -console.log(typeof fruits) // Object - - -// Array Methods - - -// at() -> Returns an indexed element of an array -// concat() -> Joins arrays and returns an array with the joined arrays -// constructor -> Returns the function that created the Array object's prototype -// copyWithin() -> Copies array elements within the array, to and from specified positions -// entries() -> Returns a key/value pair Array Iteration Object -// every() -> Checks if every element in an array pass a test -// fill() -> Fill the elements in an array with a static value -// filter() -> Creates a new array with every element in an array that pass a test -// find() -> Returns the value of the first element in an array that pass a test -// findIndex() -> Returns the index of the first element in an array that pass a test -// flat() -> Concatenates sub-array elements -// flatMap() -> Maps all array elements and creates a new flat array -// forEach() -> Calls a function for each array element -// from() -> Creates an array from an object -// includes() -> Check if an array contains the specified element -// indexOf() -> Search the array for an element and returns its position -// isArray() -> Checks whether an object is an array -// join() -> Joins all elements of an array into a string -// keys() -> Returns a Array Iteration Object, containing the keys of the original array -// lastIndexOf()-> Search the array for an element, starting at the end, and returns its position -// length -> Sets or returns the number of elements in an array -// map() -> Creates a new array with the result of calling a function for each array element -// pop() -> Removes the last element of an array, and returns that element -// prototype -> Allows you to add properties and methods to an Array object -// push() -> Adds new elements to the end of an array, and returns the new length -// reduce() -> Reduce the values of an array to a single value (going left-to-right) -// reduceRight()-> Reduce the values of an array to a single value (going right-to-left) -// reverse() -> Reverses the order of the elements in an array -// shift() -> Removes the first element of an array, and returns that element -// slice() -> Selects a part of an array, and returns the new array -// some() -> Checks if any of the elements in an array pass a test -// sort() -> Sorts the elements of an array -// splice() -> Adds/Removes elements from an array -// toString() -> Converts an array to a string, and returns the result -// unshift() -> Adds new elements to the beginning of an array, and returns the new length -// valueOf() -> Returns the primitive value of an array - - - -// Method - - -// 1. at() - -// Returns an indexed element of an array. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// console.log(fruits.at(1)); // Output: 'banana' - - -// 2. concat() - -// Joins arrays and returns an array with the joined arrays. -// Example: - -// const fruits = ['apple', 'banana']; -// const vegetables = ['carrot', 'broccoli']; - -// const combined = fruits.concat(vegetables); -// console.log(combined); // Output: ['apple', 'banana', 'carrot', 'broccoli'] - - -// 3. constructor - -// Returns the function that created the Array object's prototype. -// Example: - -// const fruits = ['apple', 'banana']; - -// console.log(fruits.constructor); // Output: Array() - - -// 4. copyWithin() - -// Copies array elements within the array, to and from specified positions. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// numbers.copyWithin(0, 3); -// console.log(numbers); // Output: [4, 5, 3, 4, 5] - - -// 5. entries() - -// Returns a key/value pair Array Iteration Object. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const iterator = fruits.entries(); -// console.log(iterator.next().value); // Output: [0, 'apple'] -// console.log(iterator.next().value); // Output: [1, 'banana'] -// console.log(iterator.next().value); // Output: [2, 'orange'] - - -// 6. every() - -// Checks if every element in an array passes a test. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const allGreaterThanZero = numbers.every((num) => num > 0); -// console.log(allGreaterThanZero); // Output: true - - -// 7. fill() - -// Fill the elements in an array with a static value. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// numbers.fill(0, 2, 4); -// console.log(numbers); // Output: [1, 2, 0, 0, 5] - - -// 8. filter() - -// Creates a new array with every element in an array that passes a test. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const evenNumbers = numbers.filter((num) => num % 2 === 0); -// console.log(evenNumbers); // Output: [2, 4] - - -// 9. find() - -// Returns the value of the first element in an array that passes a test. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const foundNumber = numbers.find((num) => num > 3); -// console.log(foundNumber); // Output: 4 - - -// 10. findIndex() - -// Returns the index of the first element in an array that passes a test. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const foundIndex = numbers.findIndex((num) => num > 3); -// console.log(foundIndex); // Output: 3 - - -// 11. flat() - -// Concatenates sub-array elements. -// Example: - -// const numbers = [1, 2, [3, 4, [5, 6]]]; - -// const flattened = numbers.flat(); -// console.log(flattened); // Output: [1, 2, 3, 4, [5, 6]] - - -// 12. flatMap() - -// Maps all array elements and creates a new flat array. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const doubled = numbers.flatMap((num) => [num, num * 2]); -// console.log(doubled); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10] - - -// 13. forEach() - -// Calls a function for each array element. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// numbers.forEach((num) => { -// console.log(num * 2); -// }); -// // Output: -// // 2 -// // 4 -// // 6 -// // 8 -// // 10 - - -// 14. from() - -// Creates an array from an object. -// Example: - -// const arrayLikeObject = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 }; - -// const fruits = Array.from(arrayLikeObject); -// console.log(fruits); // Output: ['apple', 'banana', 'orange'] - - -// 15. includes() - -// Checks if an array contains the specified element. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// console.log(fruits.includes('banana')); // Output: true -// console.log(fruits.includes('mango')); // Output: false - - -// 16. indexOf() - -// Search the array for an element and returns its position. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// console.log(fruits.indexOf('banana')); // Output: 1 -// console.log(fruits.indexOf('mango')); // Output: -1 - - -// 17. isArray() - -// Checks whether an object is an array. -// Example: - -// console.log(Array.isArray([])); // Output: true -// console.log(Array.isArray({})); // Output: false - - -// 18. join() - -// Joins all elements of an array into a string. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const joinedString = fruits.join(', '); -// console.log(joinedString); // Output: 'apple, banana, orange' - - -// 19. keys() - -// Returns a Array Iteration Object, containing the keys of the original array. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const iterator = fruits.keys(); -// console.log(iterator.next().value); // Output: 0 -// console.log(iterator.next().value); // Output: 1 -// console.log(iterator.next().value); // Output: 2 - - -// 20. lastIndexOf() - -// Search the array for an element, starting at the end, and returns its position. -// Example: - -// const numbers = [1, 2, 3, 4, 2]; - -// console.log(numbers.lastIndexOf(2)); // Output: 4 -// console.log(numbers.lastIndexOf(5)); // Output: -1 - - -// 21. length - -// Sets or returns the number of elements in an array. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// console.log(fruits.length); // Output: 3 - -// fruits.length = 2; -// console.log(fruits); // Output: ['apple', 'banana'] - - -// 22. map() - -// Creates a new array with the result of calling a function for each array element. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const doubled = numbers.map((num) => num * 2); -// console.log(doubled); // Output: [2, 4, 6, 8, 10] - - -// 23. pop() - -// Removes the last element of an array and returns that element. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const removedFruit = fruits.pop(); -// console.log(fruits); // Output: ['apple', 'banana'] -// console.log(removedFruit); // Output: 'orange' - - -// 24. prototype - -// Allows you to add properties and methods to an Array object. -// Example: - -// Array.prototype.customMethod = function () { -// console.log('Custom method called!'); -// }; - -// const numbers = [1, 2, 3]; - -// numbers.customMethod(); // Output: 'Custom method called!' - - -// 25. push() - -// Adds new elements to the end of an array and returns the new length. -// Example: - -// const fruits = ['apple', 'banana']; - -// const newLength = fruits.push('orange'); -// console.log(fruits); // Output: ['apple', 'banana', 'orange'] -// console.log(newLength); // Output: 3 - - -// 26. reduce() - -// Reduce the values of an array to a single value (going left-to-right). -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); -// console.log(sum); // Output: 15 - - -// 27. reduceRight() - -// Reduce the values of an array to a single value (going right-to-left). -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0); -// console.log(sum); // Output: 15 - - -// 28. reverse() - -// Reverses the order of the elements in an array. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// numbers.reverse(); -// console.log(numbers); // Output: [5, 4, 3, 2, 1] - - -// 29. shift() - -// Removes the first element of an array and returns that element. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const removedFruit = fruits.shift(); -// console.log(fruits); // Output: ['banana', 'orange'] -// console.log(removedFruit); // Output: 'apple' - - -// 30. slice() - -// Selects a part of an array and returns the new array. -// Example: - -// const fruits = ['apple', 'banana', 'orange', 'mango']; - -// const slicedFruits = fruits.slice(1, 3); -// console.log(slicedFruits); // Output: ['banana', 'orange'] - - -// 31. some() - -// Checks if any of the elements in an array pass a test. -// Example: - -// const numbers = [1, 2, 3, 4, 5]; - -// const hasEvenNumber = numbers.some((num) => num % 2 === 0); -// console.log(hasEvenNumber); // Output: true - - -// 32. sort() - -// Sorts the elements of an array. -// Example: - -// const fruits = ['banana', 'apple', 'orange']; - -// fruits.sort(); -// console.log(fruits); // Output: ['apple', 'banana', 'orange'] - - -// 33. splice() - -// Adds/Removes elements from an array. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// // Remove 'banana' and insert 'mango' and 'cherry' -// const removedFruits = fruits.splice(1, 1, 'mango', 'cherry'); -// console.log(fruits); // Output: ['apple', 'mango', 'cherry', 'orange'] -// console.log(removedFruits); // Output: ['banana'] - - -// 34. toString() - -// Converts an array to a string and returns the result. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const fruitsString = fruits.toString(); -// console.log(fruitsString); // Output: 'apple,banana,orange' - - -// 35. unshift() - -// Adds new elements to the beginning of an array and returns the new length. -// Example: - -// const fruits = ['banana', 'orange']; - -// const newLength = fruits.unshift('apple'); -// console.log(fruits); // Output: ['apple', 'banana', 'orange'] -// console.log(newLength); // Output: 3 - - -// 36. valueOf() - -// Returns the primitive value of an array. -// Example: - -// const fruits = ['apple', 'banana', 'orange']; - -// const primitiveValue = fruits.valueOf(); -// console.log(primitiveValue); // Output: ['apple', 'banana', 'orange'] - +// Ch 5 Array +//Array Are Mutable +// In JS Array Are Object +//An array is a data structure in JavaScript used to store multiple values in a single variable. + +// Array Constructor: + +const fruits = ['apple', 'banana', 'orange', 7]; + +const numbers = new Array(1, 2, 3, 4, 5); + + +// Accessing Array Elements + +console.log(fruits[0]); // Output: apple +console.log(fruits[1]); // Output: banana +console.log(fruits[2]); // Output: orange + +// Modifying Array Elements + +fruits[1] = 'grape'; // Modifying the second element +console.log(fruits); // Output: ['apple', 'grape', 'orange'] + +// Array Length + +console.log(fruits.length); // Output: 3 + +console.log(typeof fruits) // Object + + +// Array Methods + + +// at() -> Returns an indexed element of an array +// concat() -> Joins arrays and returns an array with the joined arrays +// constructor -> Returns the function that created the Array object's prototype +// copyWithin() -> Copies array elements within the array, to and from specified positions +// entries() -> Returns a key/value pair Array Iteration Object +// every() -> Checks if every element in an array pass a test +// fill() -> Fill the elements in an array with a static value +// filter() -> Creates a new array with every element in an array that pass a test +// find() -> Returns the value of the first element in an array that pass a test +// findIndex() -> Returns the index of the first element in an array that pass a test +// flat() -> Concatenates sub-array elements +// flatMap() -> Maps all array elements and creates a new flat array +// forEach() -> Calls a function for each array element +// from() -> Creates an array from an object +// includes() -> Check if an array contains the specified element +// indexOf() -> Search the array for an element and returns its position +// isArray() -> Checks whether an object is an array +// join() -> Joins all elements of an array into a string +// keys() -> Returns a Array Iteration Object, containing the keys of the original array +// lastIndexOf()-> Search the array for an element, starting at the end, and returns its position +// length -> Sets or returns the number of elements in an array +// map() -> Creates a new array with the result of calling a function for each array element +// pop() -> Removes the last element of an array, and returns that element +// prototype -> Allows you to add properties and methods to an Array object +// push() -> Adds new elements to the end of an array, and returns the new length +// reduce() -> Reduce the values of an array to a single value (going left-to-right) +// reduceRight()-> Reduce the values of an array to a single value (going right-to-left) +// reverse() -> Reverses the order of the elements in an array +// shift() -> Removes the first element of an array, and returns that element +// slice() -> Selects a part of an array, and returns the new array +// some() -> Checks if any of the elements in an array pass a test +// sort() -> Sorts the elements of an array +// splice() -> Adds/Removes elements from an array +// toString() -> Converts an array to a string, and returns the result +// unshift() -> Adds new elements to the beginning of an array, and returns the new length +// valueOf() -> Returns the primitive value of an array + + + +// Method + + +// 1. at() + +// Returns an indexed element of an array. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// console.log(fruits.at(1)); // Output: 'banana' + + +// 2. concat() + +// Joins arrays and returns an array with the joined arrays. +// Example: + +// const fruits = ['apple', 'banana']; +// const vegetables = ['carrot', 'broccoli']; + +// const combined = fruits.concat(vegetables); +// console.log(combined); // Output: ['apple', 'banana', 'carrot', 'broccoli'] + + +// 3. constructor + +// Returns the function that created the Array object's prototype. +// Example: + +// const fruits = ['apple', 'banana']; + +// console.log(fruits.constructor); // Output: Array() + + +// 4. copyWithin() + +// Copies array elements within the array, to and from specified positions. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// numbers.copyWithin(0, 3); +// console.log(numbers); // Output: [4, 5, 3, 4, 5] + + +// 5. entries() + +// Returns a key/value pair Array Iteration Object. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const iterator = fruits.entries(); +// console.log(iterator.next().value); // Output: [0, 'apple'] +// console.log(iterator.next().value); // Output: [1, 'banana'] +// console.log(iterator.next().value); // Output: [2, 'orange'] + + +// 6. every() + +// Checks if every element in an array passes a test. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const allGreaterThanZero = numbers.every((num) => num > 0); +// console.log(allGreaterThanZero); // Output: true + + +// 7. fill() + +// Fill the elements in an array with a static value. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// numbers.fill(0, 2, 4); +// console.log(numbers); // Output: [1, 2, 0, 0, 5] + + +// 8. filter() + +// Creates a new array with every element in an array that passes a test. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const evenNumbers = numbers.filter((num) => num % 2 === 0); +// console.log(evenNumbers); // Output: [2, 4] + + +// 9. find() + +// Returns the value of the first element in an array that passes a test. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const foundNumber = numbers.find((num) => num > 3); +// console.log(foundNumber); // Output: 4 + + +// 10. findIndex() + +// Returns the index of the first element in an array that passes a test. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const foundIndex = numbers.findIndex((num) => num > 3); +// console.log(foundIndex); // Output: 3 + + +// 11. flat() + +// Concatenates sub-array elements. +// Example: + +// const numbers = [1, 2, [3, 4, [5, 6]]]; + +// const flattened = numbers.flat(); +// console.log(flattened); // Output: [1, 2, 3, 4, [5, 6]] + + +// 12. flatMap() + +// Maps all array elements and creates a new flat array. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const doubled = numbers.flatMap((num) => [num, num * 2]); +// console.log(doubled); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10] + + +// 13. forEach() + +// Calls a function for each array element. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// numbers.forEach((num) => { +// console.log(num * 2); +// }); +// // Output: +// // 2 +// // 4 +// // 6 +// // 8 +// // 10 + + +// 14. from() + +// Creates an array from an object. +// Example: + +// const arrayLikeObject = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 }; + +// const fruits = Array.from(arrayLikeObject); +// console.log(fruits); // Output: ['apple', 'banana', 'orange'] + + +// 15. includes() + +// Checks if an array contains the specified element. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// console.log(fruits.includes('banana')); // Output: true +// console.log(fruits.includes('mango')); // Output: false + + +// 16. indexOf() + +// Search the array for an element and returns its position. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// console.log(fruits.indexOf('banana')); // Output: 1 +// console.log(fruits.indexOf('mango')); // Output: -1 + + +// 17. isArray() + +// Checks whether an object is an array. +// Example: + +// console.log(Array.isArray([])); // Output: true +// console.log(Array.isArray({})); // Output: false + + +// 18. join() + +// Joins all elements of an array into a string. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const joinedString = fruits.join(', '); +// console.log(joinedString); // Output: 'apple, banana, orange' + + +// 19. keys() + +// Returns a Array Iteration Object, containing the keys of the original array. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const iterator = fruits.keys(); +// console.log(iterator.next().value); // Output: 0 +// console.log(iterator.next().value); // Output: 1 +// console.log(iterator.next().value); // Output: 2 + + +// 20. lastIndexOf() + +// Search the array for an element, starting at the end, and returns its position. +// Example: + +// const numbers = [1, 2, 3, 4, 2]; + +// console.log(numbers.lastIndexOf(2)); // Output: 4 +// console.log(numbers.lastIndexOf(5)); // Output: -1 + + +// 21. length + +// Sets or returns the number of elements in an array. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// console.log(fruits.length); // Output: 3 + +// fruits.length = 2; +// console.log(fruits); // Output: ['apple', 'banana'] + + +// 22. map() + +// Creates a new array with the result of calling a function for each array element. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const doubled = numbers.map((num) => num * 2); +// console.log(doubled); // Output: [2, 4, 6, 8, 10] + + +// 23. pop() + +// Removes the last element of an array and returns that element. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const removedFruit = fruits.pop(); +// console.log(fruits); // Output: ['apple', 'banana'] +// console.log(removedFruit); // Output: 'orange' + + +// 24. prototype + +// Allows you to add properties and methods to an Array object. +// Example: + +// Array.prototype.customMethod = function () { +// console.log('Custom method called!'); +// }; + +// const numbers = [1, 2, 3]; + +// numbers.customMethod(); // Output: 'Custom method called!' + + +// 25. push() + +// Adds new elements to the end of an array and returns the new length. +// Example: + +// const fruits = ['apple', 'banana']; + +// const newLength = fruits.push('orange'); +// console.log(fruits); // Output: ['apple', 'banana', 'orange'] +// console.log(newLength); // Output: 3 + + +// 26. reduce() + +// Reduce the values of an array to a single value (going left-to-right). +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); +// console.log(sum); // Output: 15 + + +// 27. reduceRight() + +// Reduce the values of an array to a single value (going right-to-left). +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0); +// console.log(sum); // Output: 15 + + +// 28. reverse() + +// Reverses the order of the elements in an array. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// numbers.reverse(); +// console.log(numbers); // Output: [5, 4, 3, 2, 1] + + +// 29. shift() + +// Removes the first element of an array and returns that element. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const removedFruit = fruits.shift(); +// console.log(fruits); // Output: ['banana', 'orange'] +// console.log(removedFruit); // Output: 'apple' + + +// 30. slice() + +// Selects a part of an array and returns the new array. +// Example: + +// const fruits = ['apple', 'banana', 'orange', 'mango']; + +// const slicedFruits = fruits.slice(1, 3); +// console.log(slicedFruits); // Output: ['banana', 'orange'] + + +// 31. some() + +// Checks if any of the elements in an array pass a test. +// Example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const hasEvenNumber = numbers.some((num) => num % 2 === 0); +// console.log(hasEvenNumber); // Output: true + + +// 32. sort() + +// Sorts the elements of an array. +// Example: + +// const fruits = ['banana', 'apple', 'orange']; + +// fruits.sort(); +// console.log(fruits); // Output: ['apple', 'banana', 'orange'] + + +// 33. splice() + +// Adds/Removes elements from an array. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// // Remove 'banana' and insert 'mango' and 'cherry' +// const removedFruits = fruits.splice(1, 1, 'mango', 'cherry'); +// console.log(fruits); // Output: ['apple', 'mango', 'cherry', 'orange'] +// console.log(removedFruits); // Output: ['banana'] + + +// 34. toString() + +// Converts an array to a string and returns the result. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const fruitsString = fruits.toString(); +// console.log(fruitsString); // Output: 'apple,banana,orange' + + +// 35. unshift() + +// Adds new elements to the beginning of an array and returns the new length. +// Example: + +// const fruits = ['banana', 'orange']; + +// const newLength = fruits.unshift('apple'); +// console.log(fruits); // Output: ['apple', 'banana', 'orange'] +// console.log(newLength); // Output: 3 + + +// 36. valueOf() + +// Returns the primitive value of an array. +// Example: + +// const fruits = ['apple', 'banana', 'orange']; + +// const primitiveValue = fruits.valueOf(); +// console.log(primitiveValue); // Output: ['apple', 'banana', 'orange'] + + + +// Map, Filter, Reduce + +// Higher order array Method + + + +// Looping Through Array +// For Loop +let num = [1, 2, 5, 6, 7, 9, 10] + +// for (let i = 0; i < num.length; i++) { +// console.log(num[i]) +// } + +// num.forEach((element) => { +// console.log(element * element) +// }) + + +// For Loop: + +// const array = [1, 2, 3, 4, 5]; + +// for (let i = 0; i < array.length; i++) { +// console.log(array[i]); +// } + + +// forEach(): + + +// const array = [1, 2, 3, 4, 5]; + +// array.forEach((element) => { +// console.log(element); +// }); + + +// for...of Loop: +// The for...of loop is introduced in ECMAScript 6 and provides a concise way to iterate over iterable objects, including arrays. Here's an example: + +// const array = [1, 2, 3, 4, 5]; + +// for (const element of array) { +// console.log(element); +// } + + +// Array.map() +// The map() method creates a new array by applying a provided function to each element in the original array.It returns the resulting array.Here's an example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const doubledNumbers = numbers.map((number) => { +// return number * 2; +// }); + +// console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10] + + +// Array.filter() +// The filter() method creates a new array with all elements that pass a test implemented by the provided function. It returns the filtered array.Here's an example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const evenNumbers = numbers.filter((number) => { +// return number % 2 === 0; +// }); + +// console.log(evenNumbers); // Output: [2, 4] + + +// Array.reduce() +// The reduce() method applies a function to an accumulator and each element in the array(from left to right) to reduce it to a single value.It returns the accumulated result.Here's an example: + +// const numbers = [1, 2, 3, 4, 5]; + +// const sum = numbers.reduce((accumulator, currentNumber) => { +// return accumulator + currentNumber; +// }, 0); + +// console.log(sum); // Output: 15 + +// const array = [1, 2, 3, 4, 5]; +// let sum = array.reduce(add) + +// add -> Function \ No newline at end of file diff --git a/Ch 6 JS In Browser.js b/Ch 6 JS In Browser.js new file mode 100644 index 0000000..ae03c14 --- /dev/null +++ b/Ch 6 JS In Browser.js @@ -0,0 +1,75 @@ +// Element Tab -> All Element +// console Tab -> All The Error Plus Logs +// Network Tab -> All The Network Request And Requirement + +// External File For Js -> File Cache Ho Jati he So Website Fast Work Karti He +// We Can Add Js In Script Tag Also +// +// + +// Separation Of Concern and Cashing + +// Js Console Object +// console.log(console) +// console.error(error) +// console.assert(assert) +// console.clear() +// console.table(table) +// console.warn(warn) +// console.info(info) +// console.time(time) +// console.timeEnd(timeEnd) + +// List All Method +// console.log(console) + +// Output And Return Type Is There +// console.log("Hey Darshan") +// Output : +// Hey Darshan +// Undefined + +// Alert Prompt And Confirm +// Alert -> Alert Box Show Karta Hai +// Prompt -> Prompt Box Show Karta Hai -> Input Lene Ke Liye +// Confirm -> Confirm Box Show Karta Hai -> Yes Or No Lene Ke Liye + +// alert("Enter The Value Of A") +// let a = prompt("Enter A Here: ") +// let a = prompt("Enter A Here: ", "578") // Default Value +// document.write(a) + + +// Confirm -> Yes Or No Lene Ke Liye +// let write = confirm("Do You Want To Write It To The Page") +// if (write) { +// document.write(a) +// } else { +// document.write("Please Allow Me To Write") +// } + +// This Will Stop Screen Execution Thats Why Not Suggested To Use That In User Side Plus Look Like Old Vintage Website So -> Use In Admin Panel + +// BOM And DOM + +// BOM -> Browser Object Model +// DOM -> Document Object Model +console.log(window) +// window.console.log(window) -> Same Work Above + +// window is global object under that -> Bom , Dom , Js Core Feature Lies + +// Apke Pure HTML Page ko Document Represent Karta Hai -> Pure Page Ka Object Banke Usko Document Name De Diya Gaya He +console.log(document) +document.body.style.background = "yellow" + + + +// BOM (Browser Object Model): +// The Browser Object Model represents the browser window or tab itself. It provides additional objects and properties that allow you to control the browser's behavior and interact with the user. The window object acts as the global object in JavaScript and serves as the entry point to the BOM. It provides properties and methods to control the browser's behavior, such as window.location to manipulate the URL, window.alert() to display alert messages, and window.open() to open new browser windows or tabs. + + +// Location href = "https://dpvasani56.com" -> Redirect To Another URL + +// console.log(window) => All Method +// Window Object -> Global Object diff --git a/Ch 6 JavaScript In Browser Practice Set.js b/Ch 6 JavaScript In Browser Practice Set.js index a064439..37b4358 100644 --- a/Ch 6 JavaScript In Browser Practice Set.js +++ b/Ch 6 JavaScript In Browser Practice Set.js @@ -1,63 +1,63 @@ -// Ch 6 JavaScript In Browser Practice Set - -// Q1)How can you log a message to the console using the console object? - -// console.log("Hello, World!"); - - -// Q2)How can you display an error message in the console using the console object? - -// console.error("An error occurred."); - - -// Q3)How can you clear the console using the console object? - -// console.clear(); - - -// Q4)How can you log a warning message to the console using the console object? - -// console.warn("This is a warning."); - - -// Q5)How can you display tabular data as a table in the console using the console object? - -// const data = [ -// { name: "John", age: 25 }, -// { name: "Jane", age: 30 }, -// { name: "Bob", age: 35 } -// ]; -// console.table(data); - -// Q6)How can you write an error message to the console if a condition is false using the console object? - -// const value = 10; -// console.assert(value > 20, "Value should be greater than 20."); - - -// Q7)How can you measure the time taken to execute a block of code using the console object? - -// console.time("Timer"); -// // Code block to measure execution time -// console.timeEnd("Timer"); - - -// Q8)How can you prompt the user to enter their name and log it to the console using the prompt function? - -// const name = prompt("Enter your name:"); -// console.log("Hello, " + name + "!"); - - -// Q9)How can you display an alert box with a message to the user using the alert function? - -// alert("This is an alert message."); - - -// Q10)How can you display a confirm dialog box and log the user's choice to the console using the confirm function? - -// const result = confirm("Are you sure you want to delete this item?"); -// if (result === true) { -// console.log("Item deleted."); -// } else { -// console.log("Deletion cancelled."); +// Ch 6 JavaScript In Browser Practice Set + +// Q1)How can you log a message to the console using the console object? + +// console.log("Hello, World!"); + + +// Q2)How can you display an error message in the console using the console object? + +// console.error("An error occurred."); + + +// Q3)How can you clear the console using the console object? + +// console.clear(); + + +// Q4)How can you log a warning message to the console using the console object? + +// console.warn("This is a warning."); + + +// Q5)How can you display tabular data as a table in the console using the console object? + +// const data = [ +// { name: "John", age: 25 }, +// { name: "Jane", age: 30 }, +// { name: "Bob", age: 35 } +// ]; +// console.table(data); + +// Q6)How can you write an error message to the console if a condition is false using the console object? + +// const value = 10; +// console.assert(value > 20, "Value should be greater than 20."); + + +// Q7)How can you measure the time taken to execute a block of code using the console object? + +// console.time("Timer"); +// // Code block to measure execution time +// console.timeEnd("Timer"); + + +// Q8)How can you prompt the user to enter their name and log it to the console using the prompt function? + +// const name = prompt("Enter your name:"); +// console.log("Hello, " + name + "!"); + + +// Q9)How can you display an alert box with a message to the user using the alert function? + +// alert("This is an alert message."); + + +// Q10)How can you display a confirm dialog box and log the user's choice to the console using the confirm function? + +// const result = confirm("Are you sure you want to delete this item?"); +// if (result === true) { +// console.log("Item deleted."); +// } else { +// console.log("Deletion cancelled."); // } \ No newline at end of file diff --git a/Ch 6 JavaScript In Browser.js b/Ch 6 JavaScript In Browser.js index 935f9e6..3dffd5b 100644 --- a/Ch 6 JavaScript In Browser.js +++ b/Ch 6 JavaScript In Browser.js @@ -1,243 +1,265 @@ -// JavaScript In Browser -// Semicolon Are Optional -// JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. -// JS -> Initially Created To Make Web Pages -// Browser Has Embedded Engine -> JavaScript Engine or JavaScript Run Time -// JS Ability In Browser Is Very Limited - - -// Developer Tool -> Every Browser Has This -> Make Developer Life Easier - - -// Element - Console - Network -// All HTML Element - All Error + Log - All Network Request - - -// Use JS In Browser - -// Scripts can be placed in the , or in the section of an HTML page, or in both. -// To use JavaScript in a web page, you can embed it directly within the HTML document. - -// Inline Script: JavaScript code can be placed directly within the - - -// External Script: JavaScript code can also be stored in an external file and linked to the HTML document using the This Must Be In Body Tag - - -// Example Of JS In Browser - -// -// -// -// JavaScript in the Browser -// -// -//

Hello, World!

-// - -// -// -// - - -// Console Object Method - - -// The console object in JavaScript provides a set of methods that allow developers to interact with the browser's console. These methods are useful for logging messages, debugging code, and monitoring the execution of JavaScript code. Here are some commonly used methods of the console object along with examples: - -// log(): Logs a message to the console. - -// console.log('Hello, World!'); // Output: Hello, World! - - -// error(): Logs an error message to the console. - -// console.error('An error occurred.'); // Output: An error occurred. - - -// warn(): Logs a warning message to the console. - -// console.warn('This is a warning.'); // Output: This is a warning. - - -// info(): Logs an informational message to the console. - -// console.info('This is an information.'); // Output: This is an information. - - -// debug(): Logs a debug message to the console. - -// console.debug('Debugging information.'); // Output: Debugging information. - - -// assert(): Writes an error message to the console if the provided condition is false. - -// const value = 10; -// console.assert(value > 20, 'Value should be greater than 20.'); // Output: Value should be greater than 20. - - -// clear(): Clears the console. - -// console.clear(); // Clears the console - - -// table(): Displays tabular data as a table in the console. - -// const data = [ -// { name: 'John', age: 25 }, -// { name: 'Jane', age: 30 }, -// { name: 'Bob', age: 35 } -// ]; -// console.table(data); -// Output: -// ┌─────┬──────┬─────┐ -// │ (index) │ name │ age │ -// ├─────┼──────┼─────┤ -// │ 0 │ 'John' │ 25 │ -// │ 1 │ 'Jane' │ 30 │ -// │ 2 │ 'Bob' │ 35 │ -// └─────┴──────┴─────┘ -// count(): Logs the number of times count() has been called with the provided label. - -// console.count('Counter'); // Output: Counter: 1 -// console.count('Counter'); // Output: Counter: 2 -// console.count('Another Counter'); // Output: Another Counter: 1 -// console.count('Counter'); // Output: Counter: 3 - - -// time() and timeEnd(): Measures the time taken to execute a block of code. - -// console.time('Timer'); -// // Code block to measure execution time -// console.timeEnd('Timer'); // Output: Timer: