-
Notifications
You must be signed in to change notification settings - Fork 1
JavaScript
- Define: JavaScript is a High-level, Interpreter, single thread language.
- Character: scripting & interpreter language, dynamic typing, prototype base object oriented programming.
- Usage: primary used client side, enhanced web page, server side web dev with node.js or mobile app.
- Differ with JAVA: Main used standalone application, Mobile app(android), multi-thread, statically typing language.
-
Primitive:
- string : It represent a single or double quote,
- number : It represent Number decimal or without decimal,
- boolean : Logical entity true or false value,
- null : It represent a non-existent or invalid value,
- undefine: variable declared but not assigned,
- bigint : It ac store larger number
- symbol : It is used to store an asynchronous and unique value,
-
Non-Primitive: Its store multiple or complex values,
- function, methods, or
- Array these is all about object.
Hoisting is the default behavior of javascript, where all the variable and function declarations are moved on top.
Note : variable declarations are hoisted, not initialize/assign.
- var is a functional(global) scope, it re-declare variable & reassign value,
- let is a block scope, Allows re-assign value but not re-declare within the same scope.
- const is a block scope, it cannot be reassigned/declaration.
-
==compare values, -
===compare both value or datatype.
NuN : It is represent the Not-a-Number value, typeof of NaN will return a Number.
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
Compare Operator : == is compare value, === compare both value & Datatype.
- Duplicate argument are not allowed.
- Not allowed to create global variable.
- To define 'strick mode'at the start of the script.
Object is a collection of data & properties with key/ value format.
- Object Literal,
- Constructor Object
- Built-in Object
-
Arrow function (ES6+): Do not have their own
thiscontext, Especially useful for short, one-line expressions. -
Callback Functions: Function is passed as an argument to another function and executed later. Commonly used to asynchronous operation such as data fetching, file reading, event handling
-
Higher-Order Functions: That take one or more functions as arguments to return new functions. Abstract common patterns or functional programming enable operation
map, filter...etc. -
Closures function: closure is inner function access to the outer function scope, and also return.
-
Immediately Invoked Function Expressions (IIFE): Avoiding Global Scope Pollution or create Private Scopes
-
Currying Functions: Function is transformed into a sequence of functions, each taking a single argument.
-
Generator Functions (ES6+): Generator functions allow you to define an iterative algorithm by writing a function that can be paused and resumed. They use the
yieldkeyword to produce a sequence of values.
function* countUp() {
let count = 0;
while (true) {
yield count++;
}
}
const counter = countUp();
console.log(counter.next().value); // Output: 0
console.log(counter.next().value); // Output: 1- Maintain
lexical scopeonthisavailable in arrow function. - Not allow to create
constructionfunction using arrow function. - Not allow to used
argumentsobject in arrow function or - Not allow
newkeyword to create instances in arrow function
- The
thiskeywords refer to the object that the function is a property of. - The value of
thiskeyword will always depends on the object that is invoking the function.
call() execute the function immediately. It takes individual arguments
apply() execute the function immediately. It takes arguments as an array
bind() returns a new function with the correct context set for later execution.
The exec() and test() methods in JavaScript when working with regular expressions:
- The
exec()method searches for a specified match within a string using a regular expression. it returns anarrayotherwise returnnull. Syntax:regularExpressionObj.exec(string) - The
test()method checks whether a specified pattern exists in a string. it return true or false. Syntax:regularExpressionObj.test(string)
- Every object has a prototype properties.
- It objects inherit properties and methods from their prototypes.
- Prototypes create a chain, allowing for shared behavior among objects,
Object.prototype.
new Set(), add(), delete(), has(), size(), clear()
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
It is commonly used for handling asynchronous operations, such as fetching data from a server, reading a file, or making an HTTP request. A Promise has three states: pending, fulfilled, or rejected.
- Parallel Requests :
const [result1, result2] = await Promise.all([promise1, promise2]) - Sequential Requests: chaining promise using
.then().then().catch()
// creating a promise:
const myPromise = new Promise((resolve, reject) => {
const data = false;
if (!data) {
resolve('operation complete success');
} else {
reject('operation failed');
}
});
// handle a promise with then() or catch()
myPromise.then((result) => console.log(result)).catch((err) => console.log(err));
// Handle multiple promise
const promise1 = fetchData();
const promise2 = fetchData();
Promise.all([promise1, promise2]).then(([result1, result2]) => console.log(result1, result2));
// Handle using with Async / Await:
const fetchDataAsync = async () => {
try {
const result = await fetchData();
} catch (error) {
console.log(error);
}
};- The event loop constantly checks two things: the
call stackand theevent queue. - If the call stack is empty, the event loop takes the first event from the queue and pushes it onto the call stack, making it the current operation.
- The event loop continues this process, ensuring that the call stack is always empty before processing the next event from the queue.
Web API: (Separate Data Execute)
- Job Queue:(Micro tasks - first run)
- process.nextTick(),
- Promise callback,
- async function,
- Queue MicroTask,
- Task Queue:(Macro tasks - second run)
- setTimeout()
- setInterval()
- setImmediate()
-
Shallow copy: : Share reference.
- object.assign({}, object)
- spread operator {...object}
- Object.prototype.slice()
-
Deep copy: Independent copy of the entries object hierarchy.
- JASON.pase(JASON.stringify(object))
- structuredClone().
- lodash libraries used.
- When an HTML file is loaded into a browser, JavaScript interacts with the DOM created by the browser.
- JavaScript can’t directly understand HTML tags but interprets them as objects in the DOM.
- DOM allows dynamic updates, responsiveness, and interactivity in web pages.
It is a programming interface for HTML (HyperText Markup Language) and XML (Extensible Markup Language) documents.
| Sr. | HTML | XML |
|---|---|---|
| 1 | Displaying data on web pages. | XML is designed for storing and transporting data. |
| 2 | Static in nature. | Dynamic in nature. |
| 3 | Not case-sensitive. | case-sensitive. |
| 4 | Can ignore small errors. | Not allow small errors. |
| 5 | File extensions are .html or .htm
|
File extension is .xml
|
| sr. | client-side | server-side |
|---|---|---|
| Execution Location | Runs on the client machine, which is the browser. |
Runs on the server that serves web pages |
| Purpose | Enhances and manipulates web pages and client browsers
|
Provides back-end access to databases, file systems, and servers
|
| Technologies | HTML, CSS, and JavaScript. | PHP, Python, Java, and Ruby. |
-
In summary:
- Client-side JavaScript runs in the user’s browser, enhancing web pages.
- Server-side JavaScript executes on the web server, providing back-end functionality and dynamic content
Event Propagation: In DOM which events traverse through the hierarchy of elements in the document. There are three phases.
-
Bubbling Phase: The event bubbles up from the target element to the root element.( child to parent).
-
Capturing phase: - The event travels from the root element down to the target element. ( parent to child).
-
stopPropagation(): Stop continue to propagate up or down events but ancestor trigger event.
-
immediatePropagation(): Only trigger the current event element
-
preventDefault(): Stop the browser's default action
-
Event Delegation: It concept of event propagation, used to handle events for multiple child elements.
-
Local Storage: Object allows you to save key/value pairs in the browser. Larger storage capacity, persists across browser sessions, not sent to the server automatically (5-10 MB per domain).
-
Session Storage: Similar to localStorage but with a shorter lifespan, cleared when the session ends
-
Cookies: Small storage capacity, can have an expiration date, sent to the server with every request. (up to 4KB).
document.cookie = 'name=adarsh';
- CRP involves HTML parsing and DOM construct, CSS parsing, layout calculations, and painting.
- Optimizing the Render Tree, CSS, and JavaScript is essential for faster rendering.
- Minification, compression, and image optimization contribute to improved performance.
- Minification and Compression: Remove unnecessary whitespace, comments, and rename variables
- Bundle and Code Splitting: Bundle multiple JavaScript files into a single file.
- lazy loading: Use lazy loading for images, scripts, and other assets. Delay the loading of non-essential resources until they are needed.
-
Async and Defer Attributes:
asyncallows scripts to be downloaded asynchronously without blocking HTML parsing.deferensures scripts are executed in order after HTML parsing. - Critical Path Rendering: Minimize the number of render-blocking resources, such as CSS and JavaScript files.
- Optimized Images: Compress and optimize images to reduce their file size. Employ lazy loading for images to defer loading until they are about to be displayed
- Service Workers: Implement service workers to enable background tasks, caching, and offline capabilities.
- Reduce DOM Manipulation: Minimize direct DOM manipulation, as it can be a performance bottleneck. Use efficient DOM manipulation techniques, such as document fragment or virtual DOM, to optimize updates.
-
Throttle and Debounce:
Throttlingensures a function is not executed more than once in a specified time period, whiledebouncingdelays the execution until a specified time has passed since the last invocation. - Optimize Network Requests: Use a content delivery network (CDN) to serve static assets from servers located closer to the user.
- Memory Management: Be mindful of memory leaks by cleaning up event listeners, removing references to unused objects, and avoiding unnecessary global variables.
-
Preconnect and Prefetch: Use the tag with
rel="preconnect"to initiate early connections to third-party domains. Utilize withrel="prefetch"to fetch and cache resources that will be needed in the future. - Performance Monitoring: Use performance monitoring tools and browser developer tools to identify bottlenecks and areas for improvement.
- Caching: Explore service workers for client-side caching and offline capabilities.
CORS (Cross-Origin Resource Sharing): Web browsers to restrict web pages from making requests to a different domain than the one that served the web page.
- Access-Control-Allow-Origin: https://allowed-origin.com
- Access-Control-Allow-Methods: GET, POST, PUT, DELETE
- Access-Control-Allow-Headers: Content-Type, Authorization
- Access-Control-Allow-Credentials: true
- Access-Control-Expose-Headers: Content-Length, X-Content-Range
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer token',
},
body: JSON.stringify({ name: 'Jon', age: 30 }),
})
.then((res) => res.json())
.catch((err) => console.error(err));