Search This Blog

Q51-Q55

Q51. How JavaScript support asynchronous behavior?
Q52. What is a difference between callbacks and promises in JavaScript?
Q53. how to create a clone of object in JavaScript?
Q54. What are undeclared and undefined variables in JavaScript?
Q55. In how many ways you can clear Arrays in JavaScript?
--------------------------------------------------------------------------------------------------------------------------
Q51. How JavaScript support asynchronous behavior?

Answer: 
It can be done through 
  • Ajax (asynchronous JavaScript and xml) calls, 
  • Callback functions,
  • Javascript ES6 promises and 
  • RXJS observables.
--------------------------------------------------------------------------------------------------------------------------
Q52. What is a difference between callbacks and promises in JavaScript?

Answer : 
  • Promises and callbacks are fundamentally same.
  • Promises are introduced in ES6
  • With promises we have much cleaner code with keyword .then() to handle returning result otherwise callback hell will seen in callback.
  • With promises we have .catch() to catch error in much cleaner way.
Callback hell is an anti pattern  which means callback function inside a callback function. It would tough to maintain and readiliby is also not good with callbacks. 

http://qnimate.com/javascript-promise-vs-callback/
--------------------------------------------------------------------------------------------------------------------------
Q53. how to create a clone of object in JavaScript?

Answer  53: 

Deep copy is also known as Cloning. 
There are two ways to copy objects in JavaScript. Both  ways to make a copy by value of objects as by default objects copy by reference. 
one is to make shallow copy and other is to make a deep copy.

Simple deep copy can be made by way JSON.parse(JSON.stringify(objA)).

--------------------------------------------------------------------------------------------------------------------------
Q54. What are undeclared and undefined variables in JavaScript?

Answer 54:


1) In normal practice we first declare a variable and then define it.
2) var a, is declaring a variable. Here it is declared but undefined.
3) a = 30, giving some value to a variable is defining a variable.

(function(){
 var a; //declared but undefined
  console.log(a); //undefined

  var b;
  b = 10;
  // both declared and defined.

  c=12;
  // both declared and defined but declared globally.
})();

--------------------------------------------------------------------------------------------------------------------------
Q55. In how many ways you can clear Arrays in JavaScript?

Answer 55:
  1. assign array to empty array.
  2. make array.length = 0.
  3. using splice. use array.splice(0, array.length)
  4. pop all elements using for loop.
--------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment