JavaScript Object Creation & Concepts
JavaScript Object Creation & Concepts
--------------------------------------------------------------------------------------------------------------------------
Questions
• 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
• 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.
• 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.
• 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
• 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.
• 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] -
• 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] -
• 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]().
• 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.
• 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.
• 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
• 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.
• 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.
• 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);
• 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 ?
• 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
• 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.
• 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");
• 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 = [];
• 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;
• 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 ?
• 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);
• 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.
• 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]
• 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;
• 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]
• 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"
}
• 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);
• Number
- E.g. 9 + true --> 10 | 18 + false --> 18
• 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 )
• 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
• 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);
• 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);
• 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}`);
-
• 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.
• 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') });
• 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).
myFunc();
[Link] - [Link]
--. Que ?
• Ans 1
- E.g.
- Note.
- [Link] -
• Ans 2
- E.g.
- Note.
- [Link] -