├── README.md ├── a-Intro ├── 1-Intro.md ├── 2-StrictMode.md ├── 3-DOM-BOM.md ├── 4-Window-Document-object.md ├── 5-Js-Engine.md ├── 6-Code-Execution.md ├── 7-Event-Loop.md └── 8-Questions.md ├── b-DataTypes ├── 1-Data-Types.md ├── 2-Operators.md ├── 3-Coercion.md ├── 4-Error-Types.md └── 5-Questions.md ├── c-Scope ├── 1-Scope.md ├── 2-Shadowing.md └── 3-Questions.md ├── d-Hoisting ├── 1-Hoisting.md ├── 2-Var-Let-Const.md └── 3-Questions.md ├── e-Functions ├── 1-Function.md ├── 2-Closures.md ├── 3-Currying.md └── 4-Questions.md ├── f-Objects ├── 1-Object-Definations.md ├── 2-Object-Properties.md ├── 3-Object-Methods.md ├── 4-Object-Display.md ├── 5-Getter-Setter.md ├── 6-Constructor-Function.md ├── 7-Prototype.md └── 8-Prototype-Chaining.md ├── g-Classes ├── 1-Classes.md ├── 2-Getter-Setter.md ├── 3-Inheritance.md ├── 4-Static-Methods.md └── 5-Private-Methods.md ├── h-OOPS └── 1-OOP.md ├── i-AdvanceFunctions ├── Call-Apply-Bind.md └── Polyfills.md ├── j-ArrayMethods ├── HOF.md └── Polyfills.md ├── k-StringMerhods └── index.md ├── l-Promises └── index.md ├── m-AsyncAwait └── index.md ├── n-Generators-Iterations └── index.md ├── o-Collections └── index.md ├── p-Browser ├── BOM │ ├── o-setTimeout │ │ └── index.md │ ├── s-EventPropagation │ │ └── index.md │ ├── t-Storage │ │ └── index.md │ └── xcvcv.md ├── DOM │ └── xcvcv.md └── Web-APIs │ └── xcvcv.md ├── q-ECMAScript └── xcvcv.md ├── r-Optimisation ├── q-Debouncing │ └── index.md └── r-Throttling │ └── index.md ├── x-ErrorHandling └── index.md ├── y-Debugging └── index.md └── z-ImportantQuestions ├── 1-TheoryBased.md └── 2-OutputBased.md /README.md: -------------------------------------------------------------------------------- 1 | 2 | ![maxresdefault](https://user-images.githubusercontent.com/100460788/235359553-2a4bae94-5565-4d74-82ff-42e73f7995e2.jpg) 3 | 4 | # JavaScript Interview Questions & Answers 5 | 6 | - Click :star: if you like the project and follow [@PiyushAgrawal](https://www.linkedin.com/in/piyush-agrawal-me/) for more updates. 7 | - From basic to advanced: Test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview. I update this repo regularly with new questions. 8 | - A complete JavaScript interview handbook/series containing all the topics from basic level to advance. This Series consists of 45+ important topics with related questions and answers. 9 | --- 10 | 11 | ### Topics covered in the series 12 | 13 | | No. | Topic | 14 | | --- | -------------------------------- | 15 | | 1 | Introduction to Javascript | 16 | | 2 | Advantages of JS | 17 | | 3 | Disadvantages of JS | 18 | | 4 | Client and Server Javascript | 19 | | 5 | Strict mode in JS | 20 | | 6 | DOM and BOM | 21 | | 7 | Window and Document Object | 22 | | 8 | JS Engine | 23 | | 9 | Code Execution in JS | 24 | | 10 | Event Loop | 25 | | 11 | Data Types | 26 | | 12 | Operators | 27 | | 13 | Coercion and Type conversion | 28 | | 14 | Types of Errors | 29 | | 15 | Scope | 30 | | 16 | Shadowing | 31 | | 17 | Hoisting | 32 | | 18 | VAR vs LET vs CONST | 33 | | 19 | Functions | 34 | | 20 | Parameters vs Arguments | 35 | | 21 | Spread vs Rest Operator | 36 | | 22 | Higher order functions | 37 | | 23 | IIFE | 38 | | 24 | Closure | 39 | | 25 | Currying | 40 | | 26 | Infinite Currying | 41 | | 27 | Callbacks | 42 | | 28 | This Keyword | 43 | | 29 | Objects | 44 | | 30 | Delete Keyword | 45 | | 31 | Constructor Function | 46 | | 32 | Getter Setter | 47 | | 33 | Prototype | 48 | | 34 | Prototype Chaining | 49 | | 35 | Classes | 50 | | 36 | Inheritance | 51 | | 37 | Static Keyword | 52 | | 38 | Private Methods | 53 | | 39 | OOPS | 54 | | 41 | Encapsulation | 55 | | 42 | Abstraction | 56 | | 43 | Polymorphism | 57 | | 44 | Polyfills | 58 | | 45 | Deep copy and shallow copy | 59 | | 46 | Promises | 60 | | 47 | Async Await | 61 | | 48 | Event Propagation | 62 | | 49 | SetTimeout and SetInterval | 63 | | 50 | SetTimeout and SetInterval | 64 | | 51 | Cookies and Local storage | 65 | | 52 | Debouncing | 66 | | 53 | Throttling | 67 | | 54 | Set , Map , weakSet , weakMap | 68 | | 55 | Debugger | 69 | | 56 | Debugger | 70 | | 57 | Important output based questions | 71 | | 58 | Important theory questions | 72 | 73 | --- 74 | 75 | **[⬆ Back to Top](#topics-covered-in-the-series)** 76 | 77 | ## Disclaimer | Note : 78 | 79 | The topics and questions provided in this repository are the summary of all the frequently asked questions across numerous companies. We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus on memorizing all of them. 80 | 81 | Good luck with your interview 😊 82 | 83 | --- 84 | -------------------------------------------------------------------------------- /a-Intro/1-Intro.md: -------------------------------------------------------------------------------- 1 | ![a](https://user-images.githubusercontent.com/100460788/235360048-86873f6d-81bd-46ae-9537-13f650822233.jpg) 2 | 3 | ## What is Javascript? 4 | 5 | `JavaScript` is a lightweight, cross-platform, `single-threaded`, and interpreted compiled programming language which is also known as the scripting language for webpages. It is well-known for the development of web pages, and many non-browser environments also use it. JavaScript is `a weakly typed language` (dynamically typed). JavaScript can be used for Client-side developments as well as Server-side developments. JavaScript is both an imperative and declarative type of language. JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of language elements like operators, control structures, and statements. 6 | 7 | - JavaScript, created by `Brendan Eich` in `1995`, is one of the most widely used web development languages. 8 | - It was designed to build dynamic web pages at first. A script is a JS program that may be added to the HTML of any web page. When the page loads, these scripts execute automatically. 9 | - A language that was originally designed to build dynamic web pages may now be run on the server and on almost any device that has the JavaScript Engine installed. 10 | - After HTML and CSS, JavaScript is the third biggest web technology. 11 | - JavaScript is a scripting language that may be used to construct online and mobile apps, web servers, games, and more. 12 | - JavaScript is an object-oriented programming language that is used to generate websites and applications. It was created with the intention of being used in a browser. 13 | -Even today, the server-side version of JavaScript known as Node.js may be used to create online and mobile apps, real-time applications, online streaming applications, and videogames. Javascript frameworks, often known as inbuilt libraries, may be used to construct desktop and mobile programs. 14 | 15 | ## JavaScript is Used for 16 | 17 | - `Creating Interactive Websites`: JavaScript is used to make web pages dynamic and interactive. It means using JavaScript, we can change the web page content and styles dynamically. 18 | - `Building Applications`: JavaScript is used to make web and mobile applications. To build web and mobile apps, we can use the most popular JavaScript frameworks like – ReactJS, React Native, Node.js etc. 19 | - `Web Servers`: We can make robust server applications using JavaScript. To be precise we use JavaScript frameworks like Node.js and Express.js to build these servers. 20 | - `Game Development`: JavaSCript can be used to design Browser games. In JavaScript, lots of game engines are available that provide frameworks for building games. 21 | 22 | ## Advantages of JavaScript 23 | 24 | - `Less server interaction` − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. 25 | - `Immediate feedback to the visitors` − They don't have to wait for a page reload to see if they have forgotten to enter something. 26 | - `Increased interactivity` − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. 27 | - `Richer interfaces` − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. 28 | 29 | ## Limitations of JavaScript 30 | - `Security risks`: JavaScript can be used to fetch data using AJAX or by manipulating tags that load data such as `, , `. The 71 | 72 | 73 | 74 | ``` 75 | 76 | ### `External JavaScript` : 77 | We can create the file with a .js extension and paste the JS code inside of it. After creating the file, add this file in 90 | 91 | 92 | 93 | 94 | 95 | 96 | ``` 97 | 98 | ### Next Topic - [Strict Mode](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/2-StrictMode.md) 99 | -------------------------------------------------------------------------------- /a-Intro/2-StrictMode.md: -------------------------------------------------------------------------------- 1 | ### What is strict mode in js? 2 | 3 | `Strict Mode` was a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict”; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript. 4 | 5 | #### Benefits of using `‘use strict’` : 6 | 7 | Strict mode makes several changes to normal JavaScript semantics. 8 | 9 | - Strict mode eliminates some JavaScript silent errors by changing them to throw errors. 10 | - Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode. 11 | - Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript. 12 | - It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object). 13 | - It disables features that are confusing or poorly thought out. 14 | - Strict mode makes it easier to write “secure” JavaScript. 15 | 16 | ### Strict Mode in Variable 17 | 18 | In strict mode, using a variable without declaring it throws an error. 19 | 20 | `Note: You need to declare strict mode at the beginning of the program. If you declare strict mode below some code, it won't work.` 21 | 22 | For example, 23 | 24 | ```ts 25 | console.log("some code"); 26 | 27 | // 'use strict' is ignored 28 | // must be at the top 29 | "use strict"; 30 | 31 | x = 21; // does not throw an error 32 | ``` 33 | 34 | Correct code, 35 | 36 | ```ts 37 | 'use strict'; 38 | 39 | // Error 40 | myVariable = 9; 41 | ``` 42 | 43 | ### Strict Mode in Function 44 | 45 | You can also use strict mode inside a function. For example, 46 | 47 | ```ts 48 | myVariable = 9; 49 | console.log(myVariable); // 9 50 | 51 | function hello() { 52 | 53 | // applicable only for this function 54 | 'use strict'; 55 | 56 | string = 'hello'; // throws an error 57 | } 58 | 59 | hello(); 60 | ``` 61 | 62 | If you use `'use strict'` ; inside a function, the code inside the function will be in strict mode. 63 | 64 | In the above program, `'use strict' ;` is used inside the `hello()` function. Hence, the strict mode is applicable only inside the function. 65 | 66 | ### Things Not Allowed in Strict Mode 67 | 68 | 1. Undeclared variable is not allowed. 69 | 70 | ```ts 71 | 'use strict'; 72 | 73 | a = 'hello'; // throws an error 74 | ``` 75 | 76 | 2. Undeclared objects are not allowed. 77 | 78 | ```ts 79 | 'use strict'; 80 | 81 | person = {name: 'Carla', age: 25}; // throws an error 82 | ``` 83 | 84 | 3. Deleting an object is not allowed. 85 | 86 | ```ts 87 | 'use strict'; 88 | 89 | let person = {name: 'Carla'}; 90 | 91 | delete person; // throws an error 92 | ``` 93 | 94 | 4. Duplicating a parameter name is not allowed. 95 | 96 | ```ts 97 | "use strict"; 98 | 99 | function hello(p1, p1) { console.log('hello')}; // throws an error 100 | 101 | hello(); 102 | ``` 103 | 104 | 5. Assigning to a non-writable property is not allowed. 105 | 106 | ```ts 107 | 'use strict'; 108 | 109 | let obj1 = {}; 110 | 111 | Object.defineProperty(obj1, 'x', { value: 42, writable: false }); 112 | 113 | // assignment to a non-writable property 114 | obj1.x = 9; // throws an error 115 | ``` 116 | 117 | 6. Assigning to a getter-only property is not allowed. 118 | 119 | ```ts 120 | 'use strict'; 121 | 122 | let obj2 = { get x() { return 17; } }; 123 | 124 | // assignment to a getter-only property 125 | obj2.x = 5; // throws an error 126 | ``` 127 | 128 | 7. Assigning to a new property on a non-extensible object is not allowed. 129 | 130 | ```ts 131 | 'use strict'; 132 | 133 | let obj = {}; 134 | Object.preventExtensions(obj); 135 | 136 | // Assignment to a new property on a non-extensible object 137 | obj.newValue = 'new value'; // throws an error 138 | ``` 139 | 140 | 8. Octal syntax is not allowed. 141 | 142 | ```ts 143 | 'use strict'; 144 | 145 | let a = 010; // throws an error 146 | ``` 147 | 148 | 9. The variable name arguments and eval are not allowed. 149 | 150 | ```ts 151 | 'use strict'; 152 | 153 | let arguments = 'hello'; // throws an error 154 | 155 | let eval = 44; 156 | ``` 157 | 158 | 10. You cannot also use these reserved keywords in strict mode. 159 | 160 | `implements` `interface` `let` `package` `private` `protected` `public` `static` `yield` 161 | 162 | ### For more details - [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) 163 | ### Next Topic - [DOM/BOM](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/3-DOM-BOM.md) 164 | -------------------------------------------------------------------------------- /a-Intro/3-DOM-BOM.md: -------------------------------------------------------------------------------- 1 | ### Difference between BOM and DOM in JavaScript 2 | 3 | ![Screenshot_1](https://user-images.githubusercontent.com/100460788/233662372-0e25db06-fdf6-4ec1-9c2d-ca44fd382269.png) 4 | 5 | ### 1. Browser Object Model (BOM) 6 | 7 | BOM is a Browser Object Model, which is a window object supported by all browsers representing a browser window consisting of navigator, history, screen, location and document objects which are children of windows. BOM can function to check an event from windows with window.addEventListener and can perform manipulation using `window.innerHeight` and `window.innerWidth` . 8 | 9 | There are several methods that we can use from the BOM, including `alert()` , `prompt()` , and `console` . 10 | 11 | #### Method alert() 12 | 13 | The `alert()` method is one of the BOM methods used to display warnings or information. We can use an example as below: 14 | 15 | ``` 16 | window.alert("Hello"); 17 | ``` 18 | 19 | or 20 | 21 | ``` 22 | alert("Hello"); 23 | ``` 24 | 25 | ![aAugu](https://user-images.githubusercontent.com/100460788/233665060-8e98e70b-6cbe-477c-8379-688871f76230.png) 26 | 27 | #### Method prompt() 28 | 29 | The `prompt()` method is used to display a browser dialog and can be filled in by the user. The prompt() dialog will return a string value from the user when performing sting input in the prompt() dialog. For example, as shown below: 30 | 31 | ``` 32 | let message = prompt('Your Name?');![0_w1t2cLUc70xr93wC](https://user-images.githubusercontent.com/100460788/233667507-655431b1-f675-424f-9e04-4c40ec7e2db2.png) 33 | 34 | ``` 35 | 36 | ![0_vdDzPDRkls9eQLZY](https://user-images.githubusercontent.com/100460788/233665460-925d318f-8628-4f08-902c-f6dcacd5265c.png) 37 | 38 | #### Console methods 39 | 40 | The `console method` is a very useful method for a frontend developer, because the console method can be used to eliminate bugs in the code that has been created. Example console code below: 41 | 42 | ``` 43 | console.log('Code with me'); 44 | console.warn('Code with me'); 45 | console.info('Code with me'); 46 | console.error('Code with me'); 47 | ``` 48 | 49 | ![console-sidebar](https://user-images.githubusercontent.com/100460788/233666355-e7050424-3a2e-44f3-9386-1a6527e8e98f.png) 50 | 51 | ### 2. Document Object Model (DOM) 52 | 53 | DOM is a collection of functions and attributes / data that we use to create JavaScript programs that we can call APIs (Application Programming Interface). DOM can be used in HTML, XM and SVG. DOM is not only used for JavaScript programming but can be used for other programming as well. 54 | Inside the document object, we will find the functions and attributes that we can use to manipulate the HTML document. 55 | 56 | DOM tree objects can be accessed and manipulated with the help of any programming language since it is cross-platform and language-independent. Typically, we manipulate the DOM tree with the help of JavaScript and jQuery using multiple ways of accessing elements by their class names, ID, or the name of the element. 57 | 58 | DOM has a structure in the form of a tree we can call DOMtree. 59 | 60 | ![dom](https://user-images.githubusercontent.com/100460788/233667146-15e2efc5-20c4-48f9-9cc8-cf947c3bab5a.png) 61 | 62 | Take a look at the structure of this DOMtree, we will know the structure of the HTML code that we will manipulate using the DOM. Examples are below: 63 | 64 | ``` 65 | document.head; 66 | document.body; 67 | document.title.length; 68 | ``` 69 | 70 | Output in console will look like: 71 | 72 | ![0_w1t2cLUc70xr93wC](https://user-images.githubusercontent.com/100460788/233667576-763a42c0-7222-48ad-a021-73fc546bfd26.png) 73 | 74 | #### And we can access more specific HTML elements by using some of the functions below. 75 | 76 | - `getElementById()` function to select elements based on attributes id. 77 | - `getElementByName()` function to select elements based on attributes name. 78 | - `getElementByClassName()` function to select elements based on attributes class. 79 | - `getElementByTagName()` function to select elements by tag name. 80 | - `getElementByTagNameNS()` function to select elements by tag name. 81 | - `querySelector()` function to select elements based on query. 82 | - `querySelectorAll()` function to select elements based on query. 83 | - for more understanding - [Docs](https://www.dotnettricks.com/learn/javascript/dom-bom) 84 | 85 | ### Next Topic - [Window and document object](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/4-Window-Document-object.md) 86 | -------------------------------------------------------------------------------- /a-Intro/4-Window-Document-object.md: -------------------------------------------------------------------------------- 1 | ## Difference between Window, Document and Screen in JavaScript 2 | 3 | Window object and Document object often look alike and confusing ?? 4 | 5 | If yes , Then its time to resolve it. Lets Go. 6 | 7 | Here I am assuming that you already know about DOM and BOW. 8 | 9 | ![Screenshot_2](https://user-images.githubusercontent.com/100460788/233690248-4cb7fe7b-1a27-4fc0-a0b7-ca30783796c6.png) 10 | 11 | ### Window Vs Document 12 | 13 | `Window object` : It is the top most object and outermost element of the object hierarchy as shown in Figure 1. 14 | 15 | `Document object` : Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. Using document object, JavaScript can modify, add and delete the HTML elements, attributes CSS styles in the page 16 | 17 | - The window object represents a window/tab containing a DOM document where as document object is property of window object that points to the DOM document loaded in that window. 18 | - You can access a document object either using `window.document` property or using `document` object directly as window is global object. In the below example, title is the property of document object. 19 | 20 | ![Screenshot_6](https://user-images.githubusercontent.com/100460788/233692021-45ed5935-111a-4c75-956d-7da04128d9d3.png) 21 | 22 | - The other major difference is that both window object and document object have properties and methods. Few method names are same in both objects but with different behavior. In the below example `window.open()` opens a new tab or window and `document.open()` creates a blank document within the window. 23 | 24 | ![Screenshot_7](https://user-images.githubusercontent.com/100460788/233692034-b1bb14cb-4a55-48ee-9e7e-4206e4730ebf.png) 25 | 26 | ### Screen 27 | 28 | `Screen` is the window property that holds information of browser screen. It refers to screen object associated with that window object. Used to display screen `width`, `height`, `colorDepth`, `pixelDepth` etc 29 | 30 | - Similar to document screen can be accessed either by `window.screen` or `screen` object directly. Screen object doesn't have any methods as in window and document objects. 31 | 32 | ![Screenshot_8](https://user-images.githubusercontent.com/100460788/233692050-5769c038-b3c1-41cd-9d36-a2c08fc450ca.png) 33 | 34 | ### For more details - [Docs](https://www.geeksforgeeks.org/differences-between-document-and-window-objects/) 35 | 36 | ### Next Topic - [JS Engine](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/5-Js-Engine.md) 37 | -------------------------------------------------------------------------------- /a-Intro/5-Js-Engine.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Engine: All you need to know 2 | 3 | ### What is JavaScript Engine? 4 | 5 | - JavaScript is not understandable by computer but the only browser understands JavaScript. So, we need a program to convert our JavaScript program into computer-understandable language. A JavaScript engine is a computer program that executes JavaScript code and converts it into computer understandable language. 6 | - The JavaScript Engine is an open-source computer program whose responsibility is to execute/run JavaScript. There are a lot of steps involved in executing the JavaScript Engine, but essentially executing JavaScript code is what an engine does. All modern browsers have their own version of the JavaScript Engine. But Google's V8 Engine is the most popular JavaScript Engine. 7 | - An elementary JavaScript engine includes a baseline compiler whose job is to compile JavaScript source code into an intermediate representation (IR) called the bytecode and feeds this bytecode to the interpreter. The interpreter takes this bytecode and converts it to the machine code, which is ultimately run on the machine’s hardware (CPU). 8 | - ECMAScript Standards are being followed by the JavaScript engines to execute the code on the browser. The role of these standards is to give a definition and specification to JavaScript engines on how they should work and what features they should have. 9 | 10 | ### Here is a list of JavaScript Engines for major Internet browsers: 11 | 12 | - `V8` JavaScript Engine developed by Google for Chrome 13 | - `SpiderMonkey` The JavaScript Engine used by Mozilla Firefox 14 | - `JavaScriptCore` Developed by Apple for Safari 15 | - `Rhino` Managed by Mozilla Foundation for Firefox 16 | - `Chakra` A JavaScript Engine for Microsoft Edge 17 | - `JerryScript` A JavaScript Engine employed for the Internet of Things (IoT). 18 | 19 | ### What are the components of JavaScript Engine? 20 | 21 | ![626f6337e11f082ebf1e4d70_kinse98CDmvflgPshHgOomUovkd1DbAyoRkyhbGwP7pJKAGcslZjRYMmuoXqnC9A2L67alEIoxsL_R7z4EC7QzXFjrHq3ScHKgadxaE0ODBTAFh_b6fmcS6wik9PCMfC4LtWy_WL](https://user-images.githubusercontent.com/100460788/233707130-5b34901f-be37-4673-a142-3a3cc901e645.png) 22 | 23 | ### The engine consists of two main elements: 24 | 25 | `Memory Heap` 26 | 27 | Heap is a large unstructured data structure that stores all the dynamic data like function definitions, objects, arrays, etc. The memory heap is where the memory allocation happens, it is a location in memory where memory may be allocated at random access. Individual data elements distributed on the heap are typically released in ways that are asynchronous from one another. The memory occupied in the heap continues to exist even after JavaScript code execution has been completed and is later removed by the JavaScript Garbage Collector if needed. 28 | 29 | `Call Stack` 30 | 31 | The Call stack is a data structure that functions on the Last In First Out (LIFO) principle. The call stack stores the execution context or code for each function. It is defined as an object which stores local variables, functions, and objects of the codes and how would they appear on the screen. Primitive values like int, bool, etc are stored inside the call stack. While function definitions and objects are not stored inside the call stack, they are stored inside the memory heap. The call stack just has the reference or memory address of where these function definitions and objects are stored and would appear on the search engine. 32 | 33 | ### How does the JavaScript engine work? 34 | 35 | ![javascript_journey](https://user-images.githubusercontent.com/100460788/233707653-5cb6c00e-d49d-4803-9f94-5cec7aaa49f1.png) 36 | 37 | - The JavaScript engine works on the JavaScript source code and puts it and then executes the compilation to binary instructions (machine code) that are easily understandable by the CPU. A JavaScript engine generally consists of a baseline compiler that works on the compilation of the code in the form of intermediate representation (IR) /byte code and then passes the byte code to the interpreter. 38 | 39 | - Later, the interpreter takes this byte code and makes the conversion into machine code, which will further run this code on the hardware of the machine to generate the results. The assignment of a baseline compiler is to perform the compilation of the code as fast as possible and to generate less-optimized byte codes. 40 | 41 | - A JavaScript engine can make an intuition about the data types of the variables and perform the generation of much better code that increases the effectiveness of the system and user experience at large. 42 | 43 | - The JavaScript engine can also work on gathering, and profiling data on the execution of the code and analyzing the speed of the code. Codes that run slow or take time to process are commonly known as "Hot" codes as they get burned in the CPU. System designers have the option to further optimize and replace machine code that has already been optimized to avoid burns. 44 | 45 | ### What are different JavaScript engines? 46 | 47 | `1. V8` 48 | 49 | It is a JavaScript engine developed by the Chromium Project for Google Chrome and Chromium web browsers which can run standalone or be embedded into any C++ application. V8 uses its own parser and generates an abstract syntax tree, used for generating bytecode by Ignition using the internal V8 bytecode format. V8 provides an edge as it allows JavaScript to run much faster, which improves users' experience of the web and the overall functionality of the system. 50 | 51 | `2. Chakra` 52 | 53 | Chakra is a JavaScript engine developed by Microsoft used for Microsoft Internet Explorer. It is proprietary software with distinctive features. Chakra can JIT compile scripts on a separate CPU core parallel to the web browser. Firstly, Chakra Core reads through the Javascript code syntax and parses it to generate its AST. After the AST is generated, the code is passed to the byte code generator to profile the byte codes. Chakra works a bit differently from V8, as V8 has a decision process that decides whether a piece of code should be profiled and optimized or should be turned into byte code. 54 | 55 | `3. Spider Monkey` 56 | 57 | SpiderMonkey is the first JavaScript engine, written by Brendan Eich at Netscape Communications, released as open-source, and is currently maintained and used by the Mozilla Foundation. It contains a JavaScript compiler and interpreter along with several service programs. It is written in C++, Rust and JavaScript can be embedded into C++ and Rust projects and run as a stand-alone shell. 58 | 59 | ### For more details - [Docs](https://www.geeksforgeeks.org/introduction-to-javascript-engines/) 60 | 61 | ### Next Topic - [Code execution in JS](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/6-Code-Execution.md) 62 | -------------------------------------------------------------------------------- /a-Intro/6-Code-Execution.md: -------------------------------------------------------------------------------- 1 | ## How javascript code is executed? 2 | 3 | JavaScript is a `synchronous` and `single-threaded` language. To know behind the scene of how JavaScript code gets executed internally, we have to know something called `Execution Context` and its role in the execution of JavaScript code. 4 | 5 | ### Execution Context: 6 | 7 | Everything in JavaScript is wrapped inside Execution Context, which is an abstract concept (can be treated as a container) that holds the whole information about the environment within which the current JavaScript code is being executed. 8 | 9 | Now, an Execution Context has two components and JavaScript code gets executed in two phases. 10 | 11 | - `Memory Allocation Phase` : 12 | In this phase, all the functions and variables of the JavaScript code get stored as a key-value pair inside the memory component of the execution context. In the case of a function, JavaScript copied the whole function into the memory block but in the case of variables, it assigns undefined as a placeholder. 13 | 14 | - `Code Execution Phase` : 15 | In this phase, the JavaScript code is executed one line at a time inside the Code Component (also known as the Thread of execution) of Execution Context. 16 | Let’s see the whole process through an example. 17 | 18 | ```ts 19 | var number = 2; 20 | function Square (n) { 21 | var res = n * n; 22 | return res; 23 | } 24 | var newNumber = Square(3); 25 | ``` 26 | 27 | In the above JavaScript code, there are two variables named `number` and `newNumber` and one function named `Square` which is returning the square of the number. So when we run this program, Global Execution Context is created. 28 | 29 | So, in the Memory Allocation phase, the memory will be allocated for these variables and functions like this. 30 | 31 | ![Capture-660x298](https://user-images.githubusercontent.com/100460788/233766891-0db4ddaf-71c6-4b81-830a-e2e5ec2268ae.jpg) 32 | 33 | In the Code Execution Phase, JavaScript being a single thread language again runs through the code line by line and updates the values of function and variables which are stored in the Memory Allocation Phase in the Memory Component. 34 | 35 | So in the code execution phase, whenever a new function is called, a new Execution Context is created. So, every time a function is invoked in the Code Component, a new Execution Context is created inside the previous global execution context. 36 | 37 | ![Capture1-660x301](https://user-images.githubusercontent.com/100460788/233766898-a7f6b14a-2760-4192-b0b5-d337f3d5fa74.jpg) 38 | 39 | So again, before the memory allocation is completed in the Memory Component of the new Execution Context. Then, in the Code Execution Phase of the newly created Execution Context, the global Execution Context will look like the following. 40 | 41 | ![Capture2-660x276](https://user-images.githubusercontent.com/100460788/233766903-71083931-d101-4c68-abc4-62d700caa68b.jpg) 42 | 43 | As we can see, the values are assigned in the memory component after executing the code line by line, i.e. number: 2, res: 4, newNumber: 4. 44 | 45 | After the return statement of the invoked function, the returned value is assigned in place of undefined in the memory allocation of the previous execution context. After returning the value, the new execution context (temporary) gets completely deleted. Whenever the execution encounters the return statement, It gives the control back to the execution context where the function was invoked. 46 | 47 | ![Capture4-660x303](https://user-images.githubusercontent.com/100460788/233766914-c636bb83-439c-4667-b275-f5a6eeefe15e.jpg) 48 | 49 | After executing the first function call when we call the function again, JavaScript creates again another temporary context where the same procedure repeats accordingly (memory execution and code execution). In the end, the global execution context gets deleted just like child execution contexts. The whole execution context for the instance of that function will be deleted 50 | 51 | ## Call Stack: 52 | 53 | When a program starts execution JavaScript pushes the whole program as global context into a stack which is known as Call Stack and continues execution. Whenever JavaScript executes a new context and just follows the same process and pushes to the stack. When the context finishes, JavaScript just pops the top of the stack accordingly. 54 | 55 | ![Capture5](https://user-images.githubusercontent.com/100460788/233767149-6fac737b-b482-4abb-b5a4-44116753e02d.png) 56 | 57 | When JavaScript completes the execution of the entire code, the Global Execution Context gets deleted and popped out from the Call Stack making the Call stack empty. 58 | 59 | ### For more details - [Docs](https://www.freecodecamp.org/news/how-javascript-works-behind-the-scene-javascript-execution-context/#:~:text=There%20are%20two%20types%20of,representing%20the%20function's%20local%20scope.) 60 | 61 | ### Next Topic - [Event Loop](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/7-Event-Loop.md) 62 | -------------------------------------------------------------------------------- /a-Intro/7-Event-Loop.md: -------------------------------------------------------------------------------- 1 | ## What is an event loop in JavaScript? 2 | 3 | ![javascript-event-loop](https://user-images.githubusercontent.com/100460788/233776906-dc41f5b2-8242-4ca2-94b8-b9756100822e.png) 4 | 5 | The `event loop` is the secret behind JavaScript’s asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading. Let’s take a look at what happens on the back-end. 6 | 7 | ### Call stack 8 | 9 | The call stack is responsible for keeping track of all the operations in line to be executed. Whenever a function is finished, it is popped from the stack. 10 | 11 | ![Screenshot_10](https://user-images.githubusercontent.com/100460788/233777065-e1dcb823-ff10-493a-a709-764bcfadd940.png) 12 | 13 | The event queue is responsible for sending new functions to the stack for processing. It follows the queue data structure to maintain the correct sequence in which all operations should be sent for execution. 14 | 15 | ![Screenshot_11](https://user-images.githubusercontent.com/100460788/233777083-433a6106-4872-4ea2-a8ca-b067d24adc6d.png) 16 | 17 | Whenever an async function is called, it is sent to a browser API. These are APIs built into the browser. Based on the command received from the call stack, the API starts its own single-threaded operation. 18 | 19 | An example of this is the setTimeout method. When a setTimeout operation is processed in the stack, it is sent to the corresponding API which waits till the specified time to send this operation back in for processing. 20 | 21 | Where does it send the operation? The event queue. Hence, we have a cyclic system for running async operations in JavaScript. The language itself is single-threaded, but the browser APIs act as separate threads. 22 | 23 | The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed. 24 | 25 | ![Screenshot_12](https://user-images.githubusercontent.com/100460788/233777102-2d859d08-1f69-4045-a7e0-19a843a9a2e0.png) 26 | 27 | ### For more details - [Docs](https://www.geeksforgeeks.org/what-is-an-event-loop-in-javascript/) 28 | 29 | ### Next Topic - [Interview Questions](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/a-Intro/8-Questions.md) 30 | -------------------------------------------------------------------------------- /a-Intro/8-Questions.md: -------------------------------------------------------------------------------- 1 | ### Q1. What is the difference between Java & JavaScript? 2 | 3 | | Java | Javascript | 4 | | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | 5 | | JavaScript is an object-oriented scripting language. | Java is an object-oriented programming language. | 6 | | JavaScript applications are meant to run inside a web browser. | Java applications are generally made for use in operating systems and virtual machines. | 7 | | JavaScript does not need compilation before running the application code. | Java code needs to be compiled. | 8 | 9 | ### Q2. What are the features of JavaScript? 10 | 11 | - It is a lightweight, interpreted programming language. 12 | - It is designed for creating network-centric applications. 13 | - It is complementary to and integrated with Java. 14 | - It is an open and cross-platform scripting language. 15 | 16 | ### Q3. Is JavaScript a case-sensitive language? 17 | 18 | Yes, JavaScript is a case sensitive language. The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. 19 | 20 | ### Q4. List out the different ways an HTML element can be accessed in a JavaScript code. 21 | 22 | Here are the list of ways an HTML element can be accessed in a Javascript code: 23 | 24 | - `getElementById(‘idname’)` : Gets an element by its ID name 25 | - `getElementsByClass(‘classname’)` : Gets all the elements that have the given classname. 26 | - `getElementsByTagName(‘tagname’)` : Gets all the elements that have the given tag name. 27 | - `querySelector()` : This function takes css style selector and returns the first selected element. 28 | 29 | ### Q5. In how many ways a JavaScript code can be involved in an HTML file? 30 | 31 | There are 3 different ways in which a JavaScript code can be involved in an HTML file: 32 | 33 | - Inline 34 | - Internal 35 | - External 36 | 37 | ### Q6. What is the ‘Strict’ mode in JavaScript and how can it be enabled? 38 | 39 | Strict mode is a way to introduce better error-checking into your code. 40 | When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible. 41 | You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function. 42 | 43 | ### Q7. What is a prompt box in JavaScript? 44 | 45 | A prompt box is a box which allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. 46 | 47 | ### Q8. Who developed JavaScript, and what was the first name of JavaScript? 48 | 49 | 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. 50 | 51 | ### Q9. Difference between Client side JavaScript and Server side JavaScript? 52 | 53 | - `Client-side JavaScript` comprises the basic language and predefined objects which are relevant to running JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML pages. The browser interprets this script at runtime. 54 | - `Server-side JavaScript` also resembles client-side JavaScript. It has a relevant JavaScript which is to run in a server. The server-side JavaScript are deployed only after compilation. 55 | 56 | ### Q10. Is javascript a statically typed or a dynamically typed language? 57 | 58 | JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type. 59 | 60 | 61 | 62 | ### Next Topic - [Data Types In JS](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/b-DataTypes) 63 | 64 | -------------------------------------------------------------------------------- /b-DataTypes/1-Data-Types.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_1](https://user-images.githubusercontent.com/100460788/235360399-6fc85acd-b35e-4b94-9ec8-196c63ef1e66.png) 2 | 3 | ## JavaScript Data Types 4 | 5 | Data types are basically types of data that can be used and manipulated in a program. A variable in JavaScript can contain any data. This means that a variable at one time can be a number and at another be a string. 6 | 7 | The latest ECMAScript standard defines eight data types Out of which seven data types are `Primitive` and complex or `Non-Primitive`. 8 | 9 | ### Primitive Data Types : 10 | 11 | The predefined data types provided by JavaScript language are known as primitive data types. Primitive data types are also known as in-built data types. 12 | 13 | - `Number` : JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare different numeric values. 14 | - `String` : JavaScript Strings are similar to sentences. They are made up of a list of characters, which is essentially just an “array of characters, like “Hello Everyone” etc. 15 | - `Boolean` : Represent a logical entity and can have two values: true or false. 16 | - `Null` : This type has only one value that is null. 17 | - `Undefined` : A variable that has not been assigned a value is undefined. 18 | - `Symbol` : Symbols return unique identifiers that can be used to add unique property keys to an object that won’t collide with keys of any other code that might add to the object. 19 | - `BigInt` : BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1. 20 | 21 | ### Non-Primitive Data Types : 22 | 23 | The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is also known as derived data types or reference data types. 24 | 25 | - `Object`: It is the most important data type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles. `Arrays` and `Functions` in JavaScript belong to the ‘object’ data type. 26 | 27 | ## Primitive Data Types 28 | 29 | ### 1. Number 30 | 31 | - A number data type can be an integer, a floating point value, an exponential value, a ‘NaN’ or a ‘Infinity’. 32 | 33 | ```ts 34 | let num = 2; // integer 35 | let num2 = 1.3; // floating point number 36 | let num3 = Infinity; // Infinity 37 | let c = 10e4; // an exponential value which evaluates to 10*10000 38 | ``` 39 | 40 | - If a number is divided by 0, the resulting value is `infinity`. 41 | 42 | ```ts 43 | 5/0; // results in infinity 44 | The type of infinity is a number 45 | typeof(infinity); // returns number 46 | ``` 47 | 48 | - A `NaN` results when we try to perform an operation on a number with a non-numeric value 49 | 50 | ```ts 51 | ‘hi’ * 5; // returns NaN 52 | typeof(NaN); // returns a number 53 | ``` 54 | 55 | ### 2. String 56 | 57 | The string data type in JavaScript can be any group of characters enclosed by a single or double-quotes or by backticks. 58 | 59 | ```ts 60 | let str = "Good morning !"; 61 | let str2 = 'Single quotes works fine'; 62 | let str3 = `Hey ${str}`; // output will be "Hey Good morning !" 63 | ``` 64 | 65 | There’s no difference between ‘single’ and “double” quotes in javascript. Backticks provide extra functionality as with their help of them we can embed variables inside them. 66 | 67 | ### 3. Boolean 68 | 69 | The boolean data type has only two values, `true` and `false`. It is mostly used to check a logical condition. Thus Booleans are logical data types which can be used for comparison of two variables or to check a condition. The true and false implies a ‘yes’ for ‘true’ and a ‘no’ . 70 | 71 | Let’s see an example of comparison statement: 72 | 73 | ```ts 74 | var a=5; 75 | var b=6; 76 | console.log(a==b) // returns false 77 | console.log(a!=b) // returns true 78 | ``` 79 | 80 | When we check the data type of ‘true’ or ‘false’ using typeof operator, it returns a boolean. 81 | 82 | ```ts 83 | typeof(true) // returns boolean 84 | typeof(false) // returns boolean 85 | ``` 86 | 87 | ### 4. Undefined 88 | 89 | `Undefined` data type means a variable that is not defined. The variable is declared but doesn’t contain any value. 90 | 91 | ```ts 92 | var a; 93 | console.log(a); // This will return undefined. 94 | ``` 95 | 96 | ### 5. Null 97 | 98 | The null in JavaScript is a data type that is represented by only one value, the ‘null’ itself. A null value means no value. 99 | 100 | Something like this: 101 | 102 | ```ts 103 | var a = null; 104 | console.log(a); // This returns null 105 | ``` 106 | 107 | If we check the data type of a using the typeof operator, we get: 108 | 109 | ```ts 110 | typeof(a); // This returns object 111 | ``` 112 | 113 | This means the type of a null value is an object, not null. This is a known issue in JavaScript since its first release. 114 | 115 | ### 6. BigInt 116 | 117 | BigInt: BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1. The largest number that JavaScript can reliably represent with the Number primitive is 253-1, which is represented by the MAX_SAFE_INTEGER constant. 118 | 119 | ```ts 120 | var bigBin = BigInt("0b1010101001010101001111111111111111"); 121 | // 11430854655n 122 | console.log(bigBin); 123 | ``` 124 | 125 | ### 7. Symbol: 126 | 127 | Symbols are new primitive built-in object types introduced as part of ES6. Symbols return unique identifiers that can be used to add unique property keys to an object that won’t collide with keys of any other code that might add to the object. They are used as object properties that cannot be recreated. It basically helps us to enable encapsulation or information hiding. 128 | 129 | ```ts 130 | let symbol1 = Symbol("Geeks") 131 | let symbol2 = Symbol("Geeks") 132 | 133 | // Each time Symbol() method is used to create new global Symbol 134 | console.log(symbol1 == symbol2); // False 135 | ``` 136 | 137 | ## Non-Primitive Data Types 138 | 139 | ### 1. Object 140 | 141 | An object in JavaScript contains key-value pairs in its address. 142 | 143 | We can create objects in multiple ways. One is by making use of figure brackets {…} with an optional list of properties. The properties of an object are in the form of ‘key: value’ pair. Another way is to make use of the ‘new’ keyword. An empty Object can be created using the given below syntax. 144 | 145 | ```ts 146 | let obj = new Object(); // "object constructor" syntax 147 | let obj = {}; // "object literal" syntax 148 | ``` 149 | 150 | When we check the value of obj using the typeof operator, it returns an object. 151 | 152 | ```ts 153 | typeof (obj) // will return the data type ‘object’. 154 | ``` 155 | 156 | ### 2. Array 157 | 158 | An array in JavaScript is an object data type. An array contains more than one value with a numerical index, where the index starts from 0. Thus it holds its value in a key-value pair. 159 | 160 | ```ts 161 | var arr1= [1, 2, 3]; 162 | ``` 163 | 164 | ```ts 165 | arr1[0] =4; 166 | console.log(arr1) // This will return the array [4, 2, 3] 167 | typeof (arr1) // will return the data type ‘object’. 168 | ``` 169 | 170 | The array ‘arr1’ refers to the address in memory which contains the value [4, 2, 3]. 171 | 172 | ### 3. Function 173 | 174 | JavaScript doesn’t have a function data type but when we find the data type of a function using the typeof operator, we find that it returns a function. This is because a function is an object in JavaScript. Ideally the data type of a function should return an object but instead, it returns a function. This is an error in JavaScript. 175 | 176 | Let’s define a function named a: 177 | 178 | ```ts 179 | function a(){ } 180 | ``` 181 | 182 | Now let’s find the data type of a by using the typeof operator: 183 | 184 | ```ts 185 | typeof(a); // This will return data type function 186 | ``` 187 | 188 | ### Next Topic - [Operators in js](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/b-DataTypes/2-Operators.md) 189 | -------------------------------------------------------------------------------- /b-DataTypes/2-Operators.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Operators 2 | 3 | JavaScript operators operate the operands (values and variables), these are `symbols` that are used to manipulate a certain value or `operand`. Operators are used to performing specific `mathematical` and `logical` computations on operands. 4 | 5 | ### There are various operators supported by JavaScript. 6 | 7 | - JS Arithmetic Operators 8 | - JS Assignment Operators 9 | - JS Comparison Operators 10 | - JS Logical Operators 11 | - JS Bitwise Operators 12 | - JS Ternary Operators 13 | - JS typeof Operator 14 | 15 | ### 1. JavaScript Arithmetic Operators 16 | 17 | Arithmetic operators are used to perform `arithmetic calculations`. 18 | 19 | | Operator | Name | Example | 20 | | -------- | --------------------------- | -------------- | 21 | | `+` | Addition | `x + y` | 22 | | `-` | Subtraction | `x - y` | 23 | | `*` | Multiplication | `x * y` | 24 | | `/` | Division | `x / y` | 25 | | `%` | Reminder | `x % y` | 26 | | `++` | Increment (increments by 1) | `++x` or `x++` | 27 | | `--` | Decrement (decrements by 1) | `--x` or `x--` | 28 | | `**` | Exponentiation (Power) | `x ** y` | 29 | | `+a` | Unary | `+x` | 30 | | `-a` | Negation | `-x` | 31 | 32 | Example: In this example we will use all arithmetic operators. 33 | 34 | ```ts 35 | // Addition Operator 36 | let a = 1 + 2 37 | console.log(a); 38 | 39 | // Subtraction Operator 40 | let b = 10 - 7 41 | console.log(b); 42 | 43 | // Multiplication Operator 44 | let c = 3 * 3 45 | console.log(c); 46 | 47 | // Division Operator 48 | let d = 1 / 2 49 | console.log(d); 50 | 51 | // Modulas Operator 52 | let e = 9 % 5 53 | console.log(e) 54 | 55 | // Exponentian Operator 56 | let f = 2 ** 3 57 | console.log(f) 58 | 59 | // Increament Operator 60 | var g = 2; 61 | g1 = g++; 62 | console.log(g) 63 | 64 | // Decrement Operator 65 | var h = 2; 66 | h1 = h--; 67 | console.log(h) 68 | 69 | // Unary plus Operator 70 | var i = 3; 71 | i1 = +i; 72 | console.log(i1) 73 | 74 | // Negation Operator 75 | var j = 3; 76 | j1 = -j; 77 | console.log(j1) 78 | ``` 79 | 80 | Output : 81 | 82 | ```ts 83 | 3 84 | 3 85 | 9 86 | 0.5 87 | 4 88 | 8 89 | 3 90 | 1 91 | 3 92 | -3 93 | ``` 94 | 95 | ### 2. JavaScript Assignment Operators 96 | 97 | `Assignment operators` are used to `assign` values to variables. 98 | 99 | | Operator | Name | Example | 100 | | -------- | ------------------------- | -------------------------- | 101 | | `=` | Assugnment operator | `Y = 7` | 102 | | `+=` | Addition assignment | `Y += 1 gives Y = Y + 1` | 103 | | `-=` | Subtraction assignment | `Y -= 1 gives Y = Y - 1` | 104 | | `*=` | Multiplication assignment | `Y *= 1 gives Y = Y * 1` | 105 | | `/=` | Division assignment | `Y /= 1 gives Y = Y / 1` | 106 | | `%=` | Remainder assignment | `Y %= 1 gives Y = Y % 1` | 107 | | `**=` | Exponentiation Assignment | `Y **= 1 gives Y = Y ** 1` | 108 | 109 | Example: In this example we will use all assignment operators. 110 | 111 | ```ts 112 | // Assignment Operator 113 | let a = 2; 114 | console.log(a); 115 | 116 | // Addition Assignment Operator 117 | a += 1 118 | console.log(a); 119 | 120 | // Subtraction Assignment Operator 121 | a -= 1 122 | console.log(a); 123 | 124 | // Multiplication Assignment 125 | a *= 2 126 | console.log(a); 127 | 128 | // Division Assignment Operator 129 | a /= 2; 130 | console.log(a); 131 | 132 | // Modulus Assignment Operator 133 | a %= 2 134 | console.log(a); 135 | 136 | // Exponential Assignment Operator 137 | a **= 2 138 | console.log(a); 139 | ``` 140 | 141 | Output : 142 | 143 | ```ts 144 | 2 145 | 3 146 | 1 147 | 4 148 | 1 149 | 0 150 | 4 151 | ``` 152 | 153 | ### 3. JavaScript Comparison Operators 154 | 155 | `Comparison operators` compare two values and return a boolean value, either `true` or `false` . 156 | 157 | | Operator | Description | Example | 158 | | -------- | ------------------------------------------------------------------------------------------------ | --------- | 159 | | `==` | `Equal to` : returns true if the operands are equal | `x == y` | 160 | | `!=` | `Not equal to` : returns true if the operands are not equal | `x != y` | 161 | | `===` | `Strict equal to` : true if the operands are equal and of the same type | `x === y` | 162 | | `!==` | `Strict not equal to` : true if the operands are equal but of different type or not equal at all | `x !== y` | 163 | | `>` | `Greater than` : true if left operand is greater than the right operand | `x > y` | 164 | | `>=` | `Greater than or equal to` : true if left operand is greater than or equal to the right operand | `x >= y` | 165 | | `<` | `Less than` : true if the left operand is less than the right operand | `x < y` | 166 | | `<=` | `Less than or equal to` : true if the left operand is less than or equal to the right operand | `x <= y` | 167 | 168 | Example: In this example, we will use all comparison operators. 169 | 170 | ```ts 171 | // Assigning values 172 | let val1 = 5; 173 | let val2 = 5; 174 | 175 | // Equality Operator 176 | console.log(val1 == val2); 177 | 178 | // Strict equality Operator 179 | console.log(val1 === val2); 180 | 181 | // Inequality Operator 182 | console.log(val1 != val2); 183 | 184 | // Strict Inequality Operator 185 | console.log(val1 !== val2); 186 | 187 | // Greater than Operator 188 | console.log(val1 > val2); 189 | 190 | // Greater than or equal Operator 191 | console.log(val1 >= val2); 192 | 193 | // Less than Operator 194 | console.log(val1 < val2); 195 | 196 | // Less than or equal Operator 197 | console.log(val1 <= val2); 198 | ``` 199 | 200 | Output: 201 | 202 | ```ts 203 | true 204 | true 205 | false 206 | false 207 | false 208 | true 209 | false 210 | true 211 | ``` 212 | 213 | ### 4. JavaScript Logical Operators 214 | 215 | `Logical operators` perform logical operations and return a boolean value, either `true` or `false` . 216 | 217 | | Operator | Description | Example | 218 | | -------- | -------------------------------------------------------------------------------------- | -------- | 219 | | `&&` | `Logical AND` : true if both the operands are true, else returns false | `x && y` | 220 | | `ll` | `Logical OR` : true if either of the operands is true; returns false if both are false | `x ll y` | 221 | | `!` | `Logical NOT` : true if the operand is false and vice-versa. | `!x` | 222 | 223 | Example: In this example, we will use all logical operators. 224 | 225 | ```ts 226 | // logical AND 227 | console.log(true && true); // prints true 228 | console.log(true && false); // prints false 229 | 230 | // logical OR 231 | console.log(true || false); // prints true 232 | console.log(false || false); // prints false 233 | 234 | // logical NOT 235 | console.log(!true); // prints false 236 | console.log(!false); // prints true 237 | ``` 238 | 239 | ### 5. JavaScript Bitwise Operator 240 | 241 | The `bitwise operator` in JavaScript is used to convert the number to a `32-bit` binary number and perform the bitwise operation. The number is converted back to the `64-bit` number after the result. 242 | 243 | | Operators | Name | Example | 244 | | --------- | ---------------------------- | --------- | 245 | | `&` | Bitwise AND | `x & y` | 246 | | `l` | Bitwise OR | `x l y` | 247 | | `^` | Bitwise XOR | `x ^ y` | 248 | | `~` | Bitwise NOT | `~x` | 249 | | `<<` | Left shift | `x << y` | 250 | | `>>` | Sign-propagating right shift | `x >> y` | 251 | | `>>>` | Zero-fill right shift | `x >>> y` | 252 | 253 | Bitwise operator in detail - [Link](https://www.programiz.com/javascript/bitwise-operators) 254 | 255 | ### 6. JavaScript Ternary Operator 256 | 257 | The `ternary operator` has three operands. It is the simplified operator of `if/else` . 258 | 259 | Example: In this example, we will use the ternary operator. 260 | 261 | ```ts 262 | // Assigning values 263 | let marks = 40 264 | 265 | // Ternary Operator 266 | let result = (marks > 30) ? "Pass" : "Fail" ; 267 | 268 | console.log(result); 269 | ``` 270 | 271 | Output: 272 | 273 | ```ts 274 | Pass 275 | ``` 276 | 277 | ### 7. JavaScript typeof Operator 278 | 279 | It returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. 280 | 281 | Example: In this example, we will use typeof operator. 282 | 283 | ```ts 284 | var a = 17; 285 | var b = "Piyush"; 286 | var c = ""; 287 | var d = null; 288 | 289 | console.log(typeof a); 290 | console.log(typeof b); 291 | console.log(typeof c); 292 | console.log(typeof d); 293 | console.log(typeof e); 294 | ``` 295 | 296 | Output: 297 | 298 | ```ts 299 | number 300 | string 301 | string 302 | object 303 | undefined 304 | ``` 305 | 306 | ### Next Topic - [Coercion in js](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/b-DataTypes/3-Coercion.md) 307 | -------------------------------------------------------------------------------- /b-DataTypes/3-Coercion.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_13](https://user-images.githubusercontent.com/100460788/233829621-a9ce6fc1-0f39-483f-949f-9dcb85597bc2.png) 2 | 3 | ## Type conversion in JS 4 | 5 | `Type conversion` is the process of converting a value from one type to another. 6 | Values in JavaScript can be of different types. You could have a number, string, object, boolean – you name it. Sometimes, you may want to convert data from one type to another to fit a certain operation. 7 | 8 | There are two types of Type Coercion in JavaScript: 9 | 10 | - `Implicit` (automatically done during code execution) 11 | - `Explicit` (done by you the developer) 12 | 13 | Implicit Type Conversion is also known as `Type Coercion` while Explicit Type Conversion is also known as `Type Casting`. 14 | 15 | ## What is Implicit Type Conversion (Coercion)? 16 | 17 | There are some operations that you might try to execute in JavaScript which are literally not possible. For example, look at the following code: 18 | 19 | ```ts 20 | const sum = 35 + "hello" 21 | ``` 22 | 23 | Here, you're trying to add a number and a string. This is, practically speaking, not possible. You can only add numbers `(sum)` together or add strings `(concatenate)` together. 24 | 25 | Well, JavaScript is a `weakly typed language`. Instead of JavaScript throwing an `error`, it coerces the type of one value to fit the type of the other value so that the operation can be carried out. 26 | 27 | ```ts 28 | const sum = 35 + "hello" 29 | 30 | console.log(sum) // 35hello 31 | 32 | console.log(typeof sum) // string 33 | ``` 34 | 35 | This is an example of `coercion` where the type of one value is coerced to fit the other so that the operation can continue. 36 | 37 | ### 1. Number to String Conversion: 38 | 39 | When any string or non-string value is added to a string, it always converts the non-string value to a string implicitly. 40 | 41 | Example: 42 | 43 | ```ts 44 | var x = 10 + '20'; 45 | var y = '20' + 10; 46 | var z = true + '10'; 47 | 48 | console.log(x); 49 | console.log(y); 50 | console.log(z); 51 | ``` 52 | 53 | Output: 54 | 55 | ```ts 56 | 1020 57 | 2010 58 | true10 59 | ``` 60 | 61 | ## 2. String to Number Conversion: 62 | 63 | When an operation like subtraction (-), multiplication (\*), division (/) or modulus (%) is performed, all the values that are not number are converted into the number data type, as these operations can be performed between numbers only. Some examples of this are shown below. 64 | 65 | Example: 66 | 67 | ```ts 68 | var w = 10 - '5'; 69 | var x = 10 * '5'; 70 | var y = 10 / '5'; 71 | var z = 10 % '5'; 72 | 73 | console.log(w); 74 | console.log(x); 75 | console.log(y); 76 | console.log(z); 77 | ``` 78 | 79 | Output: 80 | 81 | ```ts 82 | 5 83 | 50 84 | 2 85 | 0 86 | ``` 87 | 88 | ### 3. Boolean to Number: 89 | 90 | When a Boolean is added to a Number, the Boolean value is converted to a number as it is safer and easier to convert Boolean values to Number values. A Boolean value can be represented as 0 for ‘false’ or 1 for ‘true’. Some examples of this are shown below. 91 | 92 | Example: 93 | 94 | ```ts 95 | var x = true + 2; 96 | var y = false + 2; 97 | 98 | console.log(x); 99 | console.log(y); 100 | ``` 101 | 102 | Output: 103 | 104 | ```ts 105 | 3 106 | 2 107 | ``` 108 | 109 | ### 4. The Equality Operator: 110 | 111 | The `Loose Equality Operator (==)` can be used to compare values irrespective of their `type`. This is done by coercing a non-number data type to a number. Some examples of this are shown below: 112 | 113 | Example: 114 | 115 | ```ts 116 | var x = (10 == '10'); 117 | var y = (true == 1); 118 | var z = (true == 'true'); 119 | 120 | console.log(x); 121 | console.log(y); 122 | console.log(z); 123 | ``` 124 | 125 | Output: 126 | 127 | ```ts 128 | true 129 | true 130 | false 131 | ``` 132 | 133 | The `Strict Equality Operator (===)` does a strict check – that is, it strictly checks the `values` compared, as well as the `types`. Type coercion does not occur here, so there are no unexpected answers. 134 | 135 | Example: 136 | 137 | ```ts 138 | var x = (10 === '10'); 139 | var y = (false === ""); 140 | 141 | console.log(x); 142 | console.log(y); 143 | ``` 144 | 145 | Output: 146 | 147 | ```ts 148 | false 149 | false 150 | ``` 151 | 152 | ## What is Explicit Type Conversion (Type Casting)? 153 | 154 | To explicitly convert types, you use the type Constructors. 155 | 156 | ### For example, to convert a number to a string: 157 | 158 | ```ts 159 | const number = 30 160 | 161 | const numberConvert = String(number) 162 | 163 | console.log(numberConvert) // "30" 164 | 165 | console.log(typeof numberConvert) // string 166 | ``` 167 | 168 | ### Another example is to convert a number to a boolean: 169 | 170 | ```ts 171 | const number = 30 172 | 173 | const numberConvert = Boolean(number) 174 | 175 | console.log(numberConvert) // true 176 | 177 | console.log(typeof numberConvert) // boolean 178 | ``` 179 | 180 | ### And one more example, to convert a boolean to a string: 181 | 182 | ```ts 183 | const boolean = false 184 | 185 | const booleanConvert = String(boolean) 186 | 187 | console.log(booleanConvert) // "false" 188 | 189 | console.log(typeof booleanConvert) // string 190 | ``` 191 | 192 | In these examples, we explicitly convert a value from one type to another. 193 | 194 | 195 | ### Next topic - [Types of errors in js](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/b-DataTypes/4-Error-Types.md) 196 | -------------------------------------------------------------------------------- /b-DataTypes/4-Error-Types.md: -------------------------------------------------------------------------------- 1 | ## What are Errors in JavaScript? 2 | 3 | JavaScript code can encounter different errors when it is executed. Errors can be caused by programming mistakes, incorrect input, or other unforeseeable events. 4 | 5 | Errors in programming can be divided into two types. 6 | 7 | These are: 8 | 9 | - `Program Error` : - In this case, the program might need to handle this error through its error handlers. An example could be network disconnection, timeout error, etc. 10 | - `Developer Error` : - The programmer has caused an error. It can be a syntax error, a logical error, a semantic error, etc. 11 | 12 | ## The 6 error types in JavaScript 13 | 14 | The following are the 6 most common error constructors in JavaScript: 15 | 16 | ### 1. Syntax error : 17 | 18 | The error occurs when you use a predefined syntax incorrectly. 19 | 20 | Run the code below to see a syntax error. It will be thrown because there are no closing braces ‘}’ for the function. We can see this here: 21 | 22 | ```ts 23 | const ourFunction = () =>{ 24 | console.log(hello) 25 | // Missing } 26 | ``` 27 | 28 | Output : 29 | 30 | ```ts 31 | } 32 | ^ 33 | SyntaxError: Unexpected token } 34 | ``` 35 | 36 | ### 2. Reference Error : 37 | 38 | In a case where a variable reference can't be found or hasn't been declared, then a Reference error occurs. 39 | 40 | ```ts 41 | console.log(x); 42 | ``` 43 | 44 | Output: 45 | 46 | ```ts 47 | console.log(x); 48 | ^ 49 | ReferenceError: x is not defined 50 | ``` 51 | 52 | ### 3. Type Error : 53 | 54 | An error occurs when a value is used outside the scope of its data type. 55 | 56 | ```ts 57 | let num = 15; 58 | console.log(num.split("")); 59 | ``` 60 | 61 | Output: 62 | 63 | ```ts 64 | console.log(num.split("")); //Converting a number to an array will throw an error 65 | ^ 66 | TypeError: num.split is not a function 67 | ``` 68 | 69 | ### 4. Evaluation Error : 70 | 71 | Current JavaScript engines and EcmaScript specifications do not throw this error. However, it is still available for backward compatibility. The error is called when the `eval()` backward function is used, as shown in the following code block: 72 | 73 | ```ts 74 | try{ 75 | throw new EvalError("'Throws an error'") 76 | }catch(error){ 77 | console.log(error.name, error.message) 78 | } 79 | ``` 80 | 81 | Output: 82 | 83 | ```ts 84 | EvalError 'Throws an error' 85 | ``` 86 | 87 | ### 5. RangeError : 88 | 89 | There is an error when a range of expected values is required, as shown below: 90 | 91 | ```ts 92 | const checkRange = (num)=>{ 93 | if (num < 30) throw new RangeError("Wrong number"); 94 | return true 95 | } 96 | 97 | checkRange(20); 98 | ``` 99 | 100 | Output: 101 | 102 | ```ts 103 | if (num < 30) throw new RangeError("Wrong number"); 104 | ^ 105 | RangeError: Wrong number 106 | ``` 107 | 108 | ### 6. URI Error : 109 | 110 | When the wrong character(s) are used in a URI function, the error is called. 111 | 112 | ```ts 113 | console.log(decodeURI("https://github.com/piyush-agrawal6")) 114 | console.log(decodeURI("%abcd")); 115 | ``` 116 | 117 | Output: 118 | 119 | ```ts 120 | console.log(decodeURI("%abcd")); 121 | ^ 122 | URIError: URI malformed 123 | ``` 124 | 125 | ### 7. InternalError : 126 | 127 | This error occurs internally in the JS engine, especially when it has too much data to handle and the stack grows way over its critical limit. 128 | 129 | This occurs when the JS engine is overwhelmed by too many recursions, too many switch cases, etc 130 | 131 | ```ts 132 | switch(num) { 133 | case 1: 134 | ... 135 | break 136 | case 2: 137 | ... 138 | break 139 | ... up to 1000 cases 140 | } 141 | ``` 142 | 143 | Output: Its output will be like `InternalError` . 144 | 145 | ## Error Handling : The try...catch...finally Statement 146 | 147 | Exception handling has been added to JavaScript in recent versions. Exceptions are handled by JavaScript's `try...catch...finally` construct and throw operator. 148 | 149 | After the `try` block, there must either be a `catch` block or a `finally` block (or both). The catch block is executed if an exception occurs in the try block. After `try/catch` , finally is executed unconditionally. Let's see an example: 150 | 151 | ```ts 152 | function myFunc() { 153 | var num = 50; 154 | try { 155 | alert("Value of variable a is : " + num ); 156 | } 157 | catch ( error ) { 158 | alert("Error: " + error.description ); 159 | } 160 | finally { 161 | alert("Finally, block will always execute!" ); 162 | } 163 | } 164 | myFunc() 165 | ``` 166 | 167 | Output: The below statements will be shown in an alert box. 168 | 169 | ```ts 170 | Value of variable a is : 50 171 | Finally, block will always execute! 172 | ``` 173 | 174 | ### Next Topic - [Interview questions](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/b-DataTypes/5-Questions.md) 175 | -------------------------------------------------------------------------------- /b-DataTypes/5-Questions.md: -------------------------------------------------------------------------------- 1 | ### 1. What are the various data types that exist in JavaScript? 2 | 3 | These are the different types of data that JavaScript supports: 4 | 5 | - `Boolean` - For true and false values 6 | - `Null` - For empty or unknown values 7 | - `Undefined` - For variables that are only declared and not defined or initialized 8 | - `Number` - For integer and floating-point numbers 9 | - `String` - For characters and alphanumeric values 10 | - `Object` - For collections or complex values 11 | - `Symbols` - For unique identifiers for objects 12 | 13 | ### 2. What is the difference between Undefined and Undeclared in JavaScript? 14 | 15 | - `Undefined` : Undefined means a variable has been declared but a value has not yet been assigned to that variable. 16 | - `Undeclared` : Variables that are not declared or that do not exist in a program or application. 17 | 18 | ### 3. What is the difference between Undefined and Null in JavaScript? 19 | 20 | - `Undefined` : Undefined means a variable has been declared but a value has not yet been assigned to that variable. 21 | - `Null` : Null is an assignment value that we can assign to any variable that is meant to contain no value. 22 | 23 | ### 4. Difference between “ == “ and “ === “ operators (with examples) 24 | 25 | - `==` operator is a loose comparison operator that used to compare the values 26 | - `===` operator is a strict comparison operator that is used to compare the values as well as types. 27 | 28 | Example: 29 | 30 | ```ts 31 | var x = 3; 32 | var y = "3"; 33 | 34 | console.log(x == y) // it returns true as the value of both x and y is the same 35 | console.log(x === y) // it returns false as the typeof x is "number" and typeof y is "string" 36 | ``` 37 | 38 | ### 5. What is NaN property in JavaScript? 39 | 40 | - `NaN` property represents the `Not-a-Number` value. It indicates a value that is not a legal number. 41 | - `typeof` of NaN will return a `Number`. 42 | - To check if a value is NaN, we use the `isNaN()` function. 43 | 44 | ### 6. What would be the result of 2+5+”3″? 45 | 46 | Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its concatenation will be done. So the result would be 73. The ” ” makes all the difference here and represents 3 as a string and not a number. 47 | 48 | ### 7. What is the output of "10"+20+30 in JavaScript? 49 | 50 | 102030 because after a string all the + will be treated as string concatenation operator (not binary +). 51 | 52 | ### 8. How to handle exceptions in JavaScript? 53 | 54 | By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript supports try, catch, finally and throw keywords for exception handling. 55 | 56 | ### 9. What are the falsy values in JavaScript, and how can we check if a value is falsy? 57 | 58 | Those values which become false while converting to Boolean are called falsy values. 59 | 60 | ```ts 61 | const falsyValues = ['', 0, null, undefined, NaN, false]; 62 | ``` 63 | 64 | We can check if a value is falsy by using the Boolean function or the Double NOT operator (!!). 65 | 66 | ### 10. Guess the outputs of the following code: 67 | 68 | ```ts 69 | function runFunc(){ 70 | console.log("1" + 1); 71 | console.log("A" - 1); 72 | console.log(2 + "-2" + "2"); 73 | console.log("Hello" - "World" + 78); 74 | console.log("Hello"+ "78"); 75 | } 76 | runFunc(); 77 | ``` 78 | 79 | Output: 80 | 81 | ```ts 82 | 11 83 | Nan 84 | 2-22 85 | NaN 86 | Hello78 87 | ``` 88 | 89 | ### 11. Guess the outputs of the following code: 90 | 91 | ```ts 92 | let a = 0; 93 | let b = false; 94 | console.log((a == b)); 95 | console.log((a === b)); 96 | ``` 97 | 98 | Output: 99 | 100 | ```ts 101 | true 102 | false 103 | ``` 104 | 105 | 106 | ### Next Topic - [Scope](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/c-Scope) 107 | -------------------------------------------------------------------------------- /c-Scope/1-Scope.md: -------------------------------------------------------------------------------- 1 | ![JS-ES2015-min-1200x675](https://user-images.githubusercontent.com/100460788/235360531-15c0c5cb-4b7e-4b97-b338-b6998371d44a.png) 2 | 3 | ## What Is Scope? 4 | 5 | In JavaScript your code runs within some set scope. This scope determines what variables your code has access to, how new variables will interact with the rest of your code, and a few other things. The best way to think of scope is as a partition to help you separate different parts of your code from one another. 6 | 7 | ### Types of Scopes in JavaScript: 8 | 9 | - Block scope 10 | - Function scope 11 | - Local scope 12 | - Global scope 13 | 14 | ### 1. Global scope : 15 | 16 | - Any time you define a a variable at the top level of a file (outside any function/curly braces) it is considered global scope and can be accessed ANYWHERE in your entire application. 17 | - This global access makes writing code easier at first since you don't have to worry about variables being blocked by different scopes, but as you start to write more complex code this quickly becomes difficult to manage. This problem is even worse when you have multiple files. 18 | 19 | ```html 20 | 21 | 22 | 23 | 41 | 42 | 43 | ``` 44 | 45 | Output : 46 | 47 | ```ts 48 | 1; 49 | 2; 50 | 3; 51 | 1; 52 | 2; 53 | 3; 54 | ``` 55 | 56 | ### 2. Local scope : 57 | 58 | Variables declared inside a function become local to the function. Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function. 59 | 60 | ```html 61 | 62 | 63 | 64 | 72 | 73 | 74 | ``` 75 | 76 | Output : 77 | 78 | ```ts 79 | 1 80 | x is not defined 81 | ``` 82 | 83 | ### 3. Block scope : 84 | 85 | - Earlier JavaScript had only Global Scope and Function Scope. `let` and `const` are the two new important keywords that were introduced by the ES6 and these two keywords provide `Block Scope` in JavaScript. 86 | - Variables that are declared inside a `{ }` block cannot be accessed from outside the block. 87 | - Variables declared with the `var` keyword cannot have block scope and they can be declared inside a { } block and can be accessed from outside the block. 88 | 89 | Example : 90 | 91 | ```ts 92 | function print() { 93 | if (true) { 94 | var a = "1"; 95 | let b = "2"; 96 | const c = "3"; 97 | } 98 | console.log(a); 99 | console.log(b); 100 | console.log(c); 101 | } 102 | print(); 103 | ``` 104 | 105 | Output : 106 | 107 | ```ts 108 | 1 109 | b is not defined 110 | c is not defined 111 | ``` 112 | 113 | ### 4. Function scope : 114 | 115 | JavaScript has function scope and each function creates a new scope. Variables defined inside a function are not accessible from outside the function and variables declared with var, let and const are quite similar when declared inside a function. 116 | 117 | Example : 118 | 119 | ```html 120 | 121 | 122 | 123 | 131 | 132 | 133 | ``` 134 | 135 | Output : 136 | 137 | ```ts 138 | 1 139 | x is not defined 140 | ``` 141 | 142 | ### Next topic - [Shadowing in js](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/c-Scope/2-Shadowing.md) 143 | -------------------------------------------------------------------------------- /c-Scope/2-Shadowing.md: -------------------------------------------------------------------------------- 1 | ## What is shadowing? 2 | 3 | `Shadowing : ` 4 | 5 | In the global scope, `shadowing` occurs when a variable declared with the `var` keyword has the same name as a variable declared with the `let` or `const` keyword. When this happens, the global variable is said to be shadowed by the function-scoped variable. 6 | 7 | Example : 8 | 9 | ```ts 10 | let a = "Hey"; 11 | 12 | function func() { 13 | let a = "Hey how"; 14 | if (true) { 15 | let a = "Hey how are you?"; 16 | console.log(a); 17 | } 18 | console.log(a); 19 | } 20 | console.log(a); 21 | 22 | func(); 23 | ``` 24 | 25 | Output: 26 | 27 | ```ts 28 | Hey 29 | Hey how are you? 30 | Hey how 31 | ``` 32 | 33 | `Illegal Shadowing :` 34 | 35 | Now, while shadowing a variable, it should not cross the boundary of the scope, i.e. we can shadow var variable by let variable but cannot do the opposite. So, if we try to shadow let variable by var variable, it is known as Illegal Shadowing and it will give the error as “variable is already defined.” 36 | 37 | Example : 38 | 39 | ```ts 40 | function func() { 41 | var a = "Joy"; 42 | let b = "Joy"; 43 | 44 | if (true) { 45 | let a = "Piyush"; // Legal Shadowing 46 | var b = "Piyush"; // Illegal Shadowing 47 | console.log(a); // It will print 'Piyush' 48 | console.log(b); // It will print error 49 | } 50 | } 51 | 52 | func(); 53 | ``` 54 | 55 | ### Next Topic - [Interview Questions](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/c-Scope/3-Questions.md) 56 | -------------------------------------------------------------------------------- /c-Scope/3-Questions.md: -------------------------------------------------------------------------------- 1 | ### 1. What are the scopes of a variable in JavaScript? 2 | 3 | The scope of a variable implies where the variable has been declared or defined in a JavaScript program. There are two scopes of a variable: 4 | 5 | - `Global variables` are available everywhere in a JavaScript code. 6 | - `Local variables` are accessible only within a function in which they are defined. 7 | 8 | ### 2. What is scope chain ? 9 | 10 | - `Scope Chain` : JavaScript engine also uses Scope to find variables. Let’s understand that using an example: 11 | 12 | ```ts 13 | var y = 24; 14 | 15 | function fun1() { 16 | var x = 667; 17 | 18 | var fun2 = function () { 19 | console.log(x); // Does not find x inside `fun2` , so looks for variable inside `fun1` , returns 667 20 | }; 21 | 22 | var fun3 = function () { 23 | console.log(y); // Does not find y inside `fun3`, so looks for variable inside `fun1` and does not find it, so looks for variable in global scope, finds it and returns 24 24 | }; 25 | 26 | fun2(); 27 | fun3(); 28 | } 29 | fun1(); 30 | ``` 31 | 32 | - As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope. 33 | - If the variable is not found in the global space as well, a reference error is thrown. 34 | 35 | ### Next Topic - [Hoisting in js](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/d-Hoisting) 36 | -------------------------------------------------------------------------------- /d-Hoisting/1-Hoisting.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_14](https://user-images.githubusercontent.com/100460788/233957579-39ddaa3e-fa3c-42ae-9b4f-82879d844363.png) 2 | 3 | ## Hoisting 4 | 5 | - In JavaScript, Hoisting is a kind of default behavior in which all the declarations either variable declaration or function declaration are moved at the top of the scope just before executing the program's code. 6 | - Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. 7 | - It allows us to call functions before even writing them in our code. 8 | - Note: JavaScript only hoists declarations, not initializations. 9 | - JavaScript allocates memory for all variables and functions defined in the program before execution. 10 | 11 | ## Sequence of variable declaration 12 | 13 | The following is the sequence in which variable declaration and initialization occur. 14 | 15 | ```ts 16 | Declaration –> Initialization/Assignment –> Usage 17 | ``` 18 | 19 | #### Variable lifecycle: 20 | 21 | ```ts 22 | let a; // Declaration 23 | a = 100; // Assignment 24 | console.log(a); // Usage 25 | ``` 26 | 27 | - However, since JavaScript allows us to both declare and initialize our variables simultaneously, so we can declare and initialize at the same time. 28 | 29 | ```ts 30 | let a = 100; 31 | ``` 32 | 33 | - Note: Always remember that in the background the Javascript is first declaring the variable and then initializing them. It is also good to know that variable declarations are processed before any code is executed. 34 | 35 | ## Variable Hoisting 36 | 37 | In terms of variables and constants, keyword `var` is hoisted and `let` and `const` does not allow hoisting. 38 | 39 | ### 1. Variable hoisting with `var` 40 | 41 | - When the interpreter hoists a variable declared with var, it initializes its value to undefined. 42 | 43 | ```ts 44 | console.log(a); 45 | 46 | var a = "bar"; 47 | 48 | console.log(a); 49 | ``` 50 | 51 | - The above program behaves as: 52 | 53 | ```ts 54 | var a; 55 | 56 | console.log(a); 57 | 58 | a = bar; 59 | 60 | console.log(a); 61 | ``` 62 | 63 | Output : 64 | 65 | ```ts 66 | undefined; 67 | bar; 68 | ``` 69 | 70 | - Remember that the first `console.log(a)` outputs `undefined` because a is hoisted and given a default value of `undefined` 71 | - Using an `undeclared variable` will throw a `ReferenceError` instead because no declaration was hoisted: 72 | 73 | ```ts 74 | console.log(a); // Uncaught ReferenceError: a is not defined 75 | ``` 76 | 77 | ### 2. Variable hoisting with `let` and `const` 78 | 79 | - Variables declared with `let` and `const` are hoisted but not initialized with a default value. Accessing a let or const variable before it's declared will result in a `ReferenceError` 80 | 81 | ```ts 82 | console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization 83 | 84 | let a = "bar"; 85 | ``` 86 | 87 | - Notice that the interpreter still hoists a: the error message tells us the variable is initialized somewhere. 88 | 89 | ### The temporal dead zone 90 | 91 | - The reason that we get a reference error when we try to access a let or const variable before its declaration is because of the `temporal dead zone (TDZ)`. 92 | - A `temporal dead zone` (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value. 93 | - Accessing the variable in this TDZ throws a `ReferenceError`. 94 | 95 | ## Function hoisting in JavaScript 96 | 97 | - Function declarations are hoisted, too. Function hoisting allows us to call a function before it is defined. 98 | - For example, the following code runs successfully and outputs `hello`: 99 | 100 | ```ts 101 | a(); // hello 102 | 103 | function a() { 104 | console.log("hello"); 105 | } 106 | ``` 107 | 108 | - Note that only `function declarations` are hoisted, not `function expressions`. This should make sense: as we just learned, variable assignments aren't hoisted. 109 | - If we try to call the variable that the function expression was assigned to, we will get a `TypeError` or `ReferenceError`, depending on the variable's scope: 110 | 111 | ```ts 112 | a(); // Uncaught TypeError: a is not a function 113 | var a = function () {}; 114 | 115 | b(); // Uncaught ReferenceError: Cannot access 'b' before initialization 116 | let b = function () {}; 117 | 118 | c(); // Uncaught ReferenceError: Cannot access 'c' before initialization 119 | const c = function () {}; 120 | ``` 121 | 122 | - This differs from calling a function that is never declared, which throws a different `ReferenceError`: 123 | 124 | ```ts 125 | a(); // Uncaught ReferenceError: a is not defined 126 | ``` 127 | 128 | ### Next Topic - [Var , let and const](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/d-Hoisting/2-Var-Let-Const.md) 129 | -------------------------------------------------------------------------------- /d-Hoisting/2-Var-Let-Const.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_15](https://user-images.githubusercontent.com/100460788/233977674-fe93dfa3-c823-45cf-9a72-cb5610a82909.png) 2 | 3 | ## Var VS Let Vs Const 4 | 5 | - One of the features that came with `ES6` is the addition of `let` and `const`, which can be used for variable declaration. The question is, what makes them different from good ol' `var` which we've been using? If you are still not clear about this, then this article is for you. 6 | 7 | - Variable declaration in JavaScript is the process of creating a variable and giving it a name so that it can be used to store a value. A variable is a named container that holds a value, and can be used to store and manipulate data in a program. `var`, `let`, and `const` are all used in JavaScript to declare variables. However, there are many differences between let, var, and const in javascript in terms of how they behave and how they should be used. 8 | 9 | ## var 10 | 11 | - `var` is the oldest way to declare a variable in JavaScript. 12 | - Variables declared with `var` have a `function-level scope`, meaning they are only accessible within the function in which they were declared. - 13 | - They also have `hoisting` behavior, which means they are accessible throughout the entire scope of the function, regardless of where they were declared. 14 | - `Reassigning` value is `allowed` while using var variable. 15 | - The `redeclaration` of var variable is `allowed. 16 | - However, because of its function-level scope, variables declared with var can lead to unexpected behavior and are generally not recommended. 17 | 18 | ```ts 19 | var x = 5; 20 | console.log(x); // Output: 5 21 | 22 | if (x > 0) { 23 | var x = 10; 24 | console.log(x); // Output: 10 25 | } 26 | console.log(x); // Output: 10 27 | ``` 28 | 29 | ## let 30 | 31 | - `let` was introduced in `ES6` as an alternative to `var`. 32 | - Variables declared with `let` have the `block-level scope`, meaning they are only accessible within the block in which they were declared. 33 | - `Hoisting` is `not allowed` while using let variable. 34 | - They also have the concept of the `temporal dead zone`, which means they are not accessible before they are declared. 35 | - `Reassigning` value is `allowed` while using let variable. 36 | - The `redeclaration` of let variable is `not allowed. 37 | 38 | ```ts 39 | let y = 5; 40 | console.log(y); // Output: 5 41 | 42 | if (y > 0) { 43 | let y = 10; 44 | console.log(y); // Output: 10 45 | } 46 | console.log(y); // Output: 5 47 | ``` 48 | 49 | ## const 50 | 51 | - `const` was also introduced in `ES6` 52 | - It is used to declare variables that `cannot be reassigned`. 53 | - `Hoisting` is `not allowed` while using let variable. 54 | - `Reassigning` value is `not allowed` while using let variable. 55 | - The `redeclaration` of const variable is `not allowed. 56 | - This makes `const` variables useful for declaring constants, such as `pi` or the `gravitational constant`, which have a `fixed value`. 57 | - Like let, `const` variables have the `block-level scope`, and, they are not accessible before they are declared. 58 | - They also have the concept of the `temporal dead zone`, which means they are not accessible before they are declared. 59 | - const is the most recommended for defining constant values that you don't expect to change. 60 | 61 | ```ts 62 | const pi = 3.14; 63 | console.log(pi); // Output: 3.14 64 | 65 | pi = 3.14159; // TypeError: Assignment to constant variable. 66 | ``` 67 | 68 | ## Comparison Table between `var`, `let` and `const` 69 | 70 | - Here is a comparison table between var, let and const in JavaScript: 71 | 72 | | Feature | var | let | const | 73 | | -------------------- | -------------- | ----------- | ----------- | 74 | | `Scope` | Function-level | Block-level | Block-level | 75 | | `Reassignable` | Yes | Yes | No | 76 | | `Redeclaration` | Yes | No | No | 77 | | `Hoisting` | Yes | No | No | 78 | | `Temporal Dead Zone` | No | Yes | Yes | 79 | 80 | 81 | ### Next Topic - [Interview questions](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/d-Hoisting/3-Questions.md) 82 | -------------------------------------------------------------------------------- /d-Hoisting/3-Questions.md: -------------------------------------------------------------------------------- 1 | ### 1. What’s the difference between let and var? 2 | - Both let and var are used for variable and method declarations in JavaScript. So there isn’t much of a difference between these two besides that while var keyword is scoped by function, the let keyword is scoped by a block. 3 | 4 | ### 2. Explain Hoisting in javascript. 5 | - Hoisting in javascript is the default process behavior of moving declaration of all the variables and functions on top of the scope where scope can be either local or global. 6 | 7 | 8 | ### Next Topic - [Functions](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/e-Functions) 9 | -------------------------------------------------------------------------------- /e-Functions/1-Function.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_2](https://user-images.githubusercontent.com/100460788/235360639-300c3c76-cbb8-4aeb-9384-1857175a2efc.png) 2 | 3 | ## Functions 4 | 5 | A function is a set of statements that take inputs, do some specific computation, and produce output. 6 | 7 | There are mainly two advantages of JavaScript functions. 8 | 9 | - `Code reusability` : We can call a function several times so it save coding. 10 | - `Less coding` : It makes our program compact. We don’t need to write many lines of code each time to perform a common task. 11 | 12 | ## Function declaration 13 | A `function definition` (also called a function declaration, or function statement) consists of the function keyword, followed by: 14 | 15 | - The name of the function. 16 | - A list of `parameters` to the function, enclosed in parentheses and separated by commas. 17 | - The JavaScript statements that define the function, enclosed in curly brackets, { }. 18 | - For example, the following code defines a simple function named `addNumbers` : 19 | ```ts 20 | function addNumbers(a,b) { 21 | return a+b; 22 | } 23 | ``` 24 | - The function above, named `addNumbers`, takes in two parameters, `a` and `b` . The code inside the function body simply adds these two parameters together and returns the result. 25 | 26 | ## Function Expression 27 | - `Function expressions` in JavaScript are similar to regular function declarations. The difference between them is that the function expression is always assigned to a `variable` . 28 | - Such a function can be `anonymous` ; it does not have to have a `name`. 29 | - For example, the function `addNumbers` could have been defined as: 30 | 31 | ```ts 32 | const addNumbers = function (a,b) { 33 | return a + b; 34 | }; 35 | 36 | console.log(1,2) // prints 3 37 | 38 | ``` 39 | 40 | ## Arrow Function 41 | - It is one of the most used and efficient methods to create a function in JavaScript because of its comparatively easy implementation. 42 | - It is a simplified as well as a more compact version of a regular or normal function expression or syntax. 43 | 44 | Syntax: 45 | ```ts 46 | let addNumbers = (a,b) => a+b 47 | ``` 48 | ## Immediately Invoked Function Expressions (IIFE) 49 | - JavaScript provides a variety of methods to define and execute Functions, there are named functions and anonymous functions, and then there are Functions that are executed as soon as they are mounted, these functions are known as Immediately Invoked Function Expressions or IIFEs. 50 | - `Syntax` : IIFEs follow a particular syntax as shown below. 51 | ```ts 52 | (function (){ 53 | // Function Logic Here. 54 | })(); 55 | ``` 56 | - `Immediately Invoked` : This part is easy to explain and demonstrate. This type of function is called immediately invoked as these functions are executed as soon as they are mounted to the stack, it requires no explicit call to invoke the function. If we look at the syntax itself we have two pairs of closed parentheses, the first one contains the logic to be executed and the second one is generally what we include when we invoke a function, the second parenthesis is responsible to tell the compiler that the function expression has to be executed immediately. 57 | 58 | ## Parameter vs. argument 59 | - A `parameter` is a variable in a function definition. It is a placeholder and hence does not have a concrete value. 60 | - An `argument` is a value passed during function invocation. 61 | 62 | ![Screenshot_1](https://user-images.githubusercontent.com/100460788/234817199-dbe5412f-15e9-4f9f-9d59-d80fe5ab00b1.png) 63 | 64 | ## Spread vs Rest Operator 65 | - JavaScript uses three dots `...` for both the `rest` and `spread` operators. 66 | - But these two operators are not the same. 67 | - The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. 68 | - But the spread syntax expands iterables into individual elements. 69 | - Example 1: In the example below two arrays are defined and they’re merged into one using the spread operator (…). 70 | ```ts 71 | // spread opetator 72 | var array1 = [10, 20, 30, 40, 50]; 73 | var array2 = [60, 70, 80, 90, 100]; 74 | var array3 = [...array1, ...array2]; 75 | console.log(array3); 76 | 77 | // rest operator 78 | function function_name(...arguments) { 79 | statements; 80 | } 81 | ``` 82 | 83 | 84 | ## Default Parameters 85 | - JavaScript functions also have a feature called `default parameters`. 86 | - They allow you to set default values for parameters in case they are not passed when the function is called. 87 | - This is helpful in situations where you want to provide a default value for a parameter in case it is not passed. 88 | - Here is an example: 89 | 90 | ```ts 91 | function greet(name = "John") { 92 | console.log(`Hello, ${name}!`); 93 | } 94 | greet(); // Hello, John! 95 | greet("Joy"); // Hello, Joy! 96 | ``` 97 | 98 | - In this example, the greet function takes in a single parameter name, which is set to `John` by `default`. 99 | - If the function is called without passing any arguments, it will use the default value `John`. 100 | - But if an argument is passed, it will use that value instead. 101 | 102 | ## First-Class Function 103 | - A programming language is said to have First-class functions if functions in that language are treated like other variables. 104 | - So the functions can be assigned to any other `variable` or passed as an `argument` or can be `returned` by another function. 105 | - JavaScript treat function as a `first-class-citizens` . This means that functions are simply a value and are just another type of object. 106 | - Example : 107 | ```ts 108 | function square(number){ 109 | return number * number 110 | } 111 | 112 | function dispalySquare(fn){ 113 | console.log(fn(2)) 114 | } 115 | 116 | displaySquare(square) // prints 4 117 | ``` 118 | 119 | ## Higher-Order Function 120 | - A function that receives another function as an argument or that returns a new function or both is called `Higher-order function`. 121 | - Higher-order functions are only possible because of the `First-class function`. 122 | - Example : 123 | ```ts 124 | let greet = function(name){ 125 | return function(greeting){ 126 | console.log(`Hi, ${name}, ${greeting}`); 127 | } 128 | } 129 | 130 | let func = greet('Joy') 131 | 132 | func("How are you") 133 | ``` 134 | - Output : 135 | ```ts 136 | Hi, Joy, How are you 137 | ``` 138 | ## Function scope 139 | - Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. 140 | - In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. 141 | 142 | -------------------------------------------------------------------------------- /e-Functions/2-Closures.md: -------------------------------------------------------------------------------- 1 | ![6217944a3023542e3a3ecebc_javascript-closures](https://user-images.githubusercontent.com/100460788/235360736-b9aaaacb-84c6-4df9-af39-7b7bbc39c608.png) 2 | 3 | ## Closure 4 | 5 | - A `closure` can be defined as a JavaScript feature in which the inner function has access to the outer function variable. 6 | - In JavaScript, every time a closure is created with the creation of a function. 7 | 8 | The closure has three scope chains listed as follows: 9 | - Access to its own scope. 10 | - Access to the variables of the outer function. 11 | - Access to the global variables. 12 | 13 | Example : 14 | ```ts 15 | function outer() { 16 | var a = 1; 17 | 18 | function inner() { 19 | var b = 2 20 | console.log(a+b); 21 | } 22 | 23 | return inner; 24 | } 25 | 26 | var sum = outer(); 27 | sum(); // prints 3 28 | ``` 29 | - In the example above, the function `outer` creates a local variable `a` and `inner` (a function which printsthe sum of two numbers to the console). 30 | 31 | - The function `inner` doesn’t have any variables `a` of its own — however, it does have access to the variables within the outer function, `outer`, because of a closure. 32 | 33 | - Therefore, it can use the variable `a` declared in `outer` and add it to the variable `b` to successfully log it to the console. 34 | 35 | ## Scope Chain 36 | - Based on the above definition, we know that an environment has access to its parent’s environment, and its parent environment has access to its parent environment, and so on. This set of identifiers that each environment has access to is called `scope` . We can nest scopes into a hierarchical chain of environments known as the `scope chain` . 37 | -------------------------------------------------------------------------------- /e-Functions/3-Currying.md: -------------------------------------------------------------------------------- 1 | ## What is Currying in JavaScript? 2 | 3 | - `Currying` is defined as changing a function having `multiple arguments` into a sequence of functions with a `single argument`. 4 | - It is a process of converting a function with `more arity` into a function having `less arity`. 5 | - The term `arity` means the number of `parameters` in a function. 6 | - It is a transformation of functions that translate a function from callable as add(1, 2, 3) into callable as add(1)(2)(3). 7 | - It only transforms a function instead of calling it. It returns a new function until all arguments get exhausted. 8 | 9 | ## Why is currying useful in JavaScript? 10 | 11 | - It helps us to create a higher-order function 12 | - Currying is helpful in Event handling. 13 | - It is very useful in building modular and reusable code 14 | - It helps us to avoid passing the same variable multiple times 15 | - It makes the code more readable 16 | 17 | ## Example 18 | - A Simple, Three-Parameter Function 19 | - In this example we will see a simple function that will accept three parameters: 20 | ```ts 21 | const add =(x, y, z)=>{ 22 | return x+y+z 23 | } 24 | console.log(add(2, 3, 5)) // prints 10 25 | ``` 26 | 27 | - `Explanation` : In the above example, we have given three parameters of which addition is performed and the result is printed as the output. 28 | - We will now use see the implementation of the currying function where one argument will be accepted by the function and it will return a series of function. 29 | ```ts 30 | function add(x) { 31 | return (y) => { 32 | return (z) => { 33 | return x + y + z 34 | } 35 | } 36 | } 37 | console.log(add(2)(3)(5)) // prints 10 38 | ``` 39 | - Now, the calculation will be performed with the previous parameters x, y, and z as 5, 2, and 3 respectively and it will return 10. 40 | 41 | 42 | ## Infinite Currying 43 | - Currying with `infinite` or `N` no.of arguments . 44 | - So let us now take a scenario where we have a function sum where we can pass arguments like this sum(1)(2) and it can go onto any number. 45 | - The sum function should generally give me a sum of all the numbers. In this case, it should probably give me the output as 3. 46 | 47 | ```ts 48 | let sum = function(a)=>{ 49 | return function(b)=>{ 50 | return a+b 51 | } 52 | } 53 | console.log(sum(1)(2)) // prints 3 54 | ``` 55 | - This is generally a smaller problem but suppose we have something like sum(1)(2)(3) then we have to return another function which should take c as an argument. 56 | - In this, we can see a clear pattern and we want to solve this question recursively. 57 | - Example : 58 | ```ts 59 | let sum = function(a)=>{ 60 | return function(b)=>{ 61 | if(b){ 62 | return sum(a+b) 63 | } 64 | return a 65 | } 66 | } 67 | console.log(sum(1)(2)(3)(4)()) // prints 10 68 | ``` 69 | 70 | - In the above code, we are taking a sum function which takes an argument a. Now, this sum function will return another function which will take an argument b. 71 | - And now we are checking whether b exists or not. 72 | - If the value of b exists then we are returning the sum function again and passing the argument as the sum of a+b. 73 | - Otherwise, we are just returning the value of an as we are considering a case where the value of b will be an empty argument. 74 | - When we console.log(sum(1)(2)(3)(4)()) then the output to the console will be 10 as we have made the function sum function very smart above which helps us to achieve the sum of the pattern given below. 75 | - This is what we call as infinite currying. 76 | -------------------------------------------------------------------------------- /e-Functions/4-Questions.md: -------------------------------------------------------------------------------- 1 | nvbn -------------------------------------------------------------------------------- /f-Objects/1-Object-Definations.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_3](https://user-images.githubusercontent.com/100460788/235360815-dc40f58d-1397-4ee0-bb19-324db222dd03.png) 2 | 3 | ## Objects 4 | 5 | - JavaScript `object` is a non-primitive data-type that allows you to store multiple collections of data in `key-value pairs`. 6 | - Each `key-value pair` is called a `property` . 7 | 8 | ![Screenshot_2](https://user-images.githubusercontent.com/100460788/235174754-39d91da9-10a5-4d80-8b7a-ec2c797c0370.png) 9 | 10 | - The key of a property can be a string. And the value of a property can be any value, e.g., a string, a number, an array, and even a function. 11 | - Example : 12 | ```ts 13 | const student = { 14 | firstName: 'ram', 15 | class: 10 16 | }; 17 | ``` 18 | 19 | ## JavaScript Nested Objects 20 | - An object can also contain another object. 21 | - For example, 22 | - 23 | ```ts 24 | const student = { 25 | name: 'John', 26 | marks: { 27 | science: 70, 28 | math: 75 29 | } 30 | } 31 | ``` 32 | 33 | ## Accessing Object Properties 34 | You can access the value of a property by using its key. 35 | 36 | ### 1. Using dot Notation 37 | - Here's the syntax of the dot notation. 38 | ```ts 39 | objectName.key 40 | ``` 41 | For example, 42 | ```ts 43 | const person = { 44 | name: 'John', 45 | age: 20, 46 | }; 47 | 48 | console.log(person.name); // Prints John 49 | ``` 50 | 51 | ### 2. Using bracket Notation 52 | - Here is the syntax of the bracket notation. 53 | ```ts 54 | objectName["propertyName"] 55 | ``` 56 | For example, 57 | ```ts 58 | const person = { 59 | name: 'John', 60 | age: 20, 61 | }; 62 | 63 | console.log(person["name"]); // Prints John 64 | ``` 65 | 66 | ## Creating a JavaScript Object 67 | There are different ways to create new objects: 68 | - Create a single object, using an object literal. 69 | - Create a single object, with the keyword new. 70 | - Define an object constructor, and then create objects of the constructed type. 71 | - Create an object using Object.create(). 72 | -------------------------------------------------------------------------------- /f-Objects/2-Object-Properties.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Properties 2 | - Properties are the values associated with a JavaScript object. 3 | - A JavaScript object is a collection of unordered properties. 4 | - Properties can usually be `changed`, `added`, and `deleted`, but some are read only. 5 | 6 | ## Adding a new property to an object 7 | - Unlike objects in other programming languages such as Java and C#, you can add a property to an object after object creation. 8 | - The following statement adds the age property to the person object and assigns 25 to it: 9 | ```ts 10 | person.age = 25; 11 | ``` 12 | 13 | ## Deleting a property of an object 14 | - To delete a property of an object, you use the `delete` operator: 15 | ```ts 16 | delete objectName.propertyName; 17 | ``` 18 | - The following example removes the age property from the person object: 19 | ```ts 20 | delete person.age; 21 | ``` 22 | - The delete keyword deletes both the `value` of the property and the `property` itself. 23 | - After deletion, the property cannot be used before it is added back again. 24 | - The delete operator is designed to be used on object properties. It has no effect on variables or functions. 25 | - The delete operator should not be used on predefined JavaScript object properties. It can crash your application. 26 | 27 | ## Modifying the value of a property 28 | - To change the value of a property, you use the assignment `operator (=)` . 29 | - For example: 30 | ```ts 31 | let person = { 32 | firstName: 'John', 33 | lastName: 'Doe' 34 | }; 35 | person.firstName = 'Jane'; 36 | console.log(person); 37 | ``` 38 | - Output: 39 | ```ts 40 | { firstName: 'Jane', lastName: 'Doe' } 41 | ``` 42 | - In this example, we changed the value of the firstName property of the person object from 'John' to 'Jane'. 43 | 44 | ## Checking if a property exists 45 | - To check if a property exists in an object, you use the `in operator`. 46 | - The in operator returns true if the propertyName exists in the objectName. 47 | - The following example creates an employee object and uses the in operator to check if the `age` and `company` properties exist in the object: 48 | ```ts 49 | let employee = { 50 | firstName: 'Peter', 51 | lastName: 'Doe', 52 | age: 18 53 | }; 54 | console.log('age' in employee); // prints true 55 | console.log('companu' in employee); // prints false 56 | ``` 57 | -------------------------------------------------------------------------------- /f-Objects/3-Object-Methods.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Methods 2 | 3 | - JavaScript methods are `actions` that can be `performed` on `objects` . 4 | - A JavaScript method is a property containing a function definition. 5 | - For example, 6 | ```ts 7 | const person = { 8 | name: 'John', 9 | greet: function(){console.log('hello')} 10 | } 11 | ``` 12 | - In the above example, a person object has two keys (name and greet), which have a string value and a function value, respectively. 13 | - Hence basically, the JavaScript method is an object property that has a function value. 14 | 15 | ## Accessing Object Methods 16 | 17 | - You access an object method with the following syntax: 18 | ```ts 19 | objectName.methodName() 20 | ``` 21 | - The methodName property will execute (as a function) when it is invoked with (). 22 | - This example accesses the fullName() method of a person object. 23 | ```ts 24 | let person = { 25 | fullName : "Joy" 26 | } 27 | 28 | let name = person.fullName(); 29 | 30 | console.log(name)// prints Joy 31 | ``` 32 | - If you access the fullName property, without (), it will return the function definition 33 | 34 | ## Adding a Method 35 | - You can also add a method in an object. 36 | - For example, 37 | 38 | ```ts 39 | let student = { }; 40 | 41 | // adding a property 42 | student.name = 'John'; 43 | 44 | // adding a method 45 | student.greet = function() { 46 | console.log('hello'); 47 | } 48 | 49 | // accessing a method 50 | student.greet(); // prints hello 51 | ``` 52 | - In the above example, an empty student object is created. Then, the name property is added. 53 | - Similarly, the greet method is also added. In this way, you can add a method as well as property to an object. 54 | 55 | ## Built-In Methods 56 | - In JavaScript, there are many built-in methods. For example, 57 | ```ts 58 | let number = '23.32'; 59 | let result = parseInt(number); 60 | console.log(result); // prints 23 61 | 62 | let message = "Hello world!"; 63 | let capital = message.toUpperCase(); 64 | console.log(capital) // prints HELLO WORLD! 65 | ``` 66 | - Here, the `parseInt()` method of Number object is used to convert numeric string value to an integer value. 67 | - Te `oUpperCase()` method converts a text to uppercase. 68 | 69 | ## Some inportant built-in object methods 70 | - `Object.values()` – return own enumerable property’s values of an object as an array. 71 | - `Object.keys()` - returns array of object's enumerable property name 72 | - `Object.entries()` – return own enumerable string-keyed property [key, value] pairs of an object. 73 | - `Object.assign()` – copy an object or merge objects. 74 | - `Object.is()` – check if two values are the same value. 75 | 76 | ## JavaScript `this` Keyword 77 | 78 | JavaScript this Keyword 79 | - To access a property of an object from within a method of the same object, you need to use the this keyword. 80 | - Let's consider an example. 81 | ```ts 82 | const person = { 83 | name: 'John', 84 | age: 30, 85 | 86 | // accessing name property by using this.name 87 | greet: function() { console.log('The name is' + ' ' + this.name); } 88 | }; 89 | 90 | person.greet(); 91 | ``` 92 | - Output : 93 | ```ts 94 | The name is John 95 | ``` 96 | 97 | - In JavaScript, the this keyword refers to an object. 98 | - Which object depends on how this is being invoked (used or called). 99 | 100 | The this keyword refers to different objects depending on how it is used: 101 | - In an object method, this refers to the object. 102 | - Alone, this refers to the global object. 103 | - In a function, this refers to the global object. 104 | - In a function, in strict mode, this is undefined. 105 | - In an event, this refers to the element that received the event. 106 | - Methods like call(), apply(), and bind() can refer this to any object. 107 | -------------------------------------------------------------------------------- /f-Objects/4-Object-Display.md: -------------------------------------------------------------------------------- 1 | ## Displaying the Object in a Loop 2 | - The properties of an object can be loop using a `for in loop` . 3 | - Example 4 | ```ts 5 | const person = { 6 | name: "John", 7 | age: 30, 8 | }; 9 | 10 | for (let x in person) { 11 | console.log(person[x]) 12 | }; 13 | ``` 14 | - Output 15 | ```ts 16 | John 17 | 30 18 | ``` 19 | 20 | ## Using Object.values() 21 | - Any JavaScript object can be converted to an array of object values using `Object.values()` . 22 | - Example : 23 | ```ts 24 | const person = { 25 | name: "John", 26 | age: 30, 27 | }; 28 | 29 | const arr = Object.values(person); 30 | cobnsole.log(arr) 31 | ``` 32 | - Output : 33 | ```ts 34 | ["John" , 30] 35 | ``` 36 | 37 | ## Using Object.keys() 38 | - Any JavaScript object can be converted to an array of object keys using `Object.keys()` . 39 | - Example : 40 | ```ts 41 | const person = { 42 | name: "John", 43 | age: 30, 44 | }; 45 | 46 | const arr = Object.keys(person); 47 | cobnsole.log(arr) 48 | ``` 49 | - Output : 50 | ```ts 51 | ["name" , "age"] 52 | ``` 53 | 54 | ## Using Object.entries() 55 | - Any JavaScript object can be converted to an array of [keys,value] pair using `Object.entries()` . 56 | - Example : 57 | ```ts 58 | const obj = { 0: "a", 1: "b", 2: "c" }; 59 | 60 | const arr = Object.entries(obj); 61 | 62 | cobnsole.log(arr) 63 | ``` 64 | - Output : 65 | ```ts 66 | [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] 67 | ``` 68 | 69 | -------------------------------------------------------------------------------- /f-Objects/5-Getter-Setter.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Getter and Setter 2 | In JavaScript, there are two kinds of object properties: 3 | - Data properties 4 | - Accessor properties 5 | 6 | ## Data Property 7 | - Here's an example of data property: 8 | ```ts 9 | const student = { 10 | // data property 11 | firstName: 'Monica'; 12 | }; 13 | ``` 14 | ## Accessor Property 15 | In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords: 16 | - `get` - to define a `getter method` to get the property value 17 | - `set` - to define a `setter method` to set the property value 18 | 19 | ## JavaScript Getter 20 | - In JavaScript, getter methods are used to access the properties of an object. For example, 21 | ```ts 22 | const student = { 23 | 24 | firstName: 'Monica', 25 | 26 | // accessor property(getter) 27 | get getName() { 28 | return this.firstName; 29 | } 30 | }; 31 | 32 | // accessing data property 33 | console.log(student.firstName); // Monica 34 | 35 | // accessing getter methods 36 | console.log(student.getName); // Monica 37 | 38 | // trying to access as a method 39 | console.log(student.getName()); // error 40 | ``` 41 | - In the above program, a getter method getName() is created to access the property of an object. 42 | 43 | ## JavaScript Setter 44 | - In JavaScript, setter methods are used to change the values of an object. For example, 45 | ```ts 46 | const student = { 47 | firstName: 'Monica', 48 | 49 | //accessor property(setter) 50 | set changeName(newName) { 51 | this.firstName = newName; 52 | } 53 | }; 54 | 55 | console.log(student.firstName); // Monica 56 | 57 | // change(set) object property using a setter 58 | student.changeName = 'Sarah'; 59 | 60 | console.log(student.firstName); // Sarah 61 | ``` 62 | - In the above example, the setter method is used to change the value of an object. 63 | 64 | ## Why Using Getters and Setters? 65 | - It gives simpler syntax 66 | - It allows equal syntax for properties and methods 67 | - It can secure better data quality 68 | - It is useful for doing things behind-the-scenes 69 | 70 | ## JavaScript Object.defineProperty() 71 | - In JavaScript, you can also use `Object.defineProperty()` method to add `getters` and `setters`. For example, 72 | ```ts 73 | const student = { 74 | firstName: 'Monica' 75 | } 76 | 77 | // getting property 78 | Object.defineProperty(student, "getName", { 79 | get : function () { 80 | return this.firstName; 81 | } 82 | }); 83 | 84 | // setting property 85 | Object.defineProperty(student, "changeName", { 86 | set : function (value) { 87 | this.firstName = value; 88 | } 89 | }); 90 | 91 | console.log(student.firstName); // Monica 92 | 93 | // changing the property value 94 | student.changeName = 'Sarah'; 95 | 96 | console.log(student.firstName); // Sarah 97 | ``` 98 | In the above example, Object.defineProperty() is used to access and change the property of an object. 99 | The syntax for using Object.defineProperty() is: 100 | ```ts 101 | Object.defineProperty(obj, prop, descriptor) 102 | ``` 103 | The Object.defineProperty() method takes three arguments. 104 | - The first argument is the objectName. 105 | - The second argument is the name of the property. 106 | - The third argument is an object that describes the property. 107 | -------------------------------------------------------------------------------- /f-Objects/6-Constructor-Function.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Constructor Function 2 | - In JavaScript, a `constructor function` is used to `create objects` . 3 | - For example, 4 | ```ts 5 | // constructor function 6 | function Person () { 7 | this.name = 'John', 8 | this.age = 23 9 | } 10 | 11 | // create an object 12 | const person = new Person(); 13 | ``` 14 | 15 | - In the above example, function `Person(`) is an object `constructor function`. 16 | - To create an object from a constructor function, we use the `new` keyword. 17 | - `Note` : It is considered a good practice to capitalize the first letter of your constructor function. 18 | 19 | ## Create Multiple Objects with Constructor Function 20 | - In JavaScript, you can create multiple objects from a single constructor function. 21 | - For example, 22 | ```ts 23 | function Person () { 24 | this.name = 'John', 25 | this.age = 23, 26 | } 27 | 28 | const person1 = new Person(); 29 | const person2 = new Person(); 30 | 31 | console.log(person1.name); // prints John 32 | console.log(person2.age); // prints 23 33 | ``` 34 | 35 | ## JavaScript this Keyword 36 | - In JavaScript, when this keyword is used in a constructor function, this refers to the object when the object is created. 37 | - For example, 38 | ```ts 39 | function Person () { 40 | this.name = 'John', 41 | } 42 | 43 | const person1 = new Person(); 44 | 45 | console.log(person1.name); // John 46 | ``` 47 | - Hence, when an object accesses the properties, it can directly access the property as person1.name. 48 | 49 | ## JavaScript Constructor Function Parameters 50 | - You can also create a constructor function with parameters. 51 | - For example, 52 | ```ts 53 | function Person (name, age) { 54 | this.name = name, 55 | this.age = age, 56 | } 57 | 58 | const person1 = new Person('John', 23); 59 | const person2 = new Person('Sam', 15); 60 | 61 | console.log(person1.name , person1.age); 62 | console.log(person2.name , person2.age); 63 | ``` 64 | - Output : 65 | ```ts 66 | John , 23 67 | Sam , 15 68 | ``` 69 | 70 | ## Adding Properties And Methods in an Object 71 | - You can add properties or methods in an object like this: 72 | ```ts 73 | function Person () { 74 | this.name = 'John', 75 | } 76 | 77 | let person = new Person(); 78 | let person2 = new Person(); 79 | 80 | // adding property to person object 81 | person.gender = 'male'; 82 | 83 | // adding method to person object 84 | person.greet = function () { 85 | console.log('hello'); 86 | } 87 | 88 | person.gender // prints male 89 | person.greet(); // prints hello 90 | ``` 91 | - In the above example, a new property `gender` and a new method `greet()` is added to the `person object` . 92 | - However, this new property and method is only added to `person`. You cannot access gender or greet() from `person2`. 93 | - Hence the program gives `error` when we try to access `person2.greet()` . 94 | 95 | 96 | ## Adding Properties And Methods in an Constructor / Object Prototype 97 | - You can also add properties and methods to a constructor function using a prototype. 98 | - For example, 99 | ```ts 100 | function Person () { 101 | this.name = 'John', 102 | } 103 | 104 | let person1 = new Person(); 105 | let person2 = new Person(); 106 | 107 | // adding new property to constructor function 108 | Person.prototype.gender = 'Male'; 109 | 110 | console.log(person1.gender); // prints Male 111 | console.log(person2.gender); // prints Male 112 | ``` 113 | - To learn more about prototypes, visit [JavaScript Prototype](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/f-Objects/7-Prototype.md). 114 | 115 | ## Built-in JavaScript Constructors 116 | JavaScript has built-in constructors for native objects: 117 | 118 | - `new String()` - A new String object 119 | - `new Number()` - A new Number object 120 | - `new Boolean()` - A new Boolean object 121 | - `new Object()` - A new Object object 122 | - `new Array()` - A new Array object 123 | - `new RegExp()` - A new RegExp object 124 | - `new Function()` - A new Function object 125 | - `new Date()` - A new Date object 126 | 127 | `Note` : It is recommended to use primitive data types and create them in a normal way, such as const name = 'John';, const number = 57; and const count = true; 128 | You should not declare strings, numbers, and boolean values as objects because they slow down the program. 129 | -------------------------------------------------------------------------------- /f-Objects/7-Prototype.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Prototype 2 | Before you learn prototypes, be sure to check these tutorials: 3 | - JavaScript Objects 4 | - JavaScript Constructor Function 5 | 6 | In JavaScript, every `function` and `object` has a property named `prototype` by default. 7 | - For example : 8 | ```ts 9 | function Person () { 10 | this.name = 'John' 11 | } 12 | 13 | const person = new Person() 14 | 15 | console.log(Person.prototype); // prints { ... } 16 | ``` 17 | - In the above example, we are trying to access the `prototype property` of a `Person` constructor function. 18 | - Since the prototype property has no value at the moment, it shows an empty object `{ ... }` . 19 | 20 | ## Prototype Inheritance 21 | - In JavaScript, a prototype can be used to add properties and methods to a constructor function. 22 | - And objects inherit properties and methods from a prototype. 23 | - It property of objects is called `Prototype Inheritance` 24 | - For example, 25 | ```ts 26 | function Person () { 27 | this.age = 23 28 | } 29 | 30 | const person = new Person(); 31 | 32 | Person.prototype.gender = 'male'; 33 | 34 | console.log(Person.prototype); 35 | console.log(person.gender); 36 | ``` 37 | 38 | - Output : 39 | ```ts 40 | { gender: "male" } 41 | male 42 | ``` 43 | -The object `person` inherits the property `gender` from the `prototype` property of `Person` constructor function. 44 | 45 | ## Add Methods and Properties to a Constructor Function Using Prototype 46 | - You can also add new methods and properties to a constructor function using prototype. 47 | - For example, 48 | ```ts 49 | function Person () { 50 | this.age = 23 51 | } 52 | const person = new Person(); 53 | 54 | // adding a property to the constructor function 55 | Person.prototype.name = "Jane" 56 | 57 | // adding a method to the constructor function 58 | Person.prototype.greet = function() { 59 | console.log('hello' + ' ' + this.name); 60 | } 61 | 62 | console.log(person.name); // Jane 63 | person.greet(); // hello Jane 64 | ``` 65 | -------------------------------------------------------------------------------- /f-Objects/8-Prototype-Chaining.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Prototype Chain 2 | - Javascript has an interesting inheritance model, which works completely different from most OOP languages. 3 | - While it is object-oriented, an object doesn’t have a type or a class to access its methods,but it has a `prototype`. 4 | - So every object has a prototype, including the prototype object i.e, the prototype object has a prototype of its own. 5 | - This “chain” goes all the way back until it reaches an object that has no prototype. 6 | - When an attribute is called on an object, the constructor is first checked for that attribute. 7 | - if it doesn’t exist, then its prototype chain is traversed until the attribute is found or the end is reached. 8 | - And this is what we call as `prototype chaining` in javascript. 9 | 10 | If an object tries to access the same property that is in the constructor function and the prototype object, the object takes the property from the constructor function. 11 | - For example, 12 | 13 | ```ts 14 | function Person() { 15 | this.name = 'John' 16 | } 17 | 18 | Person.prototype.name = 'Peter'; 19 | Person.prototype.age = 23 20 | 21 | const person = new Person(); 22 | 23 | console.log(person.name); // John 24 | console.log(person.age); // 23 25 | ``` 26 | 27 | - In the above program, a property `name` is declared in the constructor function and also in the prototype property of the constructor function. 28 | - When the program executes, `person.name` looks in the constructor function, since the constructor function has the name property with value 'John', the object takes value from that property. 29 | - When the program executes, `person.age` looks in the constructor function to see if there is a property named age. 30 | - Since the constructor function doesn't have age property, the program looks into the prototype object of the constructor function and the object inherits property from the prototype object (if available). 31 | -------------------------------------------------------------------------------- /g-Classes/1-Classes.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_4](https://user-images.githubusercontent.com/100460788/235360891-5fa04006-7ead-4748-a37a-fadd1070a801.png) 2 | 3 | ## JavaScript Classes 4 | - A JavaScript `class` is a blueprint for `creating objects`. 5 | - A class encapsulates data and functions that manipulate data. 6 | - Unlike other programming languages such as Java and C#, JavaScript `classes` are syntactic sugar over the `prototypal inheritance`. 7 | - In other words, ES6 classes are just `special functions`. 8 | 9 | ## ES6 class declaration/Syntax 10 | - JavaScript class is similar to the Javascript constructor function, and it is merely a syntactic sugar. 11 | - The constructor function is defined as: 12 | ```ts 13 | function Person () { 14 | this.name = 'John', 15 | } 16 | 17 | const person = new Person(); 18 | ``` 19 | - Instead of using the function keyword, you use the `class keyword` for creating JS classes. 20 | - For example, 21 | ```ts 22 | // creating a class 23 | class Person { 24 | constructor(name) { 25 | this.name = name; 26 | } 27 | } 28 | ``` 29 | - The `class keyword` is used to create a `class`. 30 | - The properties are assigned in a `constructor function`. 31 | - Now you can create an object. For example, 32 | ```ts 33 | // creating a class 34 | 35 | class Person { 36 | constructor(name) { 37 | this.name = name; 38 | } 39 | getName() { 40 | return this.name; 41 | } 42 | } 43 | 44 | const person = new Person('Jack'); 45 | 46 | console.log(person2.name); // Jack 47 | ``` 48 | - Here, person1 is a object of Person class. 49 | - The `getName()` is called a `method` of the `Person class`. 50 | - Like a constructor function, you can call the methods of a class using the following syntax: 51 | ```ts 52 | let name = person.getName(); 53 | 54 | console.log(name); // prints Jack 55 | ``` 56 | - To verify the fact that classes are `special functions`, you can use the `typeof operator` of to check the type of the Person class. 57 | ```ts 58 | console.log(typeof Person); // prints function 59 | ``` 60 | - `Note` : The constructor() method inside a class gets called automatically each time an object is created. 61 | 62 | ## 'use strict' 63 | - Classes always follow 'use-strict'. 64 | - All the code inside the class is automatically in strict mode. 65 | - For example, 66 | ```ts 67 | class Car { 68 | constructor(name, year) { 69 | this.name = name; 70 | this.year = year; 71 | } 72 | age() { 73 | // date = new Date(); // This will not work 74 | const date = new Date(); // This will work 75 | return date.getFullYear() - this.year; 76 | } 77 | } 78 | ``` 79 | - In "strict mode" you will get an error if you use a variable without declaring it. 80 | 81 | ## Hoisting 82 | - A class should be defined before using it. Unlike functions and other JavaScript declarations, the class is not hoisted. 83 | - For example, 84 | ```ts 85 | // accessing class 86 | const p = new Person(); // ReferenceError 87 | 88 | // defining class 89 | class Person { 90 | constructor(name) { 91 | this.name = name; 92 | } 93 | } 94 | ``` 95 | - As you can see, accessing a class before defining it throws an error. 96 | 97 | -------------------------------------------------------------------------------- /g-Classes/2-Getter-Setter.md: -------------------------------------------------------------------------------- 1 | ## Getters and Setters 2 | - In JavaScript, `getter` methods `get` the value of an object and `setter` methods `set` the value of an object. 3 | - JavaScript classes may include `getters` and `setters`. 4 | - You use the get keyword for getter methods and set for setter methods. 5 | - For example, 6 | ```ts 7 | class Person { 8 | constructor(name) { 9 | this.name = name; 10 | } 11 | 12 | // getter 13 | get personName() { 14 | return this.name; 15 | } 16 | 17 | // setter 18 | set personName(x) { 19 | this.name = x; 20 | } 21 | } 22 | 23 | let person1 = new Person('Jack'); 24 | 25 | console.log(person1.name); // prints Jack 26 | 27 | person1.personName = 'Sarah'; 28 | 29 | console.log(person1.name); // prints Sarah 30 | ``` 31 | -------------------------------------------------------------------------------- /g-Classes/3-Inheritance.md: -------------------------------------------------------------------------------- 1 | ## Class Inheritance 2 | - `Inheritance` enables you to define a class that takes all the functionality from a parent class and allows you to add more. 3 | - Using class inheritance, a class can inherit all the methods and properties of another class. 4 | - Inheritance is a useful feature that allows `code reusability`. 5 | - To use class inheritance, you use the `extends` keyword. 6 | - The following example defines the Animal and Bird classes and establishes the `inheritance` through the `extends` and `super` keywords. 7 | 8 | ```ts 9 | class Animal { 10 | constructor(legs) { 11 | this.legs = legs; 12 | } 13 | walk() { 14 | console.log('walking on ' + this.legs + ' legs'); 15 | } 16 | } 17 | 18 | class Bird extends Animal { 19 | constructor(legs) { 20 | super(legs); 21 | } 22 | fly() { 23 | console.log('flying'); 24 | } 25 | } 26 | 27 | let bird = new Bird(2); 28 | 29 | bird.walk(); // prints "walking on 2 legs" 30 | bird.fly(); // prints "flying" 31 | ``` 32 | ## How it works. 33 | #### First, 34 | - It use the `extends` keyword to make the `Bird` class inheriting from the `Animal` class: 35 | - The `Animal class` is called a base class or `parent class` while the `Bird class` is known as a derived class or `child class`. 36 | - By doing this, the Bird class inherits all methods and properties of the Animal class. 37 | 38 | #### Second 39 | - In the `Bird‘s` constructor, call `super()` to invoke the `Animal‘s` constructor with the `legs` argument. 40 | - JavaScript requires the child class to call `super()` if it has a `constructor`. 41 | - Here, `super` inside `Bird` class refers to the `Animal class. 42 | - Hence, when the constructor of `Bird` class is called, it also calls the constructor of the `Animal` class which assigns a `legs` property to it. 43 | 44 | ## Uses of Inheritance 45 | - Since a child class can inherit all the functionalities of the parent's class, this allows code reusability. 46 | - Once a functionality is developed, you can simply inherit it. No need to reinvent the wheel. This allows for cleaner code and easier to maintain. 47 | - Since you can also add your own functionalities in the child class, you can inherit only the useful functionalities and define other required features. 48 | -------------------------------------------------------------------------------- /g-Classes/4-Static-Methods.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Static Methods and Properties 2 | - By definition, `static methods` are bound to a class, not the instances of that class. 3 | - Static class methods are defined on the class itself. 4 | - You cannot call a static method on an object, only on an object class. 5 | - In ES6, you define static methods using the `static keyword`. 6 | - The following example defines a `static method` called `getName()` for the `Person` class: 7 | ```ts 8 | class Person { 9 | constructor(name) { 10 | this.name = name; 11 | } 12 | static age = 10; 13 | static getName() { 14 | return "Hello" 15 | } 16 | } 17 | ``` 18 | - To invoke the static method, you use the following syntax: 19 | ```ts 20 | let name = Person.getName(); 21 | let age = Person.age; 22 | console.log(name) // prints "Hello" 23 | console.log(age) // prints 10 24 | ``` 25 | - If you attempt to call the static method from an instance of the class, you’ll get an error. 26 | - For example: 27 | ```ts 28 | let person = new Person('Joy'); 29 | let name = person.getName(); 30 | ``` 31 | - Error: 32 | ```ts 33 | TypeError: person.getName is not a function 34 | ``` 35 | -------------------------------------------------------------------------------- /g-Classes/5-Private-Methods.md: -------------------------------------------------------------------------------- 1 | ## JavaScript private fields 2 | - ES2022 allows you to define `private fields` for a `class`. To define a private field, you prefix the field name with the `#` sign. 3 | - For example, the following defines the Circle class with a private field `radius`: 4 | ```ts 5 | class Circle { 6 | #radius; 7 | constructor(value) { 8 | this.#radius = value; 9 | } 10 | get area() { 11 | return Math.PI * Math.pow(this.#radius, 2); 12 | } 13 | } 14 | ``` 15 | In this example: 16 | - First, define the private field `#radius` in the class body. 17 | - Second, `initialize` the `#radius` field in the `constructor` with an argument. 18 | - Third, calculate the area of the circle by accessing the #radius private field in the getter method. 19 | - The following creates a new instance of the Circle class and calculates its area: 20 | ```ts 21 | let circle = new Circle(10); 22 | console.log(circle.area); // 314.159 23 | ``` 24 | - Because the #radius is a private field, you can only access it inside the Circle class. 25 | - In other words, the #radius field is invisible outside of the Circle class. 26 | - Trying to access the private field outside of the class will generate a syntax error: 27 | ```ts 28 | console.log(circle.#radius); // Syntax error 29 | ``` 30 | -------------------------------------------------------------------------------- /h-OOPS/1-OOP.md: -------------------------------------------------------------------------------- 1 | ![Screenshot_6](https://user-images.githubusercontent.com/100460788/235361061-68e1aa1d-7b17-433f-b39d-3bb3e5bde6d1.png) 2 | 3 | ## What is OOP (Object-oriented Programming)? 4 | - OOP is a programming paradigm that believes in grouping data (properties) and methods (actions) together inside a box. 5 | - It demonstrates the pattern of real-world objects. 6 | 7 | There are two types of OOP languages: 8 | - Class-Based languages like JAVA, C++. 9 | - Prototype-Based languages like JavaScript. 10 | 11 | ## Features of an Object-Oriented Language 12 | - There are four rules or main pillars of Object-oriented programming language. 13 | - This defines how the data and actions associated with the data are organized using code. 14 | 15 | ![Screenshot_3](https://user-images.githubusercontent.com/100460788/235344549-0732fa26-b173-41b4-a8c9-1261939cb8bb.png) 16 | 17 | Let us discuss all four of them in detail below. 18 | 19 | ## 1. Object 20 | ### What is an object? 21 | - We have already discussed a lot about Objects before. 22 | - Please follow the link to read - [Objects](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/f-Objects) 23 | 24 | ## 2. Classes 25 | ### What are Classes? 26 | - We have already discussed a lot about Classes in the previous module. 27 | - Please follow the link to read - [Classes](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/tree/master/g-Classes) 28 | 29 | ## 3. Encapsulation 30 | - `Encapsulation` is defined as binding the data and methods into a single unit to protect it from outside access. 31 | - Encapsulation ensures that data can only be accessed using the data functions defined inside the class. 32 | - Encapsulation is implemented through public and `private properties` and methods. 33 | - In JavaScript, all objects properties and methods are `public` by default. 34 | - Read more about Private properties here - [Private-Classes](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/g-Classes/5-Private-Methods.md) 35 | 36 | Advantages of Encapsulation in JavaScript 37 | - Encapsulation guards an object against illegal access. 38 | - Encapsulation helps to achieve a level without revealing its complex details. 39 | - This will reduce human errors. 40 | - Make the application more flexible and manageable. 41 | - Simplifies the application. 42 | 43 | ## 4. Abstraction 44 | - Abstraction is a principle that says that a class should only represent information that is relevant to the problem's context. 45 | - In plain English, only expose to the outside the properties and methods that you're going to use. If it's not needed, don't expose it. 46 | - People often misunderstood encapsulation with abstraction. 47 | - Abstraction is one step ahead of encapsulation. Abstraction is defined as showing only the essential things and hiding the inner implementation. 48 | - Let's take an example of a car. On a Car, we can perform some actions like start, break and stop. Whenever you call one of these actions, it gives you some result. 49 | - These actions have certain sub-actions which are hidden from you, but you don't need to care about those sub-actions. 50 | - This is how car company uses an abstraction of functionality to give their customer a smooth experience. 51 | 52 | ## 5. Inheritance 53 | - Inheritance is the ability to create classes based on other classes. 54 | - With inheritance, we can define a parent class (with certain properties and methods), and then children classes that will inherit from the parent class all the properties and methods that it has. 55 | - The class that inherits the property is known as subclass or child class and the class whose properties are inherited is known as a superclass or parent class. 56 | - Read more about inheritance here - [Inheritance](https://github.com/piyush-agrawal6/Javascript-Interview-Questions/blob/master/g-Classes/3-Inheritance.md) 57 | 58 | ## 6. What is Polymorphism? 59 | - Polymorphism is a concept used in the object-oriented paradigm that enables us to use the same function in different forms. 60 | - This reduces repetition and makes the code snippet useful in many different cases. 61 | - Polymorphism is implemented in JavaScript by `generic`, `overloading`, and `structural sub-typing`. 62 | 63 | Polymorphism has two types. 64 | - Compile time Polymorphism 65 | - Runtime Polymorphism 66 | 67 | `Function overloading` is a type of compile-time polymorphism. Here, we are creating more than one function with the same name and different parameters or types. 68 | 69 | `Method overriding` is a type of runtime polymorphism. Remember I told you that you can override the methods of parent class in the child class? That is method overriding. 70 | -------------------------------------------------------------------------------- /i-AdvanceFunctions/Call-Apply-Bind.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /i-AdvanceFunctions/Polyfills.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /j-ArrayMethods/HOF.md: -------------------------------------------------------------------------------- 1 | /** 2 | * ! Array Methods 3 | */ 4 | // length , reverse , sort , fill , toString , pop , shift , push , unshift , concat , splice , lastIndexOf , slice , find , includes , reduce , filter , map , forEach , some 5 | 6 | /** 7 | * ! Map , Filter , Reduce , forEach 8 | */ 9 | 10 | /** 11 | * * map 12 | */ 13 | // //what is map ? 14 | // The map() method creates a new array with the results of applying a function for every array element. 15 | //Callback takes 3 element -- CurrentElement , index , arr 16 | // //example 17 | // const nums = [1, 2, 3, 4]; 18 | // const multiply = nums.map((elem, i, arr) => { 19 | // return elem * 2; 20 | // }); 21 | // console.log(multiply); 22 | 23 | /** 24 | * * filter 25 | */ 26 | // //what is filter ? 27 | // The filter() method returns a new array with all elements that pass the test defined by the given function.Callback takes 3 element -- CurrentElement , index , arr 28 | // //example 29 | // const nums = [1, 2, 3, 4]; 30 | // const greaterThan = nums.filter((elem, i, arr) => { 31 | // return elem > 2; 32 | // }); 33 | // console.log(greaterThan); 34 | 35 | /** 36 | * * reduce 37 | */ 38 | // //what is reduce ? 39 | // The reduce() method executes a reducer function on each element of the array and returns a single output value.Callback takes 4 element -- accumulator,curr,i,arr and an initial value 40 | // //example 41 | // const nums = [1, 2, 3, 4]; 42 | // const sum = nums.reduce((acc, elem, i, arr) => { 43 | // return (acc += elem); 44 | // }, 0); 45 | // console.log(sum); 46 | 47 | /** 48 | * * forEach 49 | */ 50 | // //what is forEach ? 51 | // The forEach() method executes a provided function for each array element. 52 | //Callback takes 3 element -- CurrentElement , index , arr 53 | // It does not return an array. 54 | // //example 55 | // const nums = [1, 2, 3, 4]; 56 | // nums.forEach((elem, i, arr) => { 57 | // console.log(elem,i); 58 | // }); 59 | 60 | /** 61 | * * map polyfills 62 | */ 63 | // Array.prototype.myMap = function (cb) { 64 | // let temp = []; 65 | // for (let i = 0; i < this.length; i++) { 66 | // temp.push(cb(this[i], i, this)); 67 | // } 68 | // return temp; 69 | // }; 70 | // const nums = [1, 2, 3, 4]; 71 | // const multiply = nums.myMap((elem, i, arr) => { 72 | // return elem * 2; 73 | // }); 74 | // console.log(multiply); 75 | 76 | /** 77 | * * map vs forEach 78 | */ 79 | // These are the methods that are used to iterate on an array, more technically they invoke the provided callback function for every element of an array. 80 | // Parameters: 81 | // currentElement: This is the current element that is being processed in the callback. 82 | // indexOfElement: The index of that current element inside the array. 83 | // array: The array on which the whole operation is being performed. 84 | // // Differences between forEach and map methods: 85 | // // 1 86 | // The forEach() method does not create a new array based on the given array. 87 | // The map() method creates an entirely new array. 88 | // // 2 89 | // The forEach() method returns “undefined“. 90 | // The map() method returns the newly created array according to the provided callback function. 91 | // // 3 92 | // The forEach() method doesn’t return anything hence the method chaining technique cannot be applied here. 93 | // With the map() method, we can chain the other array Instance methods i.e returned value of the map() method invokes the next method in the chain. 94 | // // 4. 95 | // It can change the original array 96 | // It does not change the original array. 97 | // // 5. 98 | // It is not executed for empty elements. 99 | // It calls a function once for each element in an array. 100 | 101 | /** 102 | * * Questions 103 | */ 104 | 105 | // //1 106 | // Return only details of those who scored more than 60 marks and roll no. greater than 15 107 | // sum of marks 108 | // return name with marks more than 60 109 | // let students = [ 110 | // { name: "Piyush", rollNumber: 31, marks: 80 }, 111 | // { name: "Jenny", rollNumber: 15, marks: 69 }, 112 | // { name: "Dilpreet", rollNumber: 7, marks: 55 }, 113 | // { name: "Kaushal", rollNumber: 16, marks: 35 }, 114 | // ]; 115 | 116 | /** 117 | * ! call , apply , bind 118 | */ 119 | 120 | /** 121 | * * call 122 | */ 123 | // //what is call ? 124 | // Call is a function that helps you change the context of the invoking function. It helps you replace the value of "this" inside a function with whatever value you want. 125 | //call is a function that you use to change the value of this inside a function and execute it with the arguments provided. 126 | // //example 127 | // let obj = { name: "Joy" }; 128 | // function sayHello(age) { 129 | // return "Hello" + " " + this.name + " " + age; 130 | // } 131 | // console.log(sayHello.call(obj, 22)); 132 | 133 | /** 134 | * * apply 135 | */ 136 | // //what is apply ? 137 | //Apply is very similar to the call function. The only difference is that in apply you can pass the argument list as an array. 138 | // //example 139 | // let obj = { name: "Joy" }; 140 | // function sayHello(age, year) { 141 | // return "Hello" + " " + this.name + " " + age + " " + year; 142 | // } 143 | // console.log(sayHello.apply(obj, [22, 2022])); 144 | 145 | /** 146 | * * bind 147 | */ 148 | // //what is apply ? 149 | //Bind is a function that helps you create another re usable function that you can execute later by passing the arguments 150 | // //example 151 | // let obj = { name: "Joy" }; 152 | // function sayHello(age, year) { 153 | // return "Hello" + " " + this.name + " " + age + " " + year; 154 | // } 155 | // let bindFunc = sayHello.bind(obj); 156 | // console.log(bindFunc(22, 2022)); 157 | 158 | /** 159 | * * Questions 160 | */ 161 | // //1 162 | // let obj = { name: "Joy" }; 163 | // function sayHello(age) { 164 | // return this.name + " " + age; 165 | // } 166 | // console.log(sayHello.call(obj, 22)); 167 | // console.log(sayHello.apply(obj, [22])); 168 | // console.log(sayHello.bind(obj, 22)); 169 | 170 | // //2 171 | // let age = 22; 172 | // let obj1 = { 173 | // age: 20, 174 | // printAge: function () { 175 | // console.log(this.age); 176 | // }, 177 | // }; 178 | // let obj2 = { age: 24 }; 179 | // obj1.printAge.call(obj2); 180 | 181 | // //3 182 | // var status = "Hii"; 183 | // setTimeout(() => { 184 | // const status = "Hello"; 185 | // const data = { 186 | // status: "Hey", 187 | // getStatus() { 188 | // return this.status; 189 | // }, 190 | // }; 191 | // console.log(data.getStatus()); 192 | // }, 0); 193 | 194 | // //4 195 | // function f() { 196 | // console.log(this.name); 197 | // } 198 | // let a = f.bind({ name: "Joy" }).bind({ name: "Someone" }); 199 | // a(); 200 | 201 | -------------------------------------------------------------------------------- /j-ArrayMethods/Polyfills.md: -------------------------------------------------------------------------------- 1 | vxcvc -------------------------------------------------------------------------------- /k-StringMerhods/index.md: -------------------------------------------------------------------------------- 1 | dbgfgh -------------------------------------------------------------------------------- /l-Promises/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /m-AsyncAwait/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /n-Generators-Iterations/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /o-Collections/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /p-Browser/BOM/o-setTimeout/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /p-Browser/BOM/s-EventPropagation/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /p-Browser/BOM/t-Storage/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /p-Browser/BOM/xcvcv.md: -------------------------------------------------------------------------------- 1 | cvbnbn -------------------------------------------------------------------------------- /p-Browser/DOM/xcvcv.md: -------------------------------------------------------------------------------- 1 | cvbnbn -------------------------------------------------------------------------------- /p-Browser/Web-APIs/xcvcv.md: -------------------------------------------------------------------------------- 1 | cvbnbn -------------------------------------------------------------------------------- /q-ECMAScript/xcvcv.md: -------------------------------------------------------------------------------- 1 | cvbnbn -------------------------------------------------------------------------------- /r-Optimisation/q-Debouncing/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /r-Optimisation/r-Throttling/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /x-ErrorHandling/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /y-Debugging/index.md: -------------------------------------------------------------------------------- 1 | gg -------------------------------------------------------------------------------- /z-ImportantQuestions/1-TheoryBased.md: -------------------------------------------------------------------------------- 1 | ### Q4. What are the variable naming conventions in JavaScript? 2 | - You should not use any of the JavaScript reserved keyword as variable name. For example, break or boolean variable names are not valid. 3 | - JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123name is an invalid variable name but _123name or name123 is a valid one. 4 | - JavaScript variable names are case sensitive. For example, Test and test are two different variables. 5 | -------------------------------------------------------------------------------- /z-ImportantQuestions/2-OutputBased.md: -------------------------------------------------------------------------------- 1 | Hello --------------------------------------------------------------------------------