0% found this document useful (0 votes)
18 views33 pages

JavaScript Object Creation & Concepts

The document provides a comprehensive overview of various JavaScript concepts including object creation methods, prototype chains, data types, variable declarations (let, const, var), equality operators (== vs ===), first-class and higher-order functions, hoisting, temporal dead zone, closures, scopes, web storage, cookies, promises, and callback functions. Each topic is explained with examples and notes for clarity. It serves as a useful reference for understanding fundamental JavaScript programming principles.

Uploaded by

prajaktaraje21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views33 pages

JavaScript Object Creation & Concepts

The document provides a comprehensive overview of various JavaScript concepts including object creation methods, prototype chains, data types, variable declarations (let, const, var), equality operators (== vs ===), first-class and higher-order functions, hoisting, temporal dead zone, closures, scopes, web storage, cookies, promises, and callback functions. Each topic is explained with examples and notes for clarity. It serves as a useful reference for understanding fundamental JavaScript programming principles.

Uploaded by

prajaktaraje21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JS – Q & A

--------------------------------------------------------------------------------------------------------------------------

Questions

1. How to create new Objects in JS?

• Using Object Literal to create a single Object.


- E.g. Const users = { name : ‘abc’, email : ‘abc@[Link]’ }
• Using Object Literal to create an empty Object & then assign values to its keys
- E.g. Const users = {}; [Link] = ‘abc’; [Link] : ‘abc@[Link]’
• Using keyword ‘new’ to create a single Object
- E.g. const users = new Object(); [Link] = ‘abc’; [Link] : ‘abc@[Link]’
• Using Object Constructor
- E.g.
- - function Users( name, email ){ [Link] = name, [Link] = email }
- - const userA = new Users(‘abc’,’abc@[Link]’)
- Note. you can not add a new property to an existing object constructor.
• Using [Link]()
- [Link] - [Link]
US/docs/Learn/JavaScript/Objects/Object_prototypes#using_object.create
• Using Class
- E.g.
- class Car {
- constructor( nm,brnd ) {
- [Link] : nm;
- [Link] : brnd;
}
- }
- const car1 = new Car(‘Ameo’,’VW’);

2. What is Prototype Chain in JS?

• You cannot add a new property directly to any Object which is created using Object
Constructor. Prototype property allows you to add new properties to object
constructor.
- E.g.
- - [Link] = ‘44444’; isn’t allowed if Object is created using Users constructor.
- - [Link] = ‘44444’ is allowed.
- Note.
• Every object in JavaScript has a built-in property, which is called its prototype. The
prototype is itself an object, so the prototype will have its own prototype, making
what's called a prototype chain. The chain ends when we reach a prototype that has
null for its own prototype.
• When you try to access a property of an object: if the property can't be found in the
object itself, the prototype is searched for the property. If the property still can't be
found, then the prototype's prototype is searched, and so on until either the
property is found, or the end of the chain is reached, in which case undefined is
returned.
- E.g. To
- - [Link](myObject); // to find out the prototype of object ‘myObject’
- Note.
- [Link] - [Link]
US/docs/Learn/JavaScript/Objects/Object_prototypes#the_prototype_chain

3. Different Type of Datatype in JS ?

• Primitive Datatypes – String, Number, Boolean, Undefined, Null, BigInt, Symbol


• Primitive Datatypes doesn’t hold the reference, hence immutable. if a variable is
assigned with an object then both these variables will be sharing a same memory
location / reference, & any change ( add / delete etc ) will be reflected for both these
objects thereafter .
• All types except Object, define immutable values represented directly at the lowest
level of the language .
• In JavaScript, primitive values are immutable — once a primitive value is created, it
cannot be changed, although the variable that holds it may be reassigned another
value.
- E.g.
- Note. All primitive types, except null (typeof returns ‘Object’) , can be tested by
the typeof operator. typeof null returns "object", so one has to use === null to test
for null.
- [Link] -
• Non-Primitive Datatypes – Object, Array & Function
• Mutable Values & it holds the reference
• Object – Collection of Data in key : value pair
• Array – Collection of Data on the basis of index numbers
4. Difference between let, const & var ?

• Before 2015, Javascript had only Global Scope & Function Scope by using var.
• then ES6, introduced 'let', 'const' which provide Block Scope in javaScript. Variables
declared ( with 'let' & 'const') inside a { } block cannot be accessed from outside the
block.
• Declaration & assignment of variables with 'var' - You can just declare a variable
without assigning any value. The default value of this variable would be 'undefined' if
you don't assign any value. If you have declared a variable using 'var', you can't
redeclare it with 'let' or 'const'. variables declared with 'var' has a Global / Function
scope. All the declarations having Global scope can be accessed from any function.
but if a variable is declared in a function so it will be having the function scope only.
that variable can be accessed from that function only.
• Declaration & assignment of variables with 'let' - You can't just declare a variable.
Need to assign a value at the time of declaration only. You can't declare a variable
multiple times in a same scope ( global / block ). Yes, we can definitely assign the
different values multiple times. If you have declared a variable using 'let', you can't
redeclare it with any keyword like 'const', 'var' & 'let' too. It has a block scope.
• Declaration & assignment of variables with 'const' - You can't just declare a variable.
Need to assign a value at the time of declaration only, that value can't be changed
later for the lifetime. You can't declare a variable multiple times. & We can't re-
assign the different values to the variable which is declared & assigned using 'const'.
If you have declared a variable using 'const', you can't redeclare it with any keyword
like 'let', 'var' & 'const' too. It has a block scope.
• Declaration of variable without any keyword like 'var', 'let' & 'const' - Need to assign
a value to the variable at the time of declaration only. If you have declared a variable
without using any keyword before, you can't re-declare it with 'let' or 'const'. But,
you can redeclare this variable using 'var'. It has a Global / Function scope.

5. Difference between == & === in js ?

• The == operator ( equal to ) performs a loose equality comparison that performs


type coercion if necessary to make the comparison possible. It won’t consider the
data type of the values.
- E.g. 10 == ‘10’ // true | [] == 0 // true | [‘ls’] == ‘ls’ // true
- Note.
• The === operator ( strictly equal to ) performs a strict equality comparison that does
not perform type coercion and requires the operands to have the same type as well
as the same value.
- E.g. 10 === ‘10’ // false | [] === 0 // false | [].length === 0 // true | [‘ls’] === ‘ls’ // false
- Note.
6. What is first class function ?

• First class functions are javaScript functions that can behave like variables. They can
also be parsed as arguments to higher-order functions.
- E.g. add() & deducts() are First Class functions & makeCalc() is a Higher Order function
- - let add = (a,b) => a + b; let deduct = (a,b) => a - b;
- - makeCalc = ( oper, numa, numb ) => {
- return oper(numa, numb);
- }
- - [Link](makeCalc(add,37,98)); // 135
- Note. The function that we pass as an argument to another function is called
the callback function.

7. What is Higher Order function ?

• Higher Order Functions are functions that return a function or take in a function as
an argument. Eg. map, filter, sort, reduce, find etc
- E.g.
- - regNums = [2,3,8,27,64,81];
- - dblNums = [Link]( (rnm) => { return rnm * 2 } ); // 4,6,16,54,128,162
- - oddNums = [Link]( (rnf) -> { return rnf % 2 == 1 } ); // 3,27,81
- - findFirst = [Link]( ( rnff ) => rnff % 4 == 0 ); // 8
- - redTotal = [Link]( (total,rnr) => { return total = total + rnr }, 0 ) // 185
- [Link] - [Link]
callback-functions-4daad4856242

8. What is Hoisting ?

• Hoisting is javaScript’s default behavior of moving all declarations to the top of the
current scope ( script or function )
- E.g. var x; cl(x); // undefined | x = 7; cl(x); // 7
- Note. Be careful that only declaration gets hoisted not the initializations

9. What is temporal deal zone ?


• A let or const variable is said to be in a "temporal dead zone" (TDZ) from the start of
the block until code execution reaches the line where the variable is declared and
initialized. While inside the TDZ, the variable has not been initialized with a value,
and any attempt to access it will result in a ReferenceError.
- E.g.
- {
- // TDZ starts at beginning of scope
- [Link](bar); // undefined
- [Link](foo); // ReferenceError
- var bar = 1;
- let foo = 2; // End of TDZ (for foo)
- }
- Note.
- [Link] -
• Ans 2
- E.g.
- {
- // TDZ starts at beginning of scope
- const func = () => [Link](letVar); // OK
- // Within the TDZ letVar access throws `ReferenceError`
- let letVar = 3; // End of TDZ (for letVar)
- func(); // Called outside TDZ!
- }
- Note.
- [Link] -

10. What is Closures ?

• A closure is the combination of a function bundled together (enclosed) with


references to its surrounding state (the lexical environment). In other words, a
closure gives you access to an outer function's scope from an inner function. In
JavaScript, closures are created every time a function is created, at function creation
time.
- E.g.
- function makeFunc() {
- const name = "Mozilla";
- function displayName() {
- [Link](name);
- }
- return displayName;
- }
- const myFunc = makeFunc();
- myFunc();
-
11. What is scope in JS ?

• Global scope, Block scope, Function / Local scope. Global variables can be accessed
from anywhere in a JavaScript program. Variables declared
with var, let and const are quite similar when declared outside a block. Variables
defined inside a function are not accessible (visible) from outside the function.
Variables declared with var, let and const are quite similar when declared inside a
function. Variables declared with let & const inside a { } block cannot be accessed
from outside the block.

12. What is Web Storage?

• The Web Storage API is a simple syntax for storing and retrieving data in the
browser.
- E.g.
- var gid = '3798';
- [Link]("wid",gid);
- [Link]("demo").innerHTML = [Link]("wid");
- Note.
- [Link] -

13. What is Cookies ?

• Cookies are data, stored in small text files, on your computer. When a web server
has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user. Cookies were invented to solve the problem "how
to remember information about the user". When a user visits a web page, his/her
name can be stored in a cookie in the form of name-value pair. Next time the user
visits the page, the cookie "remembers" his/her name.

- E.g.
- Create a Cookie - [Link] = ‘usernm = Sachin Oswal’;
- Set Expiry – [Link] = ‘usernm = Sach Oswal; expires= Tues, 20 June 2023
12:00:00 UTC ’;
- Read a Cookie - let x = [Link];
14. How to Delete Cookies ?

• You don't have to specify a cookie value when you delete a cookie. Just set the
expires parameter to a past date.
- E.g. [Link] = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
- Note. You should define the cookie path to ensure that you delete the right cookie.
- [Link] -

15. Difference between Local storage & Session storage ?

• Local Storage - This read-only interface property provides access to the Document’s
local storage object, the stored data is stored across browser sessions. Local Storage
has 4 methods – [Link](), [Link](), localStorage
removeItem(), [Link]()
- E.g.
- Note.
- [Link] - [Link]
storage-and-cookies/
• Session Storage - A unique page session gets created once a document is loaded in a
browser tab. Page sessions are valid for only one tab at a time. Pages are only saved
for the amount of time that the tab or the browser is open; they do not persist after
the page reloads and restores. The difference between sessionStorage and
localStorage is that localStorage data does not expire, whereas sessionStorage data
is cleared when the page session ends. Session storage has 4 methods -
[Link](), [Link](), [Link](),
[Link]().

16. What is Promise in JS ?

• The Promise object represents the eventual completion (or failure) of an


asynchronous operation and its resulting value. Promise is used to solve the issue of
callBack Hell ( multiple callBack functions make the code complex in terms of
readability & to understand the flow of the execution of code ). Better handling of
asynchronous operations & Better Error Handling.
• 4 states of Promise - Pending | fulfilled ( Resolved ) | Reject | Settled ( Either
Resolved or Reject )
• async-await - To ease the promise chaining ( executing various asynchronous tasks /
function one by one ) - to reduce the chain of .then methods one after another.
- E.g.
- Note.
- [Link] -

17. What are 3 states of Promise ?

• A Promise is in one of these states.


• - pending: initial state, neither fulfilled nor rejected.
• - fulfilled: meaning that the operation was completed successfully.
• - rejected: meaning that the operation failed.

18. What is a callback function ?

• A callback is a function passed as an argument to another function. This technique


allows a function to call another function.
- E.g.
- function callsback(callbackFunc) {
- callbackFunc()
- }
-
- function firstClass() {
- [Link]("I was called");
- }
-
- firstClass(); // "I was called"
- callsback(firstClass); // "I was called"
-
- [Link] -

19. Why do we need callback functions ?

• JavaScript runs code sequentially in top-down order. However, there are some cases
that code runs (or must run) after something else happens and also not sequentially.
This is called asynchronous programming. Callbacks make sure that a function is not
going to run before a task is completed but will run right after the task has
completed. It helps us develop asynchronous JavaScript code and keeps us safe from
problems and errors.

20. What is callback hell ?

• Callback hell is a phenomenon that happens when multiple callbacks are nested on
top of each other. The two common ways of escaping the callback hell are by using
promises and async/await.

21. Difference between null & undefined ?

• Null is a special Object because typeof null returns object. A value explicitly set by
the programmer for the intentional lack of value.
• Undefined means that the variable has not been declared, or has not been given a
value. A value implicitly / explicitly set by the programmer for the intentional lack of
value.

- E.g.
- cl( null == undefined ) // true | let a = null | cl(a) // null
- cl( null === undefined ) // false | let b = undefined; let c; | cl(b,c);
- cl(typeof null) // object | cl(type of undefined) // undefined

22. What is NaN ?

• Ans 1 NaN is short for "Not-a-Number". NaN is a number that is not a legal number.
NaN is a property of the global object. In other words, it is a variable in global scope.
The Global NaN property is the same as the [Link] property.

23. Difference between undefined & undeclared ?

• Undeclared variables are those that do not exist in a program and are not declared.
If the program tries to read the value of an undeclared variable, then a runtime
Reference error is encountered.
• Undefined variables are those that are declared in the program but have not been
assigned / given any value. If the program tries to read the value of an undefined
variable, an undefined value is returned.

24. What are Global variables ?

• Variables declared Globally (outside any function) have Global Scope. Global
variables can be accessed from anywhere in a JavaScript program.
- E.g.
- var gloVar = 7;
- cl(gloVar);
-
- function gloIncr(){
- gloVar ++;
- cl(gloVar);
- }
- gloVar++;
- gloIncr();
- gloVar++;
- cl(gloVar);

25. What is event capturing & event bubbling ?

• Event Flow is the sequence or order in which the particular web page receives the
event.
• Event Bubbling when the user clicks (or any event) on the button, the click event
flows in this order from bottom element to top element when a child element is
nested in a parent element & set an event listener on both elements.
- E.g.
- [Link]("click",function(){ [Link]('Parent Element Invoked') });
- [Link]('click',function(){ [Link]('Child Element Invoked') });
• Event Capturing when the user clicks (or any event) on the button, the click event
flows in this order from top element to bottom element when a child element is
nested in a parent element & set an event listener on both elements.
- E.g.
- [Link]("click",function(){ [Link]('Parent Element Invoked') }, true);
- [Link]('click',function(){ [Link]('Child Element Invoked') });
26. Difference between Attribute & Property ?

• An Element has attributes & properties.


• An attribute is the initial state when rendered in DOM. Attributes are defined by
HTML. The value of an attribute is constant.
• A property is the current state. Properties are defined by the DOM. The value of a
property is variable. A property gives us access via JavaScript to read and write
different values.
- E.g.
- <input type=’text’ value=’0’>
- const inp = [Link](‘input’);
- cl([Link]); // ‘0’
- [Link] = 73;
- cl([Link]);
- Note. When the above HTML is parsed and rendered, the attribute’s value will be '0' and
of type string, not number. When we access [Link] (now We’re using DOM now),
we are talking to the property and not the attribute.
- [Link] - [Link]

27. Difference between Argument & Parameter ?

• Arguments are actual parameters, the values that are passed when a function is
called. Parameters are local variables which are assigned when a function is declared
& they’re called as Formal parameters as well.
- E.g.
- function add(a,b){ return a + b } // a & b are the parameters
- add(24,82); // 24 & 82 are the arguments

28. Explain setTimeout & setInterval ?

• setTimeout executes the code after x seconds.


• setInterval executes the code every x seconds.

29. Is javaScript Single threaded or multi threaded ?

• JavaScript is a single-threaded language, which means it has only one call stack that
is used to execute the program, it is synchronous in nature.
• The call stack is the same as the stack data structure and stacks are FILO that is First
In Last Out. Similarly, within the call stack, whenever a line of code gets inside the
call stack it gets executed and move out of the stack. In this way, JavaScript is a
single-thread language because of only one call stack.
• Since JavaScript is a single-threaded language, it is synchronous in nature. As the
name suggests synchronous means to be in a sequence, i.e. every statement of the
code gets executed one by one.
JavaScript is only asynchronous in the sense, for example, image processing or
making requests over the network like API calls.

30. What is JSON ?

• JavaScript Object Notation (JSON) is a standard text-based format for representing


structured data based on JavaScript object syntax. It is commonly used for
transmitting data in web applications (e.g., sending some data from the server to the
client, so it can be displayed on a web page, or vice versa).
- E.g.
- regObj = { nam : 'spo', kam : 'web' };
- jsObj = [Link](regObj);
- cl(jsObj);
- [Link]('lsItem',jsObj);
- rcObj = [Link]('lsItem');
- rtrvObj = [Link](rcObj);
- cl(rtrvObj);

31. How do you add key value pair in JS ?

• Below are the ways to add key value pair in an Object


- E.g.
- let obj3 = { name : ‘xyz’, score : 92 }
- let [Link] = ‘5.7ft’

32. What are pop up box available in JS ?

• An alert box is often used if you want to make sure information comes through to
the user. When an alert box pops up, the user will have to click "OK" to proceed.
[Link](‘someText) / alert(‘someText’)
• A confirm box is often used if you want the user to verify or accept something. When
a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
[Link] / confirm(‘someText’)
• 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. [Link]() /
[Link]("sometext","defaultText");

33. What are looping structures in JS ?

• Loops can execute a block of code a number of times.


• for - loops through a block of code a number of times
- E.g. for ( i = 0; i < [Link]; i++ ) { cl( arr[i] ) }
• for/in - loops through the properties of an object
- E.g. let person = { fname : ‘xyz’, lname : ‘kksl’, age : 92 }
- objectA = { fn : ‘pk’, score : 78 }
- for( let oa in objectA ) { cl(oa) } // fn score
• for/of - loops through the values of an iterable object
- E.g. numArr = [12,24,48]
- For(let na of numArr) { cl(na) } // 12,24,48
• While - loops through a block of code while a specified condition is true
- E.g. while (i < 10) {
text += "The number is " + i;
i++;
}
• Do/while - loops through a block of code while a specified condition is true
- E.g. do {
text += "The number is " + i;
i++;
}
while (i < 10);

34. What is variable typing in JS ?

• Javascript is loosely typed language. Javascript automatically adjusts the datatype


while assigning or reassigning the variable.
- E.g. let mg = ‘yda’; mg = 6; mg = true;
- Note. Type coercion
35. Data types in JS ?

• Primitive – string, number, Boolean, null, undefined, symbol etc


• Non-primitive – object, array, function

36. Difference between get & post ?

• The Hypertext Transfer Protocol (HTTP) is designed to enable communications


between clients and servers. HTTP works as a request-response protocol between a
client and server.
• The GET method is limited to a maximum number of characters, while the POST
method has no such limitation. This is because the GET method sends data through
the resource URL, which is limited in length, while the POST method sends data
through the HTTP message body, which has no such limitation.
• The GET method supports only string data types, while the POST method
supports different data types such as string, numeric, binary, and so on.
• GET requests remain in the browser history, POST requests do not remain in the
browser history.
• GET requests should never be used when dealing with sensitive data.

37. How to empty an array in JS effectively ?

• Instead of using pop() method in a loop, best way to redeclare it with an empty
array.
- E.g. let prevArr = [‘xj’,’fj’,’jsj’,’jdjj’,………,’jsl’,’uisi’]
- prevArr = [];

38. What is IIFE functions in JS ?

• An IIFE (Immediately Invoked Function Expression) is a function that runs the


moment it is invoked or called in the JavaScript event loop. Having a function that
behaves that way can be useful in certain situations. IIFEs prevent pollution of the
global JS scope. Now 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
IIFEs.
- E.g. ( function greet() { cl(‘hellow..’) } () ) // hellow..

39. What is asynchronous programming in js ?

• Asynchronous programming is a technique that enables your program to start a


potentially long-running task and still be able to be responsive to other events while
that task runs, rather than having to wait until that task has finished. With
asynchronous programming, JavaScript programs can start long-running tasks, and
continue running other tasks in paralell.

40. What is a pure function ?

• A Pure Function is a function (a block of code) that always returns the same result if
the same arguments are passed. It must return some value. & It should not be
dependent on any external variable.
- E.g. gst15 = amt => amt * 15 / 100;

41. What is shift & unshift in JS ?

• shift() removes first element from an Array


- E.g. [Link]()
• unshift() adds elements in the start o an Array
- E.g. [Link](‘CSK’,’RJ’)

42. What are different types of errors in JS ?

• There are a lot of types of errors in JS. We can categorize them in Internal errors,
Range errors, Reference errors, Syntax errors, Type error, Warnings etc.
- [Link] - [Link]
43. How to handle exception in JS ?

• Throw, and Try..Catch…Finally


• The try statement defines a code block to run (to try).
• The catch statement defines a code block to handle any error.
• The finally statement defines a code block to run regardless of the result.
• The throw statement defines a custom error.
- E.g.
- try {
- if([Link]() == "") throw "is empty";
- if(isNaN(x)) throw "is not a number";
- x = Number(x);
- if(x > 10) throw "is too high";
- if(x < 5) throw "is too low";
- }
- catch(err) {
- [Link] = "Input " + err;
- }
- finally {
- [Link]("demo").value = "finally";
- }

44. What is recursion function in JS ?

• When a function calls itself until someone stops it. & If no one stops it then it will
recurse / call itself forever.
- E.g.
- function recFun( num ){
- [Link](num);
- newNum = num - 1;
- if (newNum > -70) {
- recFun(newNum);
- }
- }
-
- recFun(16);

45. What is Higher Order function ?


• Higher Order Functions are functions that return a function or take in a function as
an argument. Eg. map, filter, sort, reduce, find etc
- E.g.
- - regNums = [2,3,8,27,64,81];
- - dblNums = [Link]( (rnm) => { return rnm * 2 } ); // 4,6,16,54,128,162
- - oddNums = [Link]( (rnf) -> { return rnf % 2 == 1 } ); // 3,27,81
- - findFirst = [Link]( ( rnff ) => rnff % 4 == 0 ); // 8
- - redTotal = [Link]( (total,rnr) => { return total = total + rnr }, 0 ) // 185
- [Link] - [Link]
callback-functions-4daad4856242

46. What are concept of timers in JS ?

• In JavaScript, a timer is created to execute a task or any function at a particular time.


Basically, the timer is used to delay the execution of the program or to execute the
JavaScript code in a regular time interval. With the help of timer, we can delay the
execution of the code. So, the code does not complete it's execution at the same
time when an event triggers or page loads.
• The setTimeout() function helps the users to delay the execution of code.
• The setInterval() executes the specified function repeatedly after a time interval.

47. What is AJAX in JS ?

• AJAX stands for Asynchronous JavaScript And XML.


• Read data from a web server - after the page has loaded
• Update a web page without reloading the page
• Send data to a web server - in the background
- E.g.
- <button type="button" onclick="loadDoc()">Change Content</button>
- function loadDoc() {
const xhttp = new XMLHttpRequest();
[Link] = function() {
[Link]("demo").innerHTML = [Link];
}
[Link]("GET", "ajax_info.txt", true);
[Link]();
}
- [Link] - [Link]
48. How AJAX works ?

• A browser built-in XMLHttpRequest object (to request data from a web server)
• JavaScript and HTML DOM (to display or use the data)
• AJAX allows web pages to be updated asynchronously by exchanging data with a
web server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.

- E.g.

- An event occurs in a web page (the page is loaded, a button is clicked)


- An XMLHttpRequest object is created by JavaScript
- The XMLHttpRequest object sends a request to a web server
- The server processes the request
- The server sends a response back to the web page
- The response is read by JavaScript
- Proper action (like page update) is performed by JavaScript
- [Link] - [Link]

49. What is async…await in JS ?

• async-await - To ease the promise chaining ( executing various asynchronous tasks /


function one by one ) - to reduce the chain of .then methods one after another.
- E.g.
async function inito(){
- try {
- let step1 = await submitResume();
- cl(step1);
- let step2 = await goInterview();
- cl(step2);
- }
- catch(err){
- cl(err);
- }
- }
-
- inito();

50. Use of Map object in JS ?

• A Map holds key-value pairs where the keys can be any datatype.
• A Map remembers the original insertion order of the keys.
• A Map has a property that represents the size of the map.
- E.g.
- const fruits = new Map([
- ["apples", 500],
- [9, 300],
- [true, 200]
- ]);
- [Link]("demo").innerHTML = [Link](‘apples’); // 500
- [Link] - [Link]

51. What is xmlHttp request in JS ?

• XMLHttpRequest (XHR) objects are used to interact with servers (Async


programming in JS). You can retrieve data from a URL without having to do a full
page refresh. This enables a Web page to update just part of a page without
disrupting what the user is doing.
• The constructor initializes an XMLHttpRequest. It must be called before any other
method calls.
- E.g.
- let xhr = new XMLHttpRequest();
- [Link]('GET', '[Link]
- [Link] = () => {
- if ([Link] === 200 ) {
- cl([Link]([Link]).id);
- }
- }
- [Link]();
- Note. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not
just XML.
- [Link] - [Link]
52. Advantages of Closure in JS ?

• A closure is the combination of a function bundled together (enclosed) with


references to its surrounding state (the lexical environment). In other words, a
closure gives you access to an outer function's scope from an inner function. In
JavaScript, closures are created every time a function is created, at function creation
time.
• They allow you to attach variables to an execution context.
• Variables in closures can help you maintain a state that you can use later.
• They provide data encapsulation.
• They help remove redundant code.
• They help maintain modular code.

- E.g.
- let parents = (books) => {
- let child = ( learn, exam ) => {
- finObj = {
- books, learn, exam
- }
- return finObj ;
- }
- return child;
- }
-
- onlyp = parents('history');
- // cl(onlyp);
- pnc = onlyp('8hrs','entryLevel');
- cl(pnc);

53. What is negative infinity in JS ?

• Number.NEGATIVE_INFINITY returns negative infinity. Number.NEGATIVE_INFINITY is "a


number lower than any other number".
- E.g.
- let x = Number.NEGATIVE_INFINITY; // -infinity
- let n = (-Number.MAX_VALUE) * 2; // -infinity
- let x = 100; x.NEGATIVE_INFINITY; // undefined
54. What is ‘this’ keyword in JS ?

• In JavaScript, the ‘this’ keyword refers to an object. Which object depends on


how this is being invoked (used or called).
• In an object method, this refers to the object.
• Alone, this refers to the global object.
• In a function, this refers to the global object.
• In an event, this refers to the element that received the event.
- E.g. 1
- const person = {
- firstName: "John",
- id: 5566,
- fullName : function() {
- return [Link]; // [Link]
- }
- };
- E.g.2
- panky = '78'; let x = this;
- [Link]("demo").innerHTML = [Link];
- E.g.3
- suky = 88;
- [Link]("demo").innerHTML = myFunction();
- function myFunction() {
- return [Link];
- }
- Note.
- [Link] - [Link]

55. What is the difference between alert & confirm box ?


- An alert box is often used if you want to make sure information comes through
to the user. When an alert box pops up, the user will have to click "OK" to
proceed. [Link](‘someText) / alert(‘someText’). Eg. You agree to terms.
- A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed. [Link] / confirm(‘someText’). Eg. Go ahead ? Yes / No.

56. What is arrow function in JS ?

• Arrow functions were introduced in ES6. Arrow functions allow us to write shorter
function syntax.
- E.g.
- function sum( a,b ) { return a + b }
- let sum = (a,b) => { return a + b }
- let sum = (a,b) => a + b;

57. New features in ES6 ?

• Ans ECMAScript 2015 was the second major revision to JavaScript. CMAScript 2015 is
also known as ES6 and ECMAScript 6. It introduced let, const, arrow functions, ‘…’
spread operator, [Link](), for…of, map objects, set objects, classes, promises,
symbol, default parameters, includes(), startsWith(), endsWith()etc
- [Link] - [Link]

58. List array methods ?

• push(), pop(), shift(), unshift(), toString(), join(), concat(), reverse(), splice(), slice() etc

59. Difference between call() & apply() ? Difference between spread operator & rest
parameter ?

• With the call() method, you can write a method that can be used on different
objects.
- E.g.
- const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return [Link] + " " + [Link];
}
}
- [Link](); // John Doe
• With the apply() method, you can write a method that can be used on different
objects.
- E.g.
- const person = {
fullName: function() {
return [Link] + " " + [Link];
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}

[Link](person1); // Mary Doe


-
• With The spread operator helps us expand an iterable such as an array where
multiple arguments are needed.
- E.g.
- var arr1 = [1,2,3]; var arr2 = [4,5]; var combArr = […arr1,…arr2];
• The rest parameter (...) allows a function to treat an indefinite number of arguments
as an array
- E.g.
- function sum(...args) {
let sum = 0;
for (let arg of args) { sum += arg; }
return sum;
}

let x = sum(4, 9, 16, 25, 10, 77);

61. How to remove duplicate elements in an array ?

• using indexOf & index number


- E.g.
arrayDupl = [34,24,56,29,24,57,34];
- [Link]( ( elm, i ) => {
- if ( [Link](elm) !== i ) {
- arrayDupl[i]='tbd';
- [Link](i,1);
- }
- });
- cl(arrayDupl);

61. What is the output of 1 + 1 + ‘hellow’ ?

• Answer --> 2hellow


62. What is the output of ‘hellow’ + 1 + 1 ?

• Answer --> hellow11

63. How to get even/odd no out from arrat x=[1,1,2,3,4,5,6,7,8] ?

• Ansswer -->
arrayX = [1,1,2,3,4,5,6,7,8];
- arrayOdd = [Link]( axf => axf%2 === 1 )
- arrayEven = [Link]( axf => axf%2 === 0 )
- cl(arrayX, arrayOdd, arrayEven);

64. What is the output of the number + boolean ?

• Number
- E.g. 9 + true --> 10 | 18 + false --> 18

65. Output of [Link]([1,2]+[1,2]) ?

• Answer --> 1,21,2


- E.g.
- cl([1,2]+[1,2]); // 1,21,2
- cl([1,2,3]+[1,2,3]); // 1,2,31,2,3
- cl([1,2,3]+[4,5]); // 1,2,34,5

66. What is o/p of NaN === NaN ?

• Answer --> false


• The NaN global property is a value representing Not-A-Number.
• NaN (Not a Number) is the result of a numeric expression when it cannot produce a
valid numeric result.
• Consider log(−2) and log(−3). Both those expression will return NaN (since this no
real number that is the log of a negative).
• But if you define Nan === Nan to be true, then you can conclude that log(−2) ===
log(−3), Even they are not.

67. What is IIFE functions in JS ?

• An IIFE (Immediately Invoked Function Expression) is a function that runs the


moment it is invoked or called in the JavaScript event loop. Having a function that
behaves that way can be useful in certain situations. IIFEs prevent pollution of the
global JS scope. Now 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
IIFEs.
- E.g. ( function greet() { cl(‘hellow..’) } () )

68. What is anonymous function in JS ?

• An a function that doesn't need a name, you only need it for the purpose of a single
callback.
- E.g.
- var funHelloww = function() {
- cl('hellowwwiy');
- }
-
- funHelloww();
-
- setTimeout( () => {
- cl('anony fun after 1 sec')
- }, 1000 )

69. String methods in javaScript ?

• split(), toLowerCase(), toUpperCase(), subStr(), subString(), indexOf(), includes(),


trim(), concat(), slice(), charAt(), string_name[],
70. Definition of Javascript ?

• JavaScript is a dynamic programming language that's used for web development, in


web applications, for game development, and lots more. It allows you to implement
dynamic features on web pages that cannot be done with only HTML and CSS.
• We can use javaScript using inline javascript, internal javascript, external javascript.

71. How to compare two objects in javascript ?

• Ans 1
- E.g.
obj1 = { fname : 'spo', score : 99 };
- obj2 = { fname : 'spo', score : 91 };
-
- const obj1keys = [Link](obj1);
- const obj2keys = [Link](obj2);
-
- if ( [Link] === [Link] ) {
- cl('length is same, compare now');
- for ( let key of obj1keys ) {
- if (obj1[key] === obj2[key]) {
- cl('same');
- }
- else {
- cl('not same');
- }
- }
- }
-
• Ans 2
- E.g.
- if ([Link](obj1) == [Link](obj2)){
- cl('dicto same');
- }
72. What is InstanceOf Operator in JavaScript ?

• The JavaScript instanceof operator is used to check the type of an object at the run
time. It returns a boolean value(true or false). If the returned value is true, then it
indicates that the object is an instance of a particular class and if the returned value
is false then it is not.
- E.g.
function Car(make, model, year) {
[Link] = make;
[Link] = model;
[Link] = year;
- }
-
- const auto = new Car('Honda', 'Accord', 1998);
-
- [Link](auto instanceof Car); // true
-
- [Link](auto instanceof Object); // true
-
- const bike = { make : 'bjaj', model : 'dtsi', year : 2008 }
-
- [Link](bike instanceof Car); // false
-
- [Link](bike instanceof Object); // true

73. What is strict mode in JS ?

• Ans 1 Strict Mode was a new feature in ECMAScript 5 that allows you to place a
program, or a function, in a “strict” operating context.
• Strict mode can be used in two ways, remember strict mode doesn’t work with block
statements enclosed in {} braces.
• Used in global scope for the entire script.
• It can be applied to individual functions.
- E.g.
function myFunc() {
- "use strict";
- yStrict = 'It is not allowed in strict mode';
- cl(yStrict);
- }
- myFunc();
74. What is super function in JavaScript ?

• The super keyword is used to call the constructor of its parent class to access the
parent's properties and methods. It helps in inheriting the methods from the parent
class, by using the extends keyword. By calling the super() method in the constructor
method, we call the parent's constructor method and gets access to the parent's
properties and methods.
- E.g.
- class parentClass {
- // coreKnowledge;
- constructor( blessings, coreKnowledge ){
- [Link] = 'fixed';
- [Link] = coreKnowledge;
- }
- }
- const pc1 = new parentClass('','business');
- cl(pc1);
-
- class childClass extends parentClass {
- constructor( blessings, coreKnowledge, makeAdvance ){
- super(blessings, coreKnowledge);
- [Link] = makeAdvance;
- }
- }
-
- const cc1 = new childClass('','superBizz','Digital Mkting');
- cl(cc1);

75. Difference between Slice and Splice method in JavaScript? ?

• The slice() method can be used to create a copy of an array or return a portion of an
array. It is important to note that the slice() method does not alter the original array
but instead creates a shallow copy. Unlike the slice() method, the splice() method
will change the contents of the original array.
- E.g.
- regArr = [10,20,30,40,50,60,70];
-
- let slicedArr = [Link](3,5);
- cl(slicedArr,regArr);
-
- let splicedArr = [Link](3,2);
- cl(splicedArr,regArr);
76. What is bind in javaScript ?
Ans 1 Variables has local and global scopes. Let's suppose that we have two variables with
the same name. One is globally defined and the other is defined inside a function closure
and we want to get the variable value which is inside the function closure. In that case we
use this bind() method.
- E.g.
- let gj = 'variable in Global scope';
-
- var person = {
- gj : 'variable of person object',
- getGj : function(){
- return [Link];
- }
- }
-
- cl(`${ gj } - ${ [Link] } - ${ [Link]() }`);
-
- var pgj = [Link];
- var myFunc = [Link](person)
- cl(myFunc());
- cl(pgj);

77. What is call by value and call by reference in JavaScript?

• In Pass by value, parameters passed as an arguments create its own copy. So any
changes made inside the function is made to the copied value not to the original
value.
• In Pass by reference, parameters passed as an arguments does not create its own
copy, it refers to the original value so changes made inside function affect the
original value.
- E.g. Pass by Value
- function Passbyvalue(a, b) {
- let tmp;
- tmp = b;
- b = a;
- a = tmp;
- [Link](`Inside Pass by value function -> a = ${a} b = ${b}`);
- }
- let a = 1; let b = 2;
- [Link](`Before calling Pass by value Function -> a = ${a} b = ${b}`);
- Passbyvalue(a, b);
- [Link](`After calling Pass by valueFunction -> a =${a} b = ${b}`);
-
- E.g. Pass by Reference
- function PassbyReference(obj) {
- let tmp = obj.a;
- obj.a = obj.b;
- obj.b = tmp;
- [Link](`Inside Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);
- }
- let obj = { a: 10, b: 20 }
- [Link](`Before calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);
- PassbyReference(obj)
- [Link](`After calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);
-

78. What is event capturing & event bubbling ?

• Event Flow is the sequence or order in which the particular web page receives the
event.
• Event Bubbling when the user clicks (or any event) on the button, the click event
flows in this order from bottom element to top element when a child element is
nested in a parent element & set an event listener on both elements.
• Event Capturing when the user clicks (or any event) on the button, the click event
flows in this order from top element to bottom element when a child element is
nested in a parent element & set an event listener on both elements.

79. What is event bubbling ?

• Event Bubbling when the user clicks (or any event) on the button, the click event
flows in this order from bottom element to top element when a child element is
nested in a parent element & set an event listener on both elements.
- E.g.
- [Link]("click",function(){ [Link]('Parent Element Invoked') });
- [Link]('click',function(){ [Link]('Child Element Invoked') });
• Event Capturing when the user clicks (or any event) on the button, the click event
flows in this order from top element to bottom element when a child element is
nested in a parent element & set an event listener on both elements.
- E.g.
- [Link]("click",function(){ [Link]('Parent Element Invoked') }, true);
- [Link]('click',function(){ [Link]('Child Element Invoked') });

80. Difference between javaScript & typescript ?

• When JavaScript was developed, the JavaScript development team introduced


JavaScript as a client-side programming language. But as people were using
JavaScript, developers also realized that JavaScript could be used as a server-side
programming language. However, as JavaScript was growing, JavaScript code
became complex and heavy. Because of this, JavaScript wasn’t even able to fulfill the
requirement of an Object-Oriented Programming language. This prevented
JavaScript from succeeding at the enterprise level as a server-side technology.
So TypeScript was created by the development team to bridge this gap.
• TypeScript is a superset of javaScript.
• JavaScript is TypeScript - Whatever code is written in JavaScript can be converted to
TypeScript by changing the extension from .js to .ts.
• TypeScript Code is converted into Plain JavaScript Code - TypeScript code can’t be
natively interpreted by browsers. So if the code was written in TypeScript, it gets
compiled and converted into JavaScript. This process is known as Trans-piled. With
the help of JavaScript code, browsers are able to read the code and display it.
• TypeScript is known as an Object-oriented programming language whereas
JavaScript is a prototype-based language.
• TypeScript has a feature known as Static typing but JavaScript (Dynamically Typed)
does not support this feature.
• TypeScript supports Interfaces but JavaScript does not.
• Stronger typing can help identify errors. But in JS, May require more debugging and
testing.

81. Difference between JavaScript and jQuery ?

• JavaScript is an independent language and can exist on its own. JQuery is a JavaScript
library. It would not have been invented had JavaScript was not there. jQuery is still
dependent on JavaScript as it has to be converted to JavaScript for the browser in-
built JavaScript engine to interpret and run it.
• JavaScript uses JIT[Just in Time Compiler] which is a combination of interpreter and
Compile and is written in C. It’s a combination of ECMA script and DOM (Document
Object Model). While JQuery Uses the resources that are provided by JavaScript to
make things easier. It is a lightweight JavaScript library. It has only the DOM.
• JavaScript uses long lines of code as an individual has to write the code own-self.
With JQuery, one has to write fewer lines of code than JavaScript.
• Pure JavaScript can be faster for DOM selection/manipulation than jQuery as
JavaScript is directly processed by the browser. JQuery has to be converted into
JavaScript to make it run in a browser.
• In javaScript, animation is a bit difficult but in we can add animation effects easily
with fewer lines of code in jQuery.
• JavaScript is a programming language. jQuery is an Application Programming
Interface (API).

82. Advantages of Closures ?

• A closure is the combination of a function bundled together (enclosed) with


references to its surrounding state (the lexical environment). In other words, a
closure gives you access to an outer function's scope from an inner function. In
JavaScript, closures are created every time a function is created, at function creation
time.
• Encapsulation
• State Retention
• Currying
• Memorization
• Asynchronous Programming
• Event handling

- E.g.
- function makeFunc() {
- const name = "Mozilla";
- function displayName() {
- [Link](name);
- }
- return displayName;
- }
- const myFunc = makeFunc();

myFunc();

[Link] - [Link]
--. Que ?

• Ans 1
- E.g.
- Note.
- [Link] -
• Ans 2
- E.g.
- Note.
- [Link] -

You might also like