We have workers in JavaScript and there are three sections of workers. Web Worker, Web Socket and Service Worker. These are script that run in the background without interfering the UI. In another word, we can say that these workers run in a seperate thread than the main browser thread which helps to improve the application performance because it does not bother excessive activities of the main thread.

DIFFERENCES

The web workers and web socket have DOM access whereas service worker has no dom access because it runs on a worker context. The web socket is actually a part of main thread that helps to access and manipulate the DOM.

WEB WORKER

We know that our HTML perser, parses the html code line by line and as soon as it finds the script tag, it blocks the entire UI until we the output of the script. So, in order ot overcome from this blocking nature, we use web worker. Web worker actually runs the script tag in a different environment so that our complex operations don't bock the UI and generate the script output from different thread and provide the output.

Web workers are used to run the code in a background script.

We can create a worker object using contstructor worker()

Workers run in a different global context

We use workers to do complex operations without interfering the UI

We can sent and accept messsages or data from UI using events.

var workerObj = new Worker('workerFileName.js');
We use onMessage(); To receive the messsages postMessage(); to send the data or messages

Advantages

Helps in complex computing

Does not block the UI

Optimize the program performance

Disadvantages

Does not have access to parent, window and documnent object.

JavaScript is a scripting language. It is different from Java language. It is an object-based, lightweight, cross-platform translated language. It is used for client-side and server-side development. It is widely used for client-side validation. The JavaScript code can be inserted into HTML pages that can be understood and executed by web browsers because the JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser.

The browser does not interpret server side scripting language because it can interpret or execute HTML, CSS, DXTML and Client Side Script. We need to add an interpreter to interpret or execute server side script installed in the server called “Zen-engine”. PHP and .NET are Server Side Script. Note- Server Side Script is not available at the server because it is sent from the browser.

JavaScript was developed by Brendan Eich, who was a Netscape programmer. Brendan Eich developed this new scripting language in just ten days in the year September 1995. At the time of its launch, JavaScript was initially called Mocha. After that, it was called Live Script and later known as JavaScript.

Argument object in javaScript represents arguments passed to a function.

<script> function abc(a) { console.log(typeof (a)); } abc(); //undefined abc(1); // number abc("1"); // string </script> //To know the number of arguments// <script> function abc() { console.log(arguments.length); //4 document.write(arguments.length); // 4 } abc(1, 2, 3, 4); //4 </script>

These are the features of JavaScript:

  • Open-source
  • It is a patter that is based on the concept of "objects", which can contain data and code.
  • Interpreted programming language:-Since JavaScript is an 'interpreted' language. it reduces the time required by other programming languages like Java for compilation. So, it is fast in comparision to others.
  • Integration with other back-end and front-end technologies
  • Lightweight
  • Used especially for the development of network-based applications
  • JavaScript has countless frameworks and libraries that are extensively used for developing web applications and games of all kinds.
  • Cross-platform compatible: We know that when we need to create app, we need to pick a platform to create the app for, such as Android, IOS or for windows store. If we use native technologies we need to write code in JAVA to create Android App, Object C for IOS and C# and Xaml for Windows but learning JavaScript, we can create all.gn
  • There is no need for a web page to reload when running JavaScript. For example, form input validation.
  • JavaScript helps in making the UI of web applications look and feel much better.

Whenever we assign or copy one object to another object like user = obj, we don't copy the data like sarfraz to bruce but reference. Suppose, I have a hard disk in which we create an object and put any data like sarfraz and when we copy this object to the user like user = obj, it will not copy the data but location and when we change the value later, it will also change the value of first one which was name:sarfraz and now it will be bruce so both object will have the same value bruce. but we want that when we copy one object to another object, the value should be different for both the objects and to achieve this, we use shallow copy and deep copy.

<script> let obj = { name: "sarfraz" }; console.log(obj); // name: "sarfraz" let user = obj; user.name = "bruce" console.log(obj); // name: "bruce" console.log(user); // name: "bruce" // Note: After copying to another object, the first object value will also be bruce becuase // it copies the memory location </script>

Use of shallow copy

  • Object.assign({}, obj)
  • Create one object and use destructuring inside it

We use shallow copy by Object.assign({}, obj) and second way is the create one object and use destructuring inside it like let user = {...obj} to create shallow copy and will get different values for both objects.

Question 1 :- Do we copy memory location or value when we copy one object

Memory Location

Question 2 :- Difference between shallow copy and deep copy

In shallow copy, main object is copied but in Deep copy, we can also copy the nested objects

Question 3 :- What do we actually perform when we use shallow and deep copy

We copy value in the place of memory location

Question 4 :- What are the ways to use shallow and deep copy?

There are two ways to use shallow copy 1. object.assign and 2. object destructuring and for deep Copy we can use json.parse and inside it json.stringify but in this method, date and function do not work so to fix this, we can use lodash library or we can do it manually using for loop and copy each key but it is very lengthy process. It is better to use lodash CND path and then let user = _.cloneDeep(obj);

<script> let obj = { name: "sarfraz" }; console.log(obj); // name: "sarfraz" // let user = Object.assign({}, obj); // First way to shallow copy let user = { ...obj }; // Second way to shallow copy user.name = "bruce"; console.log(obj); // name: "sarfraz" console.log(user); // name: "bruce" </script>

Deep Copy

Now, deep copy comes into the picture when we have nested object.

let obj = { name: "sarfraz", address: { city: "Noida", state: 'UP' } }; let user = { ...obj }; user.address.city = "Gurgaon" console.log(obj); // obj city will be gurgaon which is a problem and to fix this we use deep copy console.log(user); // user city will be gurgaon </script>

Here, by using both mehtods of shallow copy, we will not get the correct output becuase both the methods of shallow copy fix the issue upto one lavel of coping object and to fix the second lavel or object inside object like obj.address.city, we need to use deep copy.

Here, to fix this issue, we need to convert first into JSON STRING using JSON.stringify() and then we need to convert this json object into normal object using JSON.parse();

<script> let obj = { name: "sarfraz", address: { city: "Noida", state: 'UP' } }; let user = JSON.parse(JSON.stringify(obj)); user.address.city = "Gurgaon" console.log(obj); // obj city will Noida console.log(user); // user city will be gurgaon </script>

Limitations of Deep copy

Yes. <script> const obj = { name: "sarfraz", age: 25 } console.log(obj.name); // sarfraz for (key in obj) { document.write(key + " : " + obj[key] + '<br>') } // name : sarfraz // age : 25 </script>

    Some of the disadvantages of JavaScript are:
  • No support for multi-threading.
  • It will stop the rendering if you make any mistake in the code and difficult to find.
  • No support for multi-processing
  • JavaScript codes are always visible to everyone.( by control+U, inspect, F12) so it is not secured.
  • We know that the code of JavaScript is executed on the user’s or client machine and in some case it is used for malicious purposes and because of this some people disable the JavaScript.
  • No support for networking applications
  • Yes, It is case-sensitive.

  • Using Object literal
  • Using Create method
  • Using constructor method
Refer question no. 8 in notes/pdf for more details.

We can read or write properties of an object in javaScript using dot and bracket notation as follows:-
object.firstName
// We will get Sarfraz if first name set as Sarfraz.
We use bracket notation if a property contains special character and the property is stored in a varaiable.

An array is a collection of elements or values. We need array because when we use or declare a variable, it can store only one value at a time and to store multiple values under one name an 'Array' is declared.
An array can store any type of data.
There are two ways to define or declare the array.
1. Using bracket such as array = [a, 1, "sarfraz", 25];
1. Using array object such as array1 = new Array[a, 1, "sarfraz", 25];

Use of some, every,find and filter

All the four array methods are almost same. Some method returns true if any value or element in the given array passes the test else false.
The same is the case with every if all the values or elements in the given array pass the test else false.
find return the first value that passes the test and filter return all the values in the form of an Array that passes the test.

find() is used to find only the first value that passes the test or condition not the remaining value of any variable or Array and findIndex() find the index of the first value that clears the test. filter function will give a new array which has all the elements that passes the condition. toString will convert the array into string. Once it is converted to string, no function of array will be applicable. valueOf is a default function of array. It will give the same result when you print var a. fill function is used to change the all elements to a new element you write as fill(Ram). In this case, var ages =[20, 19, 18, Sar] will become Ram, Ram, Ram, Ram. Since all elements are there in var ages so Ram will be printed 4 times.

We can use for loop and for of loop to iterate the element of an array, explained in loop

Yes, you can assign an anonymous function to a variables

Yes, you can pass an anonymous function to an argument as well.

Lexical scope is the definition area of an expression. In other words, an item's lexical scope is the place in which the item got created.
Lexical scope tells the range of anything. we use arrow function when we have the issue of lexical scope. For example:-If we daclare let variable inside a function, we will say that the scope of let variable is till this function or the lexical scope of let variable is this function.
We also know that when we declare any object and if we want to use any other property of the same object we use this keyword.
We have also the concept of "lexical scope of this"
Sometimes, we miss the "this keyword" of any object inside the same object and that time we check the lexical scope and fix the issue using arrow function becuase it does not its own this keyword.

Step 1

<script> let obj = { name: ["sarfraz", "john"], age: 25, getName: function () { console.log(this.age); // it will return 25 } } obj.getName(); </script>

Step 2

<script> let obj = { name: ["sarfraz", "john"], age: 25, getName: function () { this.name.map(function (item) { console.log(item + " : " + this.age); // Here this.age will return undefined because different functional //scope has started, here "this" lost itself in this lexical scope }) } } obj.getName(); </script>

Step 3

<script> let obj = { name: ["sarfraz", "john"], age: 25, getName: function () { console.log(this.age); let that = this; // Now, that variable has this keyword and now we will //get the output if we write that.age but This is not a //good practice, instead of this we will use arrow function this.name.map(function (item) { console.log(item + " : " + that.age); }) //arrow function this.name.map((item) => { console.log(item + " : " + this.age); }) } } obj.getName(); </script>

Difference between normal/regular function and arrow function.

In JavaScript, functions are objects and therefore, functions can take other functions as arguments and can also be returned by other functions.

A callback function is a function that is passed as an argument to another function, to be "called back" at a later time. A function that accepts other function as arguments is called higher-order function. callbacks are not asynchronous by nature, but can be used for asynchronous purposes.

In JavaScript codes are executed synchronously which means 2nd code will be executed once first code is executed but if you want to execute the codes together like asynchronously then we will use callbacks and promise.

First of all we will make a function, name can be anything and passed parameter a, b, callback then a and b have been added in console and third parameter has been called.
We know that in callback function, another function is taken as an argument so prmtr(which is function has been defined above) has been taken.
Here, callback() will control the outer function prmtr().
Since callback() was called first and “I will be used an an argument” printed first and then console.log(a+b). So, result will be “I will be used an an argument” 30.

Built-in Method Values
Date() Returns the present date and time
concat() Joins two strings and returns the new string
push() Adds an item to an array at the end.
pop() Removes and also returns the last element of an array
round() Rounds of the value to the nearest integer and then returns it
length Returns the length of a string
Which built-in method returns the character at the specified index?
charAt()
Which built-in method combines the text of two strings and returns a new string?
concat()
Which built-in method calls function for each element in the array?
forEach()
Which built-in method returns the index within the calling string object of the first occurance of the specified value?
indexOf();
Which built-in method reverses the order of the elements of an array?
reverse()
Which built-in method sorts the elements of an array?
sort()
Which built-in method returns the characters in a string begging at the specified location through the specified number of charactors?
substr()
Which built-in method returns the string representation of the number's value?
toString()
How to read elements of an array in JavaScript?
x.length(Here x is an array which has some values like 1, 2 etc.)

operator is a symbol that performs an operation such as adding, multiplying, dividing etc between two or more than two operants(var a and var b values, numbers etc). We have 8 operators. +, -, *, exponentiaiton(**), division, modulus(remainder %), increment(++), decrement(--)

To know the type of a JavaScript variable, we can use the typeof operator. The data type of JavaScript can be divided into two types. Primitive and non-primitive data type.

The typeof is a unary operator that is placed before its single operand, which can be of any type. its value is a string indicating the data type of the operand.

<script> let arry = [1, 2, 3]; console.log(typeof (arry)); // Object let Obj = { name: "sarfraz" } console.log(typeof (Obj)); // Object // Note: the typeof non primitive data tyes are object and this is why arry and object typeOf is object let a; console.log(typeof (a)); // undefined let a = null; console.log(typeof (a)); // Object let a = false / true; console.log(typeof (a)); // boolean let a = 3.14; console.log(typeof (a)); // number let a = NaN; console.log(typeof (a)); // number let fun = function () { document.write("Hello"); }; fun(); console.log(typeof (fun)); // function </script>

HTML5 introduced a lot of api like

  • HTML Local Storage
  • HTML Application Cache
  • HTML Geolocation
  • HTML Drag and Drop
  • HTML Web Workers
  • HTML SSE(Server-Sent Events)

It is an API to store the web-side data. We have an API of HTML5 that we use to store the data of the web.
It has two types LOCAL STORATE and SESSION STORAGE.
Note:- It will work on live server only and use chrome for this.
LOCAL STORAGE VS COOKES
LOCAL STORATE:- HTML5 local storage API is used to store the data locally in user’s browsers or user’s computer/laptop. It is an alternate and better way than cookies. It is not related to the server.
When we make any website using JavaScript or JavaScript framework or library, the execution of the code takes place in user’s browser or on client side(browser) and if we store the data locally means in the user’s browsers or pc, the codes will execute quickly so the web page will load quickly.
But when we use any server side script we should use cookies.
Local storage data never save the data in the server with HTTP request means whenever we send data from local storage to server using HTTP request then that data will not save in the server. So, the response will be faster but cookies data will save in the server when we send data via HTTP request so it can be a bit slow in the response from the server.
We can save 5GB data in the local storage and Local storage data never expires but we can clear data using JavaScript methods but cookies data will expire with the time you set and if you don’t set any time it will expire with session.
Limitation of local storage:-
We can store data as string only, not boolean, number, etc. up to 5MB
Point to Remember
1.Local storage is a property of window object.
2.It stores data in the machine or web browser.
3.It does not have expiry date
4.It does not get saved to the server but in cookies it gets sent.
Methods:- (Both local & Session storage have the same methods)
setItem(key, value) - To store or add the key value pair. It will overirde the old value if already added/saved.
getItem(key) - To get the value aleady set or stored.
key(n) - It return the index of the value.
removeItem(key)- To remove the value stored
Here is the screen-shot and steps to use the above methods.

Note: If we don't set any expiration date, the cookie will expire on closing the tab. Only key and value are required to create a cookie and the rest is option. The optional thing will be filled by the browser by default if we don't set it. Here if we set path equal to forward slash then we can see the cookies by going to the default html page like index.html or any name but if we want to access the cookies from another like contact page then we will have to give path like /contact. See the video for more details.

If user enter key and value something like a##$ as key and value as 7584 then key value pair will not set like name=sarfraz; age=30;( Yaha par semecolon means second cookies, yaha do cookies add huwa hai) and because of that we need to use document.cookie = `${encodeURIComponent(Key)}=${encodeURIComponent(value)}` Now, 0##$ will be encoded and that can be decoded(to read and understand what it is ) using decodeURIComponent("a##$") and it will return a.

We can do a page redirect using JavaScript at client side by adding one line of code under head section

<div id="mylocation"></div> <head> <script> window.location = "https://www.google.com"; </script> <script> window.location.href = "home.html"; //to go to the home page on login page button click </script> </head>

We can use window.print();

Exception is an unexpected condition that occurs during the execution of the code.
If we write any code whose out is not as expected, it generates an exception to handle that exception, we use exception handling.
For example:- Dividing any number by 0 is an unexpected condition because we know that it is hardly done by any user but if any user does like that, we need to write the code in such a manner so that we can handle that exception or unexpected condition if any user divides any number by 0. We know that dividing 10 by 0 is an unexpected condition called exception and to handle this we will use Exception Handling.
We need to use try, catch, finally, and throw to handle the exception.
In Javascript, the exception is considered as an error, an error that occurs during the execution of the code unexpectedly.

With the help of try/catch/finally, we can handle exceptions in JavaScript. To implement it, we need to put all the codes under try, and if it finds any error, the catch will run and show the error. We mostly use it when we have to receive the data from the server in JSON form.

Here, we can't catch syntax errors. It does not work synchronously. It will not work properly if we use setTimout. In order to make setTimeOut function work properly we need to put try and catch in a function
like set timeout(function(){try{blabla}catch(error){console.lot("error")}}, 1000)

There are three ways to declare variable in javaScript.
var, let and const
let and const were introduced in ES6 to overcome some of the Limitations of var varaiable.

The shadowing is the process where we can declare variables with the same name in different scopes.
We can't specify or declare const and let variabls twice in the same scope.
<div id="mylocation"></div> <script> function outerScope() { const x = 20; document.write('outer scope value is ', ' : ', x, '<br>'); function innerScope() { const x = 10; document.write('inner scope value is ', ' : ', x); } innerScope(); // 10 } outerScope(); // 20 </script>

1.“==” operator is a comparison operator that used to compare the values
2.“===” operator is also a comparison operator that is used to compare the values as well as types.
Example:
var x = 3;
var y = "3";
(x == y)  // it returns true as the value of both x and y is the same
(x === y) // it returns false as the typeof x is "number" and typeof y is "string"

JavaScript is an object-oriented scripting language whereas Java is an object-oriented programming language.
JavaScript applications are run inside a web browser whereas Java applications are usually used in operating systems and virtual machines.
JavaScript needs compiler before running the application code but Java does not need compiler before running the application code.

No, we can't hoist function expression and arrow function because arrow function is derived from function expression.

Four ways to write a function

Statemnt: It is a group of operands and operator to perform a particular task.
let sum = a + b;
Here, a and b are two operands and + and = are operators, sum is a variable in which the result is assigned.
Experession:- It is a combination of one or more expression. It can be a variable or value or combination of variables or values with operators.
sum = a + 10;
In this statement, we have four expressions variable a, value 10, a+10 and sum= a + 10;

The full form of ECMA is European Computer Manufacturer's Association. It is the official name of javaScript
The name is used for language specification(version). For example, JavaScript has many specification or version like ECMAScript 5(2009), ECMAScript 6(2015), ECMAScript 7, ECMAScript 8, ECMAScript 9(2018)

Async/Await

Async-await functions are executed sequentially one after another in an easier way.

Async/Await function might throw an error when the value is returned.

Generators

Generator functions are executed with one output at a time by the generator’s yield by yield. The ‘value: X, done: Boolean’ is the output result of the Generator function.

Async-await

Async allows us to write promise based codes and a word “Async” before a function means one simple thing that function will always returns a promise and it is an Async function and work in asynchronous mode in the background. The keyword “await” before a function makes function await for a promise. It can be used only with Async function. Async is the latest version of Promise which means we can do all the things that we were doing in Promise and the best part of Async is that we can use one more feature with Async called await. Await is used inside the Async function. Async was introduced in ES8 in 2017 in which we don’t require to declare resolve and reject every time . Now, we can simply make a function and add Async just before the function declaration and it will return a promise. So, here we will use then and catch methods without defining resolve and reject which will reduce the code length and also complexity that we had when using in promises.

Fetch()

Fetch() method was introduced in ECMAScript 2015(ES6). It is the advance version of AJAX which allows to crude with server such as reading and fetching the data from server, updating, inserting and deleting the data from server. We can do the same with AJAX in jQuery and JavaScript . When we use AJAX in jQuery using $.ajax(); , $.get(); , $.post(); methods . It is easy to use due to less coding but we need to add to 50 to 100 KB file to use it as all the codes are inside this file and without it jQuery will not work, which loads every time when we run the jQuery codes which makes the application slow and when we use AJAX in JavaScript using XMLHTTPReuest method, we have to write too many codes. So, to overcome these issues fetch() method was introduced.

Fetch() Syntax:-
1.Fetch();
2.Fetch(file path or URL); file or URL can be text, ajax, php. Fetch returns promise so we will use then() call back function considering the promise is fulfilled.
3.Fetch(file/URL).then(); When we use then() call back function, we usually need to take a function to do the next work but here we will not do so as then() returns promise so we will take then()
4.Fetch(file/URL).then().then()
Feth(file/URL).then(function(response){return r esponse.data;}).then(function(result){console.log(result);})

Temporal Dead Zone is a behavior that occurs with variables declared using let and const keywords before they are initialized.
In another word, Temporal dead zone is the area where a varialbe is not accessible. <script> console.log(a); let aj = 10; </script> It will throw an error like Uncaught "ReferenceError: can't access lexical declaration 'aj' before initialization" which means we need to declare value of aj and then we need assign or initialize it and then only we can call the "aj". This happens because that In ES6, two new varialbes(let & const) were introduced which are block scope/variables where our hoising does not work like var keyword and this is why these two varialbes fall into temporal dead zone.

How to style current page/active link we are active on navbar?

Adding HTML

<ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link text-info" href="/">CSS</a> </li> <li class="nav-item"> <a class="nav-link text-info" href="php.html">PHP</a> </li> <li class="nav-item"> <a class="nav-link text-info" href="api.html">RestAPI</a> </li> </ul>

Adding CSS(attribute can be anything)

.nav-link[aria-current="page"]{ text-decoration: underline wavy yellow 1px; text-underline-offset:10px; }

Adding js

<script> let link1 = document.querySelectorAll('.nav-link'); console.log(link1); link1.forEach( link => { // console.log(link); // It will return all anchor tag like <a class="nav-link text-info" href="index.html"> // To get the href we will have to add link.href // console.log(link.href); //Now, we will get http://127.0.0.1:5500/index.html // console.log(link.href, window.location.href); // window.location.href will show the page 9 times as there are 9 links on which we click so we will // check if both are equal set attribute which has been added in Style.css if (link.href === window.location.href) { link.setAttribute('aria-current', 'page') } } ) </script>

Youtube Video Link

Throttling and Throttle function is a practice used in website to call a function after every milliseconds or any particular interval of time. In this function, the first click is executed Immediately.
Advantages:- It stops calling a function again and again. Suppose, we hava to send a request to the server on button click or want to search something on when we type in the input. So, when we enter 5 inputs, it will send 5 request to the server and make the website slow. So, we will use throttle function to avoid this issue and it will send the request only once and the second request after the interval we set. Throttle funtion has two parameters, First is the function that we will call and second is dealy(after how long we will reexecute the function) <script> var </script> It will throw an error like Uncaught "ReferenceError: can't access lexical declaration 'aj' before initialization" which means we need to declare value of aj and then we need assign or initialize it and then only we can call the "aj". This happens because that In ES6, two new varialbes(let & const) were introduced which are block scope/variables where our hoising does not work like var keyword and this is why these two varialbes fall into temporal dead zone.

It is a coding methodology/style/pattern that can convert the biggest code into a small code. It helps to make the code modular(Compatible) and reusable.

Since it well organize the code so it can be easily maintained and debugged. It is good to use this oop for your big website projects. Now a days, it is mostly used in javaScript frameworks like react js, vue js, node js, angular js etc. This oop is used in almost all high lavel progaramming languages. The syntax may be different but the concept is same for all the progaramming languages.

CLASS & OBJECT

Suppose, I have a blue print of a flat and a builder wants to make flats using the same blue prints. Since the blue print is the same for all the flats, so all the flates made by the builder will be the same/common. Here, Blueprint will the class and the houses made by the builder using the same blue prints will the object. Object will contain only those things that a class keeps, nothing will be extra in the object that class does not contain.
Object refers how the class is.
In OOP Concept, we group function and variable in a block called class.

Toita which is a car. Here, Toita is object and car is a class.
Car features like color, Engine, seats, AC, price are called properties in programming language and these properties linked to the class, car. Every class has its own properties.
The values of the properties may be different for different objects like toita and safari.
Like Toita color can be 4 but for Safari, it can be 5.
Toita engine can be 1200cc but for Safari, it can be 2700cc.

Class contains properties and methods.
properties are like variables like let a; let b; let c; declared inside the class. methods refer what your class can do and its working is defined in the methods or method is a function used to do the action like adding, substracting the variables. In methods, we can use only those properties I have declared.

How to declare class in javaScript

class myClass{ }

There are three types of methods in oops

OOPs PRINCIPAL

Use of constructor, super and prototype methods with pics

Note:- When we use two constructor methods in one class then we need to use super method in the child Constructor function as shown in the above image.

INHERITANCE IN DETAILS

Inheritance is a process where one class acquires properties and methods from another class.
The one receives the methods and properties is called child/sub/deried and the one one from it is received is called perent/super/base.
Note:- When we use two constructor methods in one class then we need to use super method in the child Constructor function.

In JavaScript, the event.preventDefault() method is used to prevent the default behavior of an element. For example: If you use it in a form element, it prevents it from submitting. If used in an anchor element, it prevents it from navigating. If used in a contextmenu, it prevents it from showing or displaying.
On the other hand, the event.stopPropagation() method is used to stop the propagation of an event or stop the event from occurring in the bubbling or capturing phase.

It is beeter to use debuger keyword when we have big files and so many errors because if we have big files, it becomes difficult to understand where the error is such as line number, error etc.

We use arrow function becuase it makes the length of the code shorter, we really don't require to use return keyword if we have signle statement or working with loop, we can also remove the parathesis in arrow function when when we have single parameter like (a) = a and third reason to use it, the concept of this keyword.

Follow the path for form events

C:\Users\pione\OneDrive\Desktop\FED\JAVASCRIPT\13. Javascript Form Event

Flex box is one-dimensional system (either in a column or a row). It is used to make one dimensional responsive layout without using position and float.

Defferences

The spread operator (...) unpacks the elements of an iterable object.
The rest parameter (...) packs the elements into an array. It actually collects all remaining arguments of a function into an array.
The rest parameters must be the last arguments of a function. However, the spread operator can be anywhere

Promises are used to handle asynchronous operations in JavaScript. Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code or call back hell. So, Promise was introduced in ES6 ( ECMAScript 2015). Promise object has four states -

  • Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  • Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
  • Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  • Settled - This state represents that the promise has been either rejected or fulfilled.
  • A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.
  • resolve is a function that will be called when the async operation has been successfully completed.
  • reject is a function that will be called, when the async operation fails or if some error occurs.

PROMISE.ALL

If all the promise is true then then call back function will execute and if any of the promises is false then catch call back will execute.

Syntax

Promise.all([p1, p2, p3]).then((result) => { console.log(result) }).catch((error) => { console.log(error) });
Here, p1, p2, p3 are three promises.

Why promises, call backs, asynce&awaite intoroduced

Find the output of the code

Map method is used to create a new array by adding, multiplying the values of an array.
It also used to make new array from the multidimentional objects by taking out the values. usuallY don't print it.
It has three parameters (value, i,array).
value is for value like in var a 1,2,3....,10 are values,
i is index and array means complete array.

A “mobile-first” approach involves designing a desktop site starting with the mobile version, which is then adapted to larger screens.
In another word, a mobile-first approach means building your website with your mobile users in mind, just to improve the mobile users’ experience on your site.
We shold follow Mobile first approach because 80% of the users will see your website on their mobile phones.

We can use regular_expression for email and other validations like mobile etc. because it reduces the legth of the code. We can visit a website called https://regex101.com/
Please visit the regex101
We need to take two forward slashes to implement regular_expression and inside it to validate letter from A to Z in capital letter and a to z in small letter we will take square bracket and write /[A-Z a-z]/
It will check capital and small letter values from A to Z. Now we have to validate @ such as pioneer25me@gmail.com So, we will write /[A-Z a-z]@/ but now I want there should be atleast one letter before @ and maximum can be anything so we will write /[A-Z a-z]{1, }@/ Note:- To valide any letter and special character we use square bracket like [] and any range like at least three letter we will us curly brackes {} and we also need to use cap symbol at begging and $ symbol at the end like / ^[A-Z a-z]{1, }@ $ /

Module is a feature introduced in ES6 that allows use to split the code of a main file of your project into different files. It is used when we have different things in our file such as variable, function, class etc. and I want to use just variable from that file then we will Export variable and import in a different file where I want to use it. It will well organize and maintaine the code and also reduce the loading time.

Module has two features or statement called Export and Import.

Export is used before any variable/fuction/class that we want to use in another file and to use the exported varialbe in different file we will use import keyword.

The CSS3 calc() function allows us to perform mathematical operations on property values. Instead of declaring, for example, static pixel values for an element's width, we can use calc() to specify that the width is the result of the addition of two or more numeric values.

Refer audio for more clarification

The float property of CSS positions an image to the right or left as needed, including text wrapping around it. All properties of elements used before it remain unchanged. 

Destructoring means breaking down a complex structure into a simpler parts. With the syntax of des we can easily extract the value of an array and object. It is used for the assigment and declaration of a variable.
<script> let x = [1, 2, "sarfraz"] const [first, second, third] = x; console.log(first); // 1 </script> <script> let user = { name: "sarfraz", age: 25 } let { name, age } = user; console.log(name); // sarfraz </script> <script> let user1 = { surname: "Mr", sex: Male } let { surname: s, sex: se } = user; console.log(s); // sarfraz console.log(se); // Male </script>

Reference Error:- We get this error when we call any variable or function not defined.

Type Error:- We know that in JavaScript every variable has different types, we have predefined types such string, number, bullian, charactor, float, integer. We get type error when we use any type not predefined.

The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a simple example:
The innerText property is used to write the simple text using JavaScript dynamically. Let's see a simple example:

<body> <div id="mylocation"></div> <script> document.getElementById('mylocation').innerHTML = "<h2>This is Sarfraz</h2>"; document.getElementById('mylocation').innerText = "This is Sarfraz"; </script> </body>

There are two types of comments in JavaScript.
1.Single Line Comment: It is represented by // (double forward slash)
2.Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here

Document : The document comes under the windows object and can also be considered as its property.
Window in JavaScript is a global object that holds the structure like variables, functions, location, historyetc.

Refer notes

Yes, JavaScript is a dynamically typed language and not statically.
Statically typed language is a language in which we have to define variable type or data type before initialization like var, let, or const when we assign any value like a =10;
In statically typed language if we write like a=10; the interpreter/compiler/translator will throw an error as they compiler is not so advanced but in dynamically typed language the interpreter will add the variable type if we miss as it is very advanced.
Since, the interpreter of JavaScript add the variable type before the code execution so we don’t get any error but programming languages like c, c++, java are statically typed language.

Constructor functions are used to create single objects or multiple objects with similar properties and methods. It is like a blueprint that can be reused for different objects. We don’t have to create different function for different objects again and again. It saves the time and coding length.
Example:
function Person(name,age,gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
var person1 = new Person("Vivek", 76, "male");
console.log(person1);
var person2 = new Person("Courtney", 34, "female");
console.log(person2);

<script> let arr = [1, 2, [[[3, 4]]], 5, [[6]], [7, 8], 9, 10]; let output = []; function flatten(arr) { for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { flatten(arr[i]); } else { output += arr[i]; } } return output; } console.log(flatten(arr)); </script>

Second Method

<script> const nested = [1, [[[2, 3]]], [4, 5, [6, 7], [[8, 9]]]] function flatten(arr) { const result = [] arr.forEach((i) => { if (Array.isArray(i)) { result.push(...flatten(i)) } else { result.push(i) } }) return result } x = flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9] console.log(x); </script>

How to fetch data, header or footer

<script> // note there should be <div class="footer1"></div> const foot = document.querySelector('.footer1') fetch('footer.html').then(res => res.text()).then(data => { foot.innerHTML = data }) </script>

We can retrieve a character from a certain index with the help of charAt() function method.

JavaScript was developed by Brendan Eich, who was a Netscape programmer. Brendan Eich developed this new scripting language in just ten days in the year September 1995. At the time of its launch, JavaScript was initially called Mocha. After that, it was called Live Script and later known as JavaScript.

<script> let obj = { id: "1", name: "user22", age: "26", work: "programmer" }; console.log(Object.keys(obj)); // [ "id", "name", "age", "work" ] console.log(Object.values(obj)); //  [ "1", "user22", "26", "programmer" ] console.log(Object.entries(obj)); // It will return the entries like Array(4) [ (2) […], (2) […], (2) […], (2) […] ] // 0: Array [ "id", "1" ] // 1: Array [ "name", "user22" ] // 2: Array [ "age", "26" ] // 3: Array [ "work", "programmer" ] </script>

Refer notes

Refer notes

1st way by assigning empty array

<script> let arr1 = [1, 2, 3, 4]; arry = [] console.log(arr1); // 0 </script>

2nd way by assigning array.length to zero

<script> let arr2 = [1, 2, 3, 4]; arry = [] console.log(arr2); // 0 </script>

3rd way by usig popping method

<script> let arry3 = [1, 2, 3, 4]; while (arry.length > 0) { arry.pop(); } console.log(arry3); </script> arry.pop() will remove 4 first and the remaining arry =[1,2,3] Since we have to remove even 1,2,3 as so we have taken while loop, which means keep on popping until arr.length is greater than 0

3rd way by usig popping method

<script> let arry4 = [1, 2, 3, 4, 5, 6]; // arry.splice(0, arry.length, "Aman", 9) arry.splice(0, arry4.length) console.log(arry4); </script> Here splice has 1st parmeter 0 means start from 0 index, second one is how many delete (arry.length) means jitna bhi length hai, third parmeter is new element you want to add.

Refer notes

<h1>Hello</h1> <script> document.querySelector("h1").innerHTML = "Hello, Sarfraz"; </script>

Here is the output :

Hello

<h1 style="color:blue">Hello</h1> <script> document.querySelector("h1").style.color = "red"; </script>

Here is the output : Hello will be red in color

</button onclick="show()">Display The Content </button> </button onclick="hide()">Hide The Content </button> <h1 style="display:none ;">Hello</h1> <script> function hide() { document.querySelector("h1").style.display = "none"; } function show() { document.querySelector("h1").style.display = "block"; } </script>

<div></div> <script> let y = "kjfadkjk" let x = document.getElementsByTagName("div").innerHTML = y; document.write(`${x} <br>`); </script>

<script> let num = 10;  // jo sir apne se aur 1 se katta hai prime number hat 1, 2, 3,5, 7 , 11, 13,17 etc. var isPrimeNumber = true; for (let i = 2; i < num; i++) { if (num % i == 0) { isPrimeNumber = false; } } if (isPrimeNumber == true) { document.write(`${num} is a Prime Number`); } else { document.write(`${num} is not a Prime Number or Composite Number`) } </script> <script> let Prime = [1, 3, 10, 5, 12]; for (var i = 0; i < Prime.length; i++) { if (Prime[i] % 2 == 0) { console.log(Prime[i], "is is not prime number") } else { console.log(Prime[i], "is prime number") } } </script>

<script> let num = 103;  // jo 2 se divide ho jaye wo even number hai 2, 4, 6, 8, 10,  etc. baki odd hai if (num % 2 == 0) { document.write(`${num} is even number`); } else { document.write(`${num} is odd number`); } </script> <script> let num = prompt("Enter Your Number"); if (num % 2 == 0) { document.querySelector('div').innerHTML = `${num} is even number` } else { document.querySelector('div').innerHTML = `${num} is odd number` } </script>

<script> let num = 346;  // jo 2 se divide ho jaye wo even number hai 2, 4, 6, 8, 10,  etc. baki odd hai let x = num % 10; document.write(x + "<br>");  // 6 document.write(parseInt(num / 10) + "<br>");  //34 let y = 34 % 10; document.write(y + "<br>");  // 4 let z = parseInt(34 / 10); document.write(z + "<br>");  // 3 document.write(x + y + z); </script>  <h1>Some Of The Digits</h1> <script> let number = 346; var str = number.toString(); let sum = 0; for (var i = 0; i < str.length; i++) { sum = sum + parseInt(str.charAt(i));  //parseInt to convert the decimal or point to integer or non point } document.write(sum); </script>

1st Method Using for loop

<script> arry = [10, 5, 0, 90, 398, 900, 200, 99, 10, 500]; let sortedArry = (arry.sort((a, b) => (a - b))); let n = sortedArry.length; let max = -Infinity; let smax = -Infinity; let tmax = -Infinity; for (i = 0; i < n; i++) { if (sortedArry[i] > max) { tmax = smax; smax = max; max = sortedArry[i]; // make sure the sequence as it is to get the correct output } } console.log(max, smax, tmax); </script>

2nd Method Using double for loop

<script> arry = [10, 5, 0, 90, 200, 99, 10]; let n = arry.length; let max = -Infinity; // -Infinity is the lowest value , we take it do take as the lowest value. as smallest as possible let smax = -Infinity; let tmax = -Infinity; for (i = 0; i < n; i++) { max = Math.max(max, arry[i]); // Here first parameter max means maximum value in arry[i] taken as 2nd parameter } for (i = 0; i < n; i++) { if (arry[i] < max) { smax = Math.max(smax, arry[i]); // Here first parameter smax means second maximum value in arry[i] taken as 2nd parameter } } for (i = 0; i < n; i++) { if (arry[i] < smax) { tmax = Math.max(tmax, arry[i]); // Here third parameter tmax means third maximum value in arry[i] taken as 2nd parameter } } console.log(max); console.log(smax); console.log(tmax); </script>

3rd Method Using Array Method

<script> let arry = [10, 5, 0, 90, 100, 99]; let decreasedOrder = arry.sort((a, b) => a - b); let increasedOrder = arry.sort((a, b) => a - b).reverse(); console.log(increasedOrder[0]); // to get largest number console.log(increasedOrder[1])// to get the second largest number </script>

<script> for (i = 1; i <= 6; i++) { for (j = 1; j <= i; j++) { document.write('*'); } document.write("<br>"); } </script>

Here is the output :

<script> for (i = 1; i <= 6; i++) { for (j = i; j <= 6; j++) { document.write('*'); } document.write("<br>"); } </script>

Here is the output :

var arr = [1, 2, 3];

<h3>To remove between two strings</h3> <script> var str = 'some string' function removeWhiteSpace(value) { let newVal = value.replace(" ", ""); return newVal; } let output = removeWhiteSpace(str); document.write(output); </script> <h3>To remove all whitespaces</h3> <script> var str = 'some string is dancing is playing' function removeWhiteSpace(value) { let newVal = value.replace(/ /g, ""); return newVal; } let output = removeWhiteSpace(str); document.write(output); </script>

Here is the output :

Using for loop

<script> let arry = [2, 4, 5, 6]; let sum = 0; for (i = 0; i < arry.length; i++) { sum = sum + arry[i]; } document.write(sum); </script>

Using Reducer

<script> let arry = [2, 4, 5, 6]; let sum = arry.reduce(function (a, b) { return a + b }) document.write(sum); </script>

Division Using Reducer

<script> let arry = [2, 4, 8, 6]; let sum = arry.reduce((a, b) => (a + b)); let division = sum / arry.length; document.write(division); </script>

Division Using for loop

<script> let arry = [2, 4, 8, 6]; let sum = 0; for (i = 0; i < arry.length; i++) { sum = sum + arry[i]; divide = sum / arry.length; } document.write(divide); </script>

Here is the output :

Using if else if

<script> let nu1 = 50, nu2 = 12, nu3 = 20; if (nu1 > nu2 && nu1 > nu3) { document.write('num1 is greatest'); } else if (nu2 > nu1 && nu2 > nu3) { document.write('num2 is greatest'); } else { document.write('num3 is greatest'); } </script>

Using Switch

<script> let nu1 = 50, nu2 = 52, nu3 = 20; switch (true) { case (nu1 > nu2 && nu1 > nu3): document.write('num1 is greatest'); break; case (nu2 > nu1 && nu2 > nu3): document.write('num2 is greatest'); break; default: document.write('num3 is greatest'); } </script>

Here is the output :

<script> var arr = [1, 2, 3, 10, 4, 5, 6, 7, 8, 9]; let max = arr[0]; for (i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i] } } document.write(max); </script>

Here is the output :

<script> let arry = [4, 6, 0, 7, 0, 8]; let output = arry.filter((item) => item > 0); let zero = arry.length - output.length let result = [...new Array(zero).fill(0), ...output] document.write(result); </script>

Here is the output :

<script> let arr = [3, 4, 5, 6] arr.foo = "Hi" // 3,4,5,6,Hi for (let i in arr) { console.log(i); // 0, 1, 2, 3, foo // because for .. in returns keys document.write(i); // 0123go } for (let i of arr) { console.log(i); // 3, 4, 5, 6 // because for .. in returns values. } </script> <script> let arr = [1, 2, 3, 4, 5] let obj = { ...arr }; console.log(obj); // Object { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 } </script> <script> const promise = new Promise((res) => res(2)); promise.then((v) => { console.log(v); // 2 return v * 2 }).then((v) => { console.log(v); // 2*2 = 4 return v * 2 }).finally((v) => { console.log(v); // It will return undifined because it wil not receive any value if it would be then instead of finally then 8 would be returned. return 0; }).then((v) => { console.log(v); }); // the output will be 2 then 4 then 8 then undefined ( finally will be executed at last) </script>

Event Delegation:- It is a pattern/way which is used to handle the event properly. Suppose, we have one parent and it has 5 children and we have add the same event on all the children. So, instead of adding an add event listener to each children, we will add event to the parent element becuase if we add on the parent the children will have the same event automatically due to event capturing which heppens from top to bottom and it will reduce the length of the code, impove the readibility of the code and hence it will improve the performance of the website.
We can add an event listener to the parent element and using e.target or .target property, we can target the each child.

Synchronous and Asynchronous

Asynchronous is anything that does not run in the main thread application but Synchronous does.
Promises and callbacks are the asynchronous code.
Fetching API is also an example of an asynchronous code.
Please note that JavaScript executes synchronous code first and then asynchronous code

Example of Synchronous program

let x = 10; x += 1; console.log(x); // This is synchronuous because second line of code is executed after first line of code.

Example of Asynchronous program

setTimeout(() => console.log("Hello"), 1000);

How to remove 2 and 3 in give array?

let arr = [1, 2, 3, 4, 5]; // First Method console.log(arr.splice(arr.indexOf(2),1)); // Array [ 2 ] console.log(arr); // Array(4) [ 1, 3, 4, 5 ] console.log(arr.splice(arr.indexOf(4),1)); // Array [ 4 ] console.log(arr); // Array(3) [ 1, 3, 5 ] // 2nd Method // console.log(arr.splice(1, 3, 3)); // Array(3) [ 2, 3, 4 ] // console.log(arr); // Array(3) [ 1, 3, 5 ] , we have removed 2 and 4