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.
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.
Use of shallow copy
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);
Deep Copy
Now, deep copy comes into the picture when we have nested object.
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();
Limitations of Deep copy
-
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
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
Difference between for in and for of loop?
Difference Among filter/Map/Reduce/ForEach
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
Step 2
Step 3
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.
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.
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
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.
like set timeout(function(){try{blabla}catch(error){console.lot("error")}}, 1000)
var, let and const
let and const were introduced in ES6 to overcome some of the Limitations of var varaiable.
We can't specify or declare const and let variabls twice in the same scope.
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 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.
Four ways to write a function
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 functions are executed sequentially one after another in an easier way.
Async/Await function might throw an error when the value is returned.
GeneratorsGenerator 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);})
In another word, Temporal dead zone is the area where a varialbe is not accessible.
How to style current page/active link we are active on navbar?
Adding HTML
Adding CSS(attribute can be anything)
Adding js
Youtube Video Link
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)
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.
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.
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.
Follow the path for form events
C:\Users\pione\OneDrive\Desktop\FED\JAVASCRIPT\13. Javascript Form Event
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.
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.
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.
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.
Refer audio for more clarification
h2>
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:
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
Window in JavaScript is a global object that holds the structure like variables, functions, location, historyetc.
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.
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);
Second Method
How to fetch data, header or footer
1st way by assigning empty array
2nd way by assigning array.length to zero
3rd way by usig popping method
3rd way by usig popping method
Hello
Here is the output :
Hello
Hello
Here is the output : Hello will be red in color
Hello
Some Of The Digits
1st Method Using for loop
2nd Method Using double for loop
3rd Method Using Array Method
Here is the output :
Here is the output :
To remove between two strings
To remove all whitespaces
Here is the output :
Using for loop
Using Reducer
Division Using Reducer
Division Using for loop
Here is the output :
Using if else if
Using Switch
Here is the output :
Here is the output :
Here is the output :
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
Example of Asynchronous program