• ES6 Interview Questions and Answers 2024

    ES6 interview questions, Top Es6 Interview Questions

    Are you a qualified ECMAScript programmer who works on client-side scripting on the internet? If yes, then more training in ECMAScript 6 will certainly help you to crack ES6 interview questions and open the door to more opportunities for you. As an ECMAScript 6 developer, you will be able to use a new syntax to write more complex applications that involve various classes and modules.

    With features such as arrow functions, typed arrays, and math improvements, you can train yourself to build larger applications as well as libraries. IndiaHires will provide you all the information as to how you can crack ES6 interview questions and answers 2024

    SQL Interview Questions and Answers

    ES6 interview questions list

    1. What is ES6?Define ES6 and mention the new features of ES6?
    2. Could you explain the difference between ES5 and ES6?
    3. Explain about Internationalization and localization?
    4. What is IIFEs (Immediately Invoked Function Expressions)?
    5. When should I use Arrow functions in ES6?
    6. What are the differences between ES6 class and ES5 function constructors?
    7. Why do we need to use ES6 classes?
    8. What is Hoisting in JavaScript?
    9. What is the motivation for bringing Symbols to ES6?
    10. What are the advantages of using spread syntax in ES6, and how is it different from rest syntax?
    11. Explain the Prototype Design Pattern?
    12. What is the difference between .call and .apply?
    13. What are the actual uses of ES6 WeakMap?
    14. What is the difference between ES6 Map and WeakMap?
    15. How to “deep-freeze” object in JavaScript?
    16. What is the preferred syntax for defining enums in JavaScript?
    17. Explain the difference between Object.freeze() vs const?
    18. When are you not supposed to use the arrow functions in ES6? Name three or more cases.
    19. Can you give an example of a curry function, and why does this syntax have an advantage?
    20. What are the template literals in ES6?
    21. What do you understand by Generator function?

    Below are the new features listed

    1. Constants (Immutable variables)
    2. Scoping
    3. Arrow functions
    4. Extended parameter handling
    5. Template literals
    6. Extended literals
    7. Modules
    8. Classes
    9. Enhanced Regular expressions
    10. Enhanced object properties.
    11. Destructuring Assignment
    12. Symbol Type
    13. Iterators
    14. Generator
    15. Map/Set & WeakMap/WeakSet
    16. Typed Arrays
    17. Built-in Methods
    18. Promises
    19. Meta programming
    20. Internationalization and Localization.

    ECMAScript 5 (ES5):

    The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers

    ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015):

    The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers.

    Here are some key differences between ES5 and ES6:

    1. Arrow functions & string interpolation:
       
        
          const greetings = (name) => {
              return `hello ${name}`;
          }
      
          const greetings = name => `hello ${name}`;   
        
      
    2. Const

      Const works like a constant in other languages in many ways but there are some caveats. Const stands for ‘constant reference’ to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can’t change the reference itself.

       
        
          const NAMES = [];
          NAMES.push("Jim");
          console.log(NAMES.length === 1); // true
          NAMES = ["Steve", "John"]; // error   
        
      
    3. Block-scoped variables

      The new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.

    4. Default parameter values

      Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value

       
        
          // Basic syntax
          function multiply (a, b = 2) {
               return a * b;
          }
          multiply(5); // 10  
        
      
    5. Class Definition and Inheritance

      ES6 introduces language support for classes (class keyword), constructors (constructor keyword), and the extend keyword for inheritance.

    6. for-of operator

      The for…of statement creates a loop iterating over iterable objects

    7. Spread Operator

      For objects merging

       
        
          const obj1 = { a: 1, b: 2 }
          const obj2 = { a: 2, c: 3, d: 4}
          const obj3 = {...obj1, ...obj2}
        
      
    8. Promises

      Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.

       
        
          const isGreater = (a, b) => {
            return new Promise ((resolve, reject) => {
              if(a > b) {
                resolve(true)
              } else {
                reject(false)
              }
              })
          }
          isGreater(1, 2)
            .then(result => {
              console.log('greater')
            })
           .catch(result => {
              console.log('smaller')
           })
        
      
    9. Modules exporting & importing
       
        
          const myModule = { x: 1, y: () => { console.log('This is ES5') }}
          export default myModule;
        
      
       
        
          import myModule from './myModule';
        
      

    These are APIs that are standard JavaScript APIs that help with different tasks such as collation, number formatting, currency formatting, date and time formatting.

    • Collation

      It is used to search within a set of strings and sort a set of strings. It is parametrized by the locale and Unicode-conscious.

    • Number Formatting

      Numbers can be formatted with localized separators and digit groupings. Other things that include style formatting, numbering, percent, and precision.

    • Currency formatting

      Numbers can be formatted mainly with currency symbols, with localized separators and digit groupings.

    • Date and time formatting

      It has been formatted and ordered with localized separators. The format can be short, long and other parameters, such as the locale and time zone.

    It’s an Immediately Invoked Function Expression, or an IIFE for short. It will run immediately after it has been created:

    	
    	
    		(function IIFE(){
    		    console.log( "Hello!" );
    		})();
    		// "Hello!"		
    	
    

    This pattern is often used when trying to avoid contaminating the global namespace, because all variables used inside the IIFE (like any other normal function) are not visible outside its scope.

    I am now using the following thumb rule for functions in ES6 and beyond:

    • Use function in the global scope and for Object.prototype properties.
    • Use class for object constructors.
    • Use => everywhere else.

    Why use arrow functions almost everywhere?

    • Scope safety

      When arrow functions are used consistently, everything is guaranteed to use the same object as the root. If even a single standard function callback is mixed in with a bunch of arrow functions, there’s a chance that the scope will get messed up.

    • Compactness

      The Arrow functions are easier to read and write to. (This may seem to be an opinion, so I’m going to give a few more examples).

    • Clarity

      When almost everything is an arrow function, any regular function immediately sticks out to define the scope. The developer can always look up the next-higher function statement to see what the object is.

    Let’s first look at example of each:

     
      
        // ES5 Function Constructor
        function Person(name) {
          this.name = name;
        }
    
        // ES6 Class
        class Person {
          constructor(name) {
            this.name = name;
          }
        }   
      
    

    For simple constructors, they look pretty similar.

    The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

     
      
        // ES5 Function Constructor
        function Student(name, studentId) {
          // Call constructor of superclass to initialize superclass-derived members.
          Person.call(this, name);
    
          // Initialize subclass's own members.
          this.studentId = studentId;
        }
    
        Student.prototype = Object.create(Person.prototype);
        Student.prototype.constructor = Student;
    
        // ES6 Class
        class Student extends Person {
          constructor(name, studentId) {
            super(name);
            this.studentId = studentId;
          }
        }   
      
    

    Some of the reasons you might choose to use Classes:

    • Syntax is simpler and less error prone.
    • It’s much easier (and again, less error-prone) to set up inheritance hierarchies using the new syntax than the old one.
    • Class defends you from the common error of not using a new constructor function (by having the constructor throw an exception if this is not a valid constructor object).
    • Calling the parent prototype version of the method is much simpler with a new syntax than the old one (super.method() instead of ParentConstructor.prototype.method.call(this) or Object.getPrototypeOf(Object.getPrototypeOf(this)).

    Consider:

     
      
        / **ES5**
        var Person = function(first, last) {
            if (!(this instanceof Person)) {
                throw new Error("Person is a constructor function, use new with it");
            }
            this.first = first;
            this.last = last;
        };
    
        Person.prototype.personMethod = function() {
            return "Result from personMethod: this.first = " + this.first + ", this.last = " + this.last;
        };
    
        var Employee = function(first, last, position) {
            if (!(this instanceof Employee)) {
                throw new Error("Employee is a constructor function, use new with it");
            }
            Person.call(this, first, last);
            this.position = position;
        };
        Employee.prototype = Object.create(Person.prototype);
        Employee.prototype.constructor = Employee;
        Employee.prototype.personMethod = function() {
            var result = Person.prototype.personMethod.call(this);
            return result + ", this.position = " + this.position;
        };
        Employee.prototype.employeeMethod = function() {
            // ...
        };  
      
    

    In ES6 classes

     
      
        // ***ES2015+**
        class Person {
            constructor(first, last) {
                this.first = first;
                this.last = last;
            }
    
            personMethod() {
                // ...
            }
        }
    
        class Employee extends Person {
            constructor(first, last, position) {
                super(first, last);
                this.position = position;
            }
    
            employeeMethod() {
                // ...
            }
        } 
      
    

    Hoisting is the action of the JavaScript interpreter to move all the variables and function declarations to the top of the current scope. There are two types of hoists:

    1. variable hoisting – rare
    2. function hoisting – more common

    Where a var (or function declaration) appears within the scope of the declaration, it shall be taken to belong to the whole scope and shall be accessible everywhere.

    	
    	
    		var a = 2;
    		foo();                 // works because `foo()`
    		                         // declaration is "hoisted"
    
    		function foo() {
    		    a = 3;
    		    console.log( a );   // 3
    		    var a;             // declaration is "hoisted"
    		                         // to the top of `foo()`
    		}
    
    		console.log( a );   // 2
    	
    

    21 React JS Interview Questions and Answers

    Symbols are a new, special type of object that can be used as a unique property name in objects. Using Symbol instead of string allows different modules to create properties that do not conflict with each other. Symbols can also be made private, so that no one who does not already have direct access to the Symbol can access their properties.

    Symbols are a new primitive thing. Just like the number, string, and boolean primitives, the symbol has a function that can be used to create them. Unlike other primitives, the symbols do not have a literal syntax (e.g. how string have '') “-the only way to create them is with the symbol constructor in the following way:

    	
    	
    		let symbol = Symbol();
    	
    

    In reality, Symbol's is just a slightly different way of attaching properties to an object-you could easily provide well-known Symbols as standard methods, just like Object.prototype.hasOwnProperty, which appears in everything that inherits from Object.

    ES6 spread syntax is very useful when coding in a functional paradigm as you can easily create copies of arrays or objects without using Object.create, slice, or a library function. This language feature is often used in Redux and rx.js projects.

    	
    	
    		function putDookieInAnyArray(arr) {
    		  return [...arr, 'dookie'];
    		}
    
    		const result = putDookieInAnyArray(['I', 'really', "don't", 'like']); // ["I", "really", "don't", "like", "dookie"]
    
    		const person = {
    		  name: 'Todd',
    		  age: 29,
    		};
    
    		const copyOfTodd = { ...person };
    	
    

    The rest syntax of ES6 offers a shorthand for including an arbitrary number of arguments to be passed to a function. It’s like the inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking array of data, and it works in function arguments, as well as in array and object destructuring assignments.

    	
    	
    		function addFiveToABunchOfNumbers(...numbers) {
    		  return numbers.map(x => x + 5);
    		}
    
    		const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15]
    
    		const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4]
    
    		const { e, f, ...others } = {
    		  e: 1,
    		  f: 2,
    		  g: 3,
    		  h: 4,
    		}; // e: 1, f: 2, others: { g: 3, h: 4 }
    	
    

    The Prototype Pattern creates new objects, but instead of creating non-initialized objects, it returns objects that are initialized with values copied from a prototype-or sample-object. The pattern of the prototype is also referred to as the pattern of the properties.

    An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values of the database. The prototype object holds the default values that are copied to the newly created business object.

    Classical languages rarely use the Prototype pattern, but the JavaScript being a prototype language uses this pattern in the construction of new objects and their prototypes.

    Both .call and .apply are used to invoke functions, and the first parameter will be used as the value of this within the function. However, .call takes the comma-separated arguments as the next arguments, while .apply uses the array of arguments as the next argument. An easy way to remember this is C for a call and a comma-separated and A for apply and an array of arguments.

    	
    	
    		function add(a, b) {
    		  return a + b;
    		}
    
    		console.log(add.call(null, 1, 2)); // 3
    		console.log(add.apply(null, [1, 2])); // 3	
    	
    

    WeakMaps provide a way to extend objects from the outside without interference with garbage collection. Whenever you want to extend an object, but can’t apply a WeakMap because it is sealed-or from an external source.

    WeakMaps provide a way to extend objects from the outside without interference with garbage collection. Whenever you want to extend an object, but can’t apply a WeakMap because it is sealed-or from an external source.

    	
    	
    		var map = new WeakMap();
    		var pavloHero = {
    		    first: "Pavlo",
    		    last: "Hero"
    		};
    		var gabrielFranco = {
    		    first: "Gabriel",
    		    last: "Franco"
    		};
    		map.set(pavloHero, "This is Hero");
    		map.set(gabrielFranco, "This is Franco");
    		console.log(map.get(pavloHero)); //This is Hero	
    	
    

    The interesting aspect of the WeakMaps is that it has a weak reference to the key inside the map. A weak reference means that if the object is destroyed, the garbage collector will remove the entire entry from the WeakMap, freeing up memory.

    They both behave differently when the object referred to by their keys / values is deleted. Take the following example code:

    var map = new Map();

    var weakmap = new WeakMap();

    	
    	
    		(function() {
    		    var a = {
    		        x: 12
    		    };
    		    var b = {
    		        y: 12
    		    };
    
    		    map.set(a, 1);
    		    weakmap.set(b, 2);
    		})()
    	
    

    The above IIFE is executed there is no way we can refer to {x:12} and {y:12}. The Garbage Collector goes ahead and removes the “WeakMap” key b pointer and also removes {y:12} from memory. But in the case of “Map,” the garbage collector does not remove a pointer from “Map” and does not remove {x:12} from memory.

    WeakMap allows the garbage collector to do his job, but not Map. With manually written maps, the key array would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are kept “weakly” which means that they do not prevent the collection of garbage in the event that there is no other reference to the object.

    If you want to make sure that the object is deep frozen, you need to create a recursive function to freeze each property that is of the object type:

    Without deep freeze:
    	
    	
    	let person = {
    		name: "Leonardo",
    		profession: {
    			name: "developer"
    		}
    	};
    	Object.freeze(person); // make object immutable
    	person.profession.name = "doctor";
    	console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }
    	
    
    With deep freeze:
    	
    	
    	function deepFreeze(object) {
    	    let propNames = Object.getOwnPropertyNames(object);
    	    for (let name of propNames) {
    	        let value = object[name];
    	        object[name] = value && typeof value === "object" ?
    	            deepFreeze(value) : value;
    	    }
    	    return Object.freeze(object);
    	}
    	let person = {
    	    name: "Leonardo",
    	    profession: {
    	        name: "developer"
    	    }
    	};
    	deepFreeze(person);
    	person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of object
    	
    

    Since 1.8.5 it’s possible to seal and freeze the object, so define the above as:

    	
    	
    		const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
    	
    
    Or
    	
    	
    		const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
    		Object.freeze(DaysEnum);
    	
    

    and voila! JS enums.

    However, this does not prevent you from assigning an undesired value to a variable, which is often the main goal of the enums:

    	
    	
    	let day = DaysEnum.tuesday
    	day = 298832342 // goes through without any errors
    	
    

    Since its release, ES6 has introduced several new features and methods to JavaScript. Among these new features are the method and const of Object.freeze(). Sometimes people get confused between the method Object.freeze() and the const but Object.freeze() and the const are completely different.

    Const:

    The const keyword generates a read-only reference to a value. The variables generated by the const keyword are immutable. In other words, you can’t reassign them to a variety of values. Trying to reassign a constant variable will result in a TypeError.

    	
    	
    		let myName = "indiahires"
    	    console.log(myName)  
    	  
    	    // Uncaught TypeError 
    	    myName = "ih" 
    	
    

    The const keyword ensures that the created variable is read-only. But it doesn’t mean that the actual value to which the reference to the const variable is immutable. Even though the variable person is constant. However, you can change the value of your property. But you can not reassign a different value to a constant person.

    	
    	
    		const person = { 
    	        name: "indiahires"
    	    }; 
    	          
    	// No TypeError 
    	person.name = "ih"; 
    	console.log(person.name);  
    	
    
    Object.freeze() method:

    If you want the value of the person object to be immutable, you have to freeze it using the Object.freeze() method.

    	
    	
    	const person = Object.freeze({name: "indiahires"});      
         // TypeError 
         person.name = "ih";  
    	
    

    The method Object.freeze() is shallow, which means that it can freeze the properties of the object, not the objects referenced by the properties.

    	
    	
    	const person = Object.freeze({ 
    	    name: 'indiahires', 
    	    address: { 
    	        city:"Chandigarh"
    	    } 
    	});  
    
    	/*But the person.address object is not immutable, you can add a new property to the person.address object as follows:*/
    
    	// No TypeError
    	person.address.country = "India";
    	
    
    Final words

    const prevents reassignment.

    Object.freeze() prevents mutability.

    Arrow functions should NOT be used:

    1. When we want function hoisting – as arrow functions are anonymous.
    2. When we want to use this/arguments in a function – as arrow functions do not have this/arguments of their own, they depend upon their outer context.
    3. When we want to use named function – as arrow functions are anonymous.
    4. When we want to use function as a constructor – as arrow functions do not have their own this.
    5. When we want to add function as a property in object literal and use object in it – as we can not access this (which should be object itself).

    Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, accumulates all the required parameters one at a time. This technique can be useful to make it easier to read and compose code written in a functional style. It is important to note that if a function is to be cured, it needs to start as a single function, and then break out into a sequence of functions, each of which accepts a single parameter.

    There is a lot of mathematical and computer science theory behind currying in functional programming and I encourage you to read more on Wikipedia. Interesting fact: Currying is named after a mathematician Haskell Curry, not the food.

    Basic example:

    	
    	
    		const sum = x => y => x + y;
    		// returns the number 3
    		sum (2)(1);
    		// returns a function y => 2 + y
    		sum (2);	
    	
    

    Note that sum (2)(1); produces the same result as we would have had if we had defined it as const sum = (x , y) = > x + y; which we would call const sum = (x , y) = > x + y; Summary (2 , 1);.

    If seeing more than one arrow gives you trouble, just realize that you are simply returning everything that is behind the first arrow. In this case it’s returning another function as its return value because JavaScript has first-class functions. Also this approach works, because the nested returned function has access to the scope of its parent function and so conveniently the y => x + y gets the x from its parent.

    First class functions

    in functional programming JavaScript has first class functions because it supports functions as arguments and return values.

    	
    	
    		const someFunction = () => console.log ('Hello World!');
    		const firstClass1 = functionAsArgument => functionAsArgument ();
    
    		firstClass1(someFunction); // Hello World! is printed out
    
    		const firstClass2 = () => someFunction;
    
    		firstClass1 (firstClass2()); // Hello World! is printed out	
    	
    

    Practical example: curry as a partial application

    This is an example of partially applied function versus curry function, both doing the same thing using JQuery “on” function:

    	
    	
    		const partiallyAppliedOnClick = handler => $ ('button').on ('click', handler);
    
    		const curryOn = handler => event => $ ('button').on (event, handler);
    
    		const curryOnClick = handler => curryOn (handler) ('click');
    	
    

    Curry functions are neat when used for carrying reusable code containers. You take a function with multiple arguments, and you know that one of those arguments will have a specific value, but the other is undecided. Therefore, by using curry as a fancy partial application, you can create a new function that will allow you to deal with undecided arguments only without repeating your code.

    Practical example: curry for functional composition

    Functional composition is a concept that is worthy of its own post. The problem we’re trying to solve by currying is that JavaScript is full of object-oriented approaches that can be difficult to use with functional code, especially if you want to be a purist (or a hipster) about it.

    In functional composition you have a sequence of functions applied all on the same single argument as f(g(x)). This would be your example:

    	
    	
    		// Object oriented approach
    		const getUglyFirstCharacterAsLower = str
    		  => str.substr (0, 1).toLowerCase ();
    
    		// Functional approach
    		const curriedSubstring = start => length => str
    		  => str.substr(start, length);
    
    		const curriedLowerCase = str => str.toLowerCase ();
    
    		const getComposedFirstCharacterAsLower = str
    		  => curriedLowerCase (curriedSubstring (0) (1) (str));
    	
    

    It is also very popular to use a compose function to compose your functions:

    	
    	
    		const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
    	
    

    Using the above-defined functions curriedSubstring and curriedLowerCase you can then use compose to do this:

    	
    	
    		const getNewComposedFirstCharacterAsLower = compose (curriedLowerCase, curriedSubstring (0) (1));
    		if (getComposedFirstCharacterAsLower ('Martin') === getNewComposedFirstCharacterAsLower ('Martin') {
    		  console.log ('These two provide equal results.');
    		}
    	
    
    	
    	
    		function curry(fn) {
    		  if (fn.length === 0) {
    		    return fn;
    		  }
    
    		  function _curried(depth, args) {
    		    return function(newArgument) {
    		      if (depth - 1 === 0) {
    		        return fn(...args, newArgument);
    		      }
    		      return _curried(depth - 1, [...args, newArgument]);
    		    };
    		  }
    
    		  return _curried(fn.length, []);
    		}
    
    		function add(a, b) {
    		  return a + b;
    		}
    
    		var curriedAdd = curry(add);
    		var addFive = curriedAdd(5);
    
    		var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]
    	
    

    Source: JavaScript ES6 curry functions with practical examples

    The literal template is a new feature introduced in ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals allow embedded expressions, also called literal strings.

    Previous to ES6, literal templates were referred to as template strings. The literal template is enclosed with the backtick (` x`) character. Placeholders in the literal template are represented by the dollar sign and the curly braces (${expression}). If we need to use the expression in the backticks, we can place the expression in (${expression}).

    Basic example:

    	
    	
    		let str1 = "Hello";  
      
    		let str2 = "World";  
    		   
    		let str = `${str1} ${str2}`;  
    		console.log(str);  	
    	
    

    A generator gives us a new way to work with iterators and functions. The generator is a special type of function that can be paused one or more times in the middle and can be resumed later. The function declaration * (function keyword followed by an asterisk) is used to define a generator function.

    When the generator is called, the code does not run. Instead, it returns a special object that is called the Generator object to manage the execution. Let’s look at the example of generators in ES6.

    To learn more about Generators in ES6, follow this link ES6 Generators.

    Basic example:

    	
    	
    		function* gen() {    
    			yield 100;    
    			yield;    
    			yield 200;    
    		}    
    		// Calling the Generator Function    
    		var mygen = gen();    
    		console.log(mygen.next().value);    
    		console.log(mygen.next().value);    
    		console.log(mygen.next().value);     	
    
    		//Output
    
    		100
    		undefined
    		200
    	
    

    Both for..of and for..in statements iterate across lists; the values iterated on are different though, for..in returns a list of keys to the object being iterated, while for..of returns a list of values of the numeric properties of the object being iterated.

    Here is an example that demonstrates this distinction:

    	
    	
    		let list = [4, 5, 6];
    
    		for (let i in list) {
    		   console.log(i); // "0", "1", "2",
    		}
    
    		for (let i of list) {
    		   console.log(i); // "4", "5", "6"
    		}
    	
    

    Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

    	
    	
    		let pets = new Set(["Cat", "Dog", "Hamster"]);
    		pets["species"] = "mammals";
    
    		for (let pet in pets) {
    		   console.log(pet); // "species"
    		}
    
    		for (let pet of pets) {
    		    console.log(pet); // "Cat", "Dog", "Hamster"
    		}
    	
    

    Although this has been a pretty long article to follow through, I strongly believe that most of us must have learned what kind of ES6 interview questions asked in the interview.

    ES6 Basic Interview Questions

    1. Mention some popular features of ES6.

    Some of the common ES6 features are:

    • Supports constants/immutable variables.
    • Block scope support for all variables, constants and functions.
    • Introduction to arrow functions
    • Handling extended parameter
    • Default parameters
    • Extended and template literals
    • De-structuring assignment
    • Promises
    • Classes
    • Modules
    • Collections
    • Supports Map/Set & Weak-map/Weak-Set
    • Localization, meta-programming, internationalization

    2. What are the object oriented features supported in ES6.

    The object-oriented features supported in ES6 are:

    • Classes: We can create classes in ES6. The class function essentially builds a template from which we may later create objects. When a new instance of the class is created, the constructor method is invoked.
    • Methods: Static methods can also be found in classes. A static method, unlike an object, is a function that is bound to the class. A static method can’t be called from a class instance.
      Let’s take a look at getters and setters for a moment. Encapsulation is a fundamental notion in OOP. Data (object properties) should not be directly accessed or updated from outside the object, which is a crucial aspect of encapsulation. A getter (access) or a setter (modify) are particular methods we define in our class to access or edit a property.
    • Inheritance: It is also possible for classes to inherit from one another. The parent is the class that is being inherited from, and the child is the class that is inheriting from the parent.
       

    3. Give a thorough comparison between ES5 and ES6.

    ES5ES6
    ES5 is the fifth edition of the ECMAScript which was introduced in 2009.ES6 is the sixth edition of the ECMAScript which was introduced in 2015.
    Primitive data types that are string, boolean, number, null, and undefined are supported by ES5.There are a few additions to the JavaScript data types in ES6.  For supporting unique values, a new primitive data type ‘symbol’ was introduced.
    In ES5, we could define the variables by using the var keyword only.In ES6, in addition to var, there are two new methods to define variables: let and const.
    Both function and return keywords are used in order to define a function in ES5.An arrow function is a newly added feature in ES6 in which we don’t require the function keyword in order to define the function.
    In ES5, a for loop is used to iterate over elements.ES6 introduced the idea of for…of loop in order to iterate over the values of the iterable objects.

    4. What is the difference between let and const? What distinguishes both from var?

    When declaring any variable in JavaScript, we used the var keyword. Var is a function scoped keyword. Within a function, we can access the variable. When we need to create a new scope, we wrap the code in a function.

    Both let and const have block scope. If you use these keywords to declare a variable, it will only exist within the innermost block that surrounds them. If you declare a variable with let inside a block (for example, if a condition or a for-loop), it can only be accessed within that block.

    The variables declared with the let keyword are mutable, which means that their values can be changed. It’s akin to the var keyword, but with the added benefit of block scoping. The variables declared with the const keyword are block-scoped and immutable. When variables are declared with the const keyword, their value cannot be modified or reassigned.

    5. Discuss the arrow function.

    In ES6, arrow functions are introduced. The shorthand syntax for writing ES6 functions is arrow functions. The arrow function’s definition consists of parameters, followed by an arrow (=>), and the function’s body.

    The ‘fat arrow’ function is another name for the Arrow function. We won’t be able to employ them as constructors.

     const function_name = (arg_1, arg_2, arg_3, ...) => {  
        //body of the function  
    } 

    Few things to note:

    • It reduces the size of the code.
    • For a single-line function, the return statement is optional.
    • Bind the context lexically.
    • For a single-line statement, functional braces are not required.
    • Doesn’t work with new

    6. When should one not use arrow functions?

    One should not use arrow functions in the following cases:

    • Function Hoisting, Named Functions:

    As arrow functions are anonymous, we cannot use them when we want function hoisting or when we want to use named functions.

    • Object methods:
     var a = {
      b: 7,
      func: () => {
        this.b--;
      }
    }

    The value of b does not drop when you call a.func. It’s because this isn’t bound to anything and will inherit the value from its parent scope.

    • Callback functions with dynamic context:
     var btn = document.getElementById('clickMe');
    btn.addEventListener('click', () => {
      this.classList.toggle('on');
    });

    We’d get a TypeError if we clicked the button. This is due to the fact that this is not bound to the button, but rather to its parent scope.

    • this/arguments:

    Since arrow functions don’t have this/arguments of their own and they depend on their outer context, we cannot use them in cases where we need to use this/arguments in a function.

    7. What is the generator function?

    This is a newly introduced feature in ES6. The Generator function returns an object after generating several values over time. We can iterate over this object and extract values from the function one by one. A generator function returns an iterable object when called. In ES6, we use the * sign for a generator function along with the new ‘yield’ keyword.

     function *Numbers() {
        let num = 1;
        while(true) {
            yield num++;
        }
    }
      
    var gen = Numbers();
     
    // Loop to print the first
    // 5 Generated numbers
    for (var i = 0; i < 5; i++) {
     
        // Generate the next number
        document.write(gen.next().value);
     
        // New Line
        document.write("<br>");
    }

    Output:

    1
    2
    3
    4
    5

    The yielded value becomes the next value in the sequence each time yield is invoked. Also, generators compute their output values on demand, allowing them to efficiently represent expensive to compute sequences or even infinite sequences.

    8. What is the “spread” operator in ES6?

    The list of parameters is obtained using the spread operator. Three dots (…) are used to represent it. The spread operator divides an iterable (such as an array or a string) into individual elements. It’s mostly used in JavaScript to make shallow copies of JS. It improves the readability of your code by making it more concise.

    The spread operator can be used to join two arrays together or to concatenate them.

    let arr1 = [4, 5, 6];  
        
    let arr2 = [1, 2, 3, ...arr1, 7, 8, 9, 10];  
        
    console.log(arr2);

    Output:

    [ 1 2 3 4 5 6 7 8 9 10 ]

    9. Explain Destructuring in ES6.

    Destructuring was introduced in ES6 as a way to extract data from arrays and objects into a single variable. It is possible to extract smaller fragments from objects and arrays using this method. The following is an example.

    let greeting =['Good','Morning'];  
    let [g1, g2] = greeting;  
    console.log (g1, g2);

    Output:

    Good Morning

    10. What are Promises in ES6?

    Asynchronous programming is a concept found in JavaScript. The processes are run separately from the main thread in asynchronous programming. Promises are the most convenient approach to deal with asynchronous programming in ES6. Depending on the outcome of the procedure, a promise can be refused or resolved. Callbacks were used to cope with asynchronous programming before promises were introduced in ES6.

    However, it caused the problem of callback hell, which was addressed with the introduction of promises.

    (A callback is a function that is performed after another function has completed. When working with events in JavaScript, callback is very useful. As an argument to another function, we pass a function into another function.

    When we use callbacks in our web applications, it’s common for them to get nested. Excessive callback usage clogs up your web application and leads to callback hell.)

    11. Explain the Rest parameter in ES6.

    It’s a new feature in ES6 that enhances the ability to manage arguments. Indefinite arguments can be represented as an array using rest parameters. We can invoke a function with any number of parameters by utilizing the rest parameter.

     function display(...args) {  
        let ans = 0;  
        for (let i of args) {  
            ans *= i;  
        }  
        console.log("Product = "+ans);  
      }  
        
      display(4, 2, 3); 

    Output:

     Product = 24

    12. Discuss the template literals in ES6.

    Template literals are a brand-new feature in ES6. It makes producing multiline strings and performing string interpolation simple.

    Template literals, also known as string literals, allow for embedded expressions.

    Template literals were referred to as template strings prior to ES6. The backtick (“) character is used to enclose template literals. The dollar sign and curly brackets (${expression}) are used to denote placeholders in template literals. If we need to use an expression within the backticks, we can put it in the (${expre

  • SQL Interview Questions and Answers

    SQL, or Structured Query Language, is a language that is used to interact or communicate with a database. This language assists in performing tasks like retrieval, insertion, updating, and deletion of data from databases. This information is commonly asked in SQL interview questions. An ANSI (American National Standards Institute) standard, SQL helps developers execute queries, insert records in tables, update records, create databases, create tables, or delete tables.

    No doubt other programming languages such as ASP, PHP, and ColdFusion helped in making the Internet very dynamic, but SQL has revolutionized how users interact with websites in general. Any reputed webpage that allows the user to provide content uses SQL.

    Most Frequently Asked SQL Interview Questions

    Here in this article, we will be listing frequently asked SQL Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

    1. What is SQL and explain its components?

    SQL is a standard language which is used to accessing and manipulating databases. It stands for Structured Query Language. It can be used to develop a web application for a server-side scripting language, like ASP, PHP, etc.

    It consists of three components that are listed below:-

    • Data Definition Language.
    • Data Manipulation Language.
    • Data Control Language.

    2. Explain the types of joins in SQL?

    In SQL, Joins is used to merge records from two or more tables in a database, based on a related column between them.

    Here are the four types of the joins in SQL

    • INNER JOIN: It returns records that have matching values in both tables
    • LEFT JOIN: It returns all records from the left table and the matched records from the right table
    • RIGHT JOIN: Right Join returns all records from the right table and the matched records from the left table
    • FULL JOIN: It returns all records when there is a match in either left or right table

    3. What is a Primary key? Explain

    A primary key is a column in a table that designated to uniquely identifies the rows in that table. Primary key holds a unique value for each row and cannot contain null values.

    4. Explain Constraints in SQL?

    It is a rule used to limit the type of data that can insert into a table, to maintain the integrity and accuracy of the data inside the table.

    It can be divided into two types.

    • Column level constraints
    • Table-level constraints

    These are the most common constraints that can be applied to a table.

    • NOT NULL
    • DEFAULT
    • UNIQUE
    • PRIMARY KEY
    • FOREIGN KEY etc

    5. What is the difference between HAVING and a WHERE in SQL?

    WHERE clause is used for filtering rows, and it applies to every row but HAVING term is used to filter groups.

    WHERE can be used without the GROUP BY but HAVING clause cannot be used without the GROUP BY.

    6. Explain the difference between SQL and MySQL.

    • Mysql is available free because it is open source, but SQL is not an open source.
    • Mysql offers updateable views, but SQL offers indexed views which are more powerful.
    • Mysql does not support XML, but SQL supports XML.
    • Mysql not supported Auto tuning but SQL can.
    • Mysql did not support User-defined functions, but SQL supported.
    • Mysql support Transaction is very much limited but SQL support extensively and entirely offered.
    • Mysql not offered Stored procedures and full joins but offered in SQL.
    • Mysql does not support Cursor feature but is there in SQL

    7. What is Trigger in SQL? Explain

    In SQL, a trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table. It can be performed when you run one of the following SQL like INSERT, UPDATE and DELETE occurred in a table. It’s activation time can be BEFORE or AFTER.

    8. Explain Normalization and what are the advantages of it?

    It is a systematic approach of decomposing tables to remove data redundancy and undesirable characteristics like Insertion, Update and Deletion. Normalization is a multi-step process that put data into the tabular form and removing duplicated data from the tables.

    Advantages
    • It helps to the reduction of redundant data.
    • It has a much more flexible database design.
    • It is better to handle on database security.
    • It is dealing with data consistency within the database.
    Rule of Normalization
    • 1NF(First Normal Form)
    • 2NF(Second Normal Form)
    • 3NF(Third Normal Form)
    • BCNF(Boyce and Codd Normal Form)
    • 4NF(Fourth Normal Form)

    9. How to find 3rd highest salary of an employee from the employee table in SQL?

    SELECT salary FROM employee e1 WHERE 3-1 = (SELECT COUNT(DISTINCT salary) FROM employee e2 WHERE e2.salary > e1.salary)

    10. Explain ALIAS in SQL?

    It is used to rename a table in a specific SQL statement. Renaming is a temporary change without change actual table name in the database. It can be applied to tables as well as fields.

    The basic syntax of a table alias
    SELECT field1, field2 FROM TABLE_NAME AS TABLE WHERE "WRITE_YOUT_CONDITION";

    The basic syntax of a column alias
    SELECT field1 AS column1 FROM TABLE_NAME WHERE "WRITE_YOUT_CONDITION";

    11. Explain Scalar functions in SQL?

    It is a function that takes one or more values but returns a single value. It is based on user input and returns a single value.

    • UCASE()
    • LCASE()
    • MID()
    • LEN()
    • ROUND()
    • NOW()
    • FORMAT()

    12. Explain Aggregate functions are available there in SQL?

    The aggregate function performs a calculation on a set of values, and it returns a single value as output. It ignores NULL values when it performs calculation except for the COUNT function.

    SQL provides many aggregate functions that are listed below.

    • AVG()
    • COUNT()
    • SUM()
    • MIN()
    • MAX() etc

    13. How to make a copy values from one column to another in SQL?

    UPDATE `table_name` SET new_field=old_field

    14. What are the advantages of SQL? Explain

    There are many advantages of SQL, and some of them are mentioned below:

    • No coding needed: It is easy to manage without any need to write the substantial amount of code
    • Well defined standards: Long established are used by the SQL databases that are being used by ISO and ANSI.
    • Portability: We can use this program in PCs, servers, laptops and mobile phones.
    • Interactive Language
    • Multiple data views

    15. Who introduced SQL?

    It was initially developed in the early 1970s at IBM by Donald D. Chamberlin and Raymond F. Boyce.

    16. What is a Database? Explain

    It is a collection of data that is organized to be easily accessed, managed and updated. It is distributed into rows, columns, and tables. It’s indexed to make it easier to find related information.

    17. Explain table and field in SQL?

    Table: It is a collection of related data that consists of rows and columns. It has a specified number of columns but can have any number of rows.

    Field: It is a column in a table that is designed to maintain specific information about all records in the table.

    18. Explain Unique key in SQL.

    It is a set of one or more than one fields or columns of a table that uniquely identify a record in the table. It is little like a primary key, but it can accept only one null value.

    19. Explain Foreign key in SQL?

    It is a collection of fields in one table that uniquely identifies a row of another table. In simple words, the foreign key is defined in a second table, but it refers to the primary

    20. Write a query to display the current date in SQL?

    SELECT CURDATE();

    21. Explain the difference between DROP and TRUNCATE commands in SQL?

    TRUNCATE
    • It removes all rows from a table.
    • It does not require a WHERE clause.
    • Truncate cannot be used with indexed views.
    • It is performance wise faster.
    DROP
    • It removes a table from the database.
    • All table’s rows, indexes, and privileges will also be removed when we used this command.
    • The operation cannot be rolled back.

    You can download here sql interview questions pdf after registeration or subscribe.

    22. Write a query to find the names of users that begin with “um” in SQL?

    SELECT * FROM employee WHERE name LIKE 'um%';

    23. Explain CLAUSE in SQL?

    It is the source of a rowset to be operated upon in a DML statement. These clauses are very common which is used with Select statement, Update statement and Delete statement.

    SQL provides with the following clauses that are given below:

    • WHERE
    • GROUP BY
    • HAVING
    • ORDER BY etc

    24. How to use distinct and count in SQL query? Explain

    count(): It returns the number of rows in a table satisfying the condition specified in the WHERE clause. It would return 0 if there were no matching conditions.

    Syntax:
    SELECT COUNT(*) FROM category WHERE 'status' = 1;

    distinct(): It is used to return only different values. In a table, a column often contains many duplicate values, and sometimes we want to list the different values. It can be used with aggregates functions.

    Syntax:
    SELECT DISTINCT class FROM College ORDER BY department

    25. What has stored procedures in SQL and how we can use it?

    It is a set of precompiled SQL statements that are used to perform a particular task. A procedure has a name, a parameter list, and SQL statement, etc. It will help in reduce network traffic and increase the performance.

    Example

                                                        CREATE PROCEDURE simple_function
    AS
        SELECT first_name, last_name
        FROM employee;
    
    EXEC simple_function;
  • React js interview questions and Answers

    ReactJS is a JavaScript library for building reusable User interface components. It is a template-based language combined with different functions that support the HTML. Our recently updated React Interview Questions can help you crack your next interview. This means the result of any React’s operation is an HTML code. You can use ReactJS to build all kinds of single-page applications.

    Short Questions About React
    What is the latest version of React?17.0.2, released on March 22, 2024.
    When was React first released?29th May 2013
    React JS is Created ByJordan Walke
    License of ReactJSMIT License

    What’s In It For Me?

    We have created this section for your convenience from where you can navigate to all the sections of the article. All you need to just click or tap on the desired topic or the section, and it will land you there.

    React Developer Interview Questions

    Here in this article, we will be listing frequently asked React js interview questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.1. What is the differnece between Virtual DOM and Real DOM?

    Real DOMVirtual DOM
    The update process is very slow in this.The update process is much faster here.
    It can directly update the HTML.It can’t directly update the HTML.
    It creates a new DOM if the element is updated.It updates the JSX if there is any update on an element.
    DOM manipulation related to a Real DOM is very complicated.DOM Manipulation related to a Virtual DOM is effortless.
    There is a lot of memory wastage in a Real DOM.There are no cases of memory wastage in a Virtual DOM.

    2. Why should we not update the state directly?

    One should never update the state directly because of the following reasons:

    • If you update it directly, calling the setState() afterward may just replace the update you made.
    • When you directly update the state, it does not change this.state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value.
    • You will lose control of the state across all components.

    Note: Out of all the react questions, this is one that actually helps the interviewer to judge your level of understanding in this subject. Read the answer carefully to understand it properly.

    3. How to call the function in render to react?

    To call a function inside a render in React, use the following code:

    Example

                                                        import React, { Component, PropTypes } from 'react';
    
    export default class PatientTable extends Component {
          constructor(props) {
            super(props);
            this.state = {
             checking:false
          };
            this.renderIcon = this.renderIcon.bind(this);
      }   renderIcon(){
        console.log("came here")
        return(
          <div>Function called</div>
        )
      }   render() {    return (
           <div className="patient-container">        {this.renderIcon}             </div>
       );
     }
    }

    4. What is Props?

    Props stand forProperties in React. They are read-only components that must be kept pure. These components are passed down from the parent to the child component throughout the app. A child component cannot send the prop back to the parent component. This can help in maintaining the unidirectional data flow and is used to render the dynamically generated data.

    5. What are the new features in React?

    The latest release of React is 16.6.9 and here are its newest features:

    • Measuring performance using
    • Improved Asynchronous act() for testing
    • No more crashing when calling findDOMNode() inside a tree
    • Efficient handling of infinite loops caused due to the setState inside of useEffect has also been fixed

    6. What is JSX?

    JSX stands for JavaScript XML. It is a file type used by React that utilizes the expressiveness of JavaScript along with HTML. This makes the HTML file easy to understand. This file makes applications robust and boosts their performance.

    Example

                                                        render(){
          return(
              <div>  <h1> Welcome To Best Interview Question!!</h1> </div>
         );
     }

    7. What are controlled and uncontrolled components?

    A Controlled Component is one that takes the current value through the props and notifies of any changes through callbacks such as onChange.

    Example:

    <input type=”text” value={value} onChange={handleChange} />

    An uncontrolled component is one storing its own state internally, and you can query the DOM via a ref to find its current value as and when needed. Uncontrolled components are a bit closer to traditional HTML.

    Example:

    <input type=”text” defaultValue=”foo” ref={inputRef} />

    Note: React is a widely used open-source library used for building interactive user interfaces. It is a web platform licensed under MIT. This is one of the very popular react interview questions.

    8. What is function based component in React?

    Basically Function Based Component are the component which are made by JavaScript Functions.It takes props as argument and return JSX.

    Example

                                                        Import React from ‘react’;
    const XYZ = (props ) => {
         <div>
              <h1>React Interview Questions</h1>
         </div>
    }
    export default XYZ;

    9. What is the difference between React Native and React?

    ReactReact Native
    Released in the year 2013.Released in the year 2015.
    It can be executed on multiple platforms.It is not platform-independent. It will need some extra effort to work on different platforms.
    Generally used for developing web applications.Generally used for developing mobile applications.
    Here, Virtual DOMs are used to render browser code.Here, an in-built API is used to render code for mobile applications.
    It uses the JS library and CSS for animations.It has its own in-built animation libraries.
    It uses the React Router to navigate through web pages.It has an in-built navigator to navigate through mobile application pages.

    0. What is the difference between Element and Component?

    React ComponentReact Element
    It is a simple function or class used for accepting input and returning a React elementIt is a simple object used for describing a DOM node and the attributes or properties as per your choice.
    The React Component has to keep the references to its DOM nodes and also to the instances of the child components.The React Element is an immutable description object, and in this, you cannot apply any methods.

    11. What are refs used for in React?

    Refs are a function in React having the following uses:

    • Accessing DOM and React elements that you have created.
    • Changing the value of a child component without using props and others.

    12. How React is different from Angular?

    ReactJSAngularJS
    This is an open-source JS library used for building user interfaces and uses a controller view pattern.This is a JS-based open-source front end web framework and uses an MVC based pattern.
    It is developed and maintained by Facebook Developers.It is developed and maintained by Google Developers.
    Based on the JSX programming language.Based on Javascript and HTML language.
    It is straightforward to learn.Comparatively, it is difficult to learn.
    It supports server-side rendering.It supports client-side rendering.
    It has a uni-directional data binding methodology.It has a bi-directional data binding methodology.
    It is based on a Virtual DOM.It is based on a regular DOM.

    Note: Before getting confused with the plethora of React coding interview questions, you need to ensure the basics. This question will help you to understand the basics of reactjs and make you even more confident enough to jump onto the advanced questions.

    3. What is the difference between componentWillMount and componentDidMount?

    componentWillMount()componentDidMount()
    This is called only once during the component lifecycle immediately before the component is rendered to the server. It is used to assess props and do any extra logic based upon them.It is called only on the client end, meaning, it is usually performed after the initial render when a client has received data from the server.
    Used to perform state changes before the initial render.It allows you to perform all kinds of advanced interactions including state changes.
    No way to “pause” rendering while waiting for the data to arrive.It can be used to set up long-running processes within a component.
    It is invoked just immediately after the mounting has occurred.Putting the data loading code in this just ensures that data is fetched from the client’s end.
    Users should avoid using any async initialization in order to minimize any side-effects or subscriptions in this method.Here, the data does not load until the initial render is done. Hence, users must set an initial state properly to eradicate undefined state errors.

    14. What is the difference between Function Based Component and Class Based Component?

    The Main Difference is of Syntax. The function-Based component used props as an argument and is also called stateless component and In class-based component, we extend all the property of predefined function and used according to our need.

    Class Based Component use state and the state is used as props in child component.In Class Based component we can use different lifecycle method of component.

    15. What are arrow functions? How are they used?

    Arrow functions, also called ‘fat arrow‘ (=>), are brief syntax for writing the expression. These functions bind the context of the components because auto binding is not available by default in ES6. Arrow functions are useful if you are working with the higher-order functions.

    Example

                                                        //General way
    render() {
      return(
        <MyInput onChange={this.handleChange.bind(this) } />
      );
    } //With Arrow Function
    render() {
       return(
          <MyInput onChange={ (e) => this.handleOnChange(e) } />
       );
    }

    16. What is the purpose of render() in React?

    It is compulsory for each React component to have a render(). If more than one element needs to be rendered, they must be grouped inside one tag such as <form>, <group>,<div>. This function goes back to the single react element which is the presentation of native DOM Component. This function must return the same result every time it is invoked.

    17. What is a state in React and how is it used?

    States are at the heart of components. They are the source of data and must be kept simple. States determine components’ rendering and behavior. They are mutable and create dynamic and interactive components, and can be accessed via this.state().

    Note: From the vast number of react developer interview questions, answering this will help you to align yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

    18. What is the component lifecycle in ReactJS?

    Component lifecycle is an important part of ReactJS. Component lifecycle falls into three categories – property updates, Initialization and Destruction. Lifecycle is a method of managing the state and properties of the components.

    19. What is an event?

    Events are the triggered reactions to actions like mouse hover, click, key press, etc.

    20. What is Redux?

    Redux is used to handle data in a reliable manner. It performs task accurately and ensures that the data has been controlled. You can also apply filters if only a specific part of data is required.

    NOTE: If you are looking Redux Interview Questions then you can visit here.

    21. What is Flux?

    Flux is an illustration that helps to maintain a unidirectional data stream. It also controls construed data unique fragments and makes them interface without creating issues. The configuration of Flux is insipid and is not specific to applications.

    22. What is meant by pooling?

    The server needs to be regularly monitored for updates. The aim is to check for the presence of new comments. This process is considered as pooling. It checks for the updates almost every 5 seconds. Pooling helps keep an eye on the users and ensure there is no negative information on servers.

    23. In what cases would you use a Class Component over a Functional Component?

    If your component has a state or lifecycle method, use Class component. Else, a Functional component.

    24. What can you do if the expression contains more than one line?

    Enclosing the multi-line JSX expression is the best option. Sometimes it becomes necessary to avoid multi-lines in order to perform the task reliably and for getting the expected results.

    25. Is it possible to use the word Class in JSX?

    No. This is because the word Class is an occupied word in JavaScript. If you use the word Class JSX will get translated to JavaScript.

    Note: Before getting confused with the plethora of react coding interview questions, you need to ensure the basics. This question will help you to understand the core basics of react and make you even more confident enough to jump onto the advanced questions.

    26. Is it possible to display props on a parent component?

    Yes. This is a complex process, and the best way to do it is by using a spread operator.

    27. What is React?

    React is a JavaScript Library which is used to show content to user and handle user interaction.

    28. What is Component?

    Component is a building block of any React app which is made by either JavaScript Function of Class. Ex. Header Component, Footer Component etc.

    There are two types of Components.
    • Function Based Component
    • Class Based Component

    29. What are Class Based Component?

    Class Based Component is the JavaScript Class. In these Components we extends the JavaScript predefined class into our component.

    Example

                                                        Import React,{Component} from ‘react’;
    
    class ABC extends Component {
    
     render(){
    
       return(
    
        <div>
    
           <h1>Hello World</h1>
    
    </div>
    
    );
    
    }}
    
    export default ABC;

    30. What is a Higher Order Component (HOC)?

    A higher-order component or HOC in React is basically an advanced technique used for reusing component logic. HOCs are not a part of the React API. They are a pattern emerging from the React’s compositional nature.

    Higher Order Component in React
    A higher-order component is any function that takes an element and returns it with a new item.

    31. What is a pure function?

    The term pure function in React means that the return value of the function is entirely determined by its inputs and that the execution of the function produces no side effects.

    32. What is ReactDOMServer?

    The ReactDOMServer is an object which enables you to render components as per a static markup. Generally, it is used on a Node Server.

    33. How to apply validation on props in React?

    The App.proptypes is used for validating props in React components.

    Here is the syntax:

    class App extends React.Component {
        render() {}
    }
    Component.propTypes = { /*Definition */};

    34. How to create a component in react js?

    There are 3 ways to create a component in React:

    • Using a depreciated variable function
    • Using a Class
    • Using a Stateless Functional Component
    1. Using a depreciated variable function

    In this, you need to declare a variable in your Javascript file/tag and use the React.createClass() function to create a component using this code.

    var MyComponent = React.createClass({
       render() {
          return <div>
          <h1>Hello World!</h1>
          <p>This is my first React Component.</p>
          </div>
       }
    })

    Now, use the div element to create a unique ID for the specific page and then link the above script onto the HTML page.

    <div id=”react-component”></div>

    Use ReactDOM.render() function to take 2 arguments, the react component variable and the targeted HTML page.

    ReactDOM.render(<MyComponent />, document.getElementById('react-component'))

    Finally, save the HTML page to display the result like this one below:

    2. Using a Class

    Javascript has lately started supporting classes. Any React developer can easily create a class using the class extends (Inherits). Following is the code

    3. Using a Stateless Functional Component

    It might sound a bit complex, but this basically means that a normal function will be used in place of a variable to return a react component.

    Create a const called MyComp and set it as equal to a () function. Use the arrow function, => to declare the logic of the function as follows:

    const MyComponent = () => {
       return <div>
       <h1>Hello!</h1>
       <p>This is my first React Component.</p>

    35. How to link one page to another page in react js?

    There are two ways to link one page to another to React:

    Using React Router: Use the feature from the react-router to link the first page to the second one.

    <Link to ='/href' ></Link>

    36. How to reload the current page in react js?

    Reloading/Refreshing a page using Javascript:
    Use Vanilla JS to call the reload method for the specific page using the following code:

    window.location.reload(false);

    37. How to redirect to another page in react js?

    The best way to redirect a page in React.js depends on what is your use case. Let us get a bit in detail:

    If you want to protect your route from unauthorized access, use the component and try this:

    Example

                                                        import React from 'react'
    import { Redirect } from 'react-router-dom'
    const ProtectedComponent = () => {
       if (authFails)
       return <Redirect to='/login' />
    }
    return <div> My Protected Component </div>
    }

    38. How do you reference a DOM element in react?

    In React, an object this.refs which is found as an instance inside the component can be used to access DOM elements in Reactjs.

    Note: One of the most tricky react advanced interview questions, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry run would help you get that dream job.

    39. What are React Hooks?

    React Hooks were brought in by the React team to efficiently handle state management and the side-effects in function components. React Hooks is a way of making the coding effortless. They help by enabling us to write React applications by only using React components.

    0. How to call one component from another component in reactjs?

    To render a component with another component in Reactjs, let us take an example:

    Let us suppose there are 2 components as follows:

    Example

                                                        Component 1
    
    class Header extends React.Component{
    
        constructor(){
            super();
        }     checkClick(e, notyId){
           alert(notyId);
        }
    } export default Header; Component 2 class PopupOver extends React.Component{     constructor(){
            super();        
        }     render(){
            return (
                <div className="displayinline col-md-12 ">
                    Hello
                </div>
            );
        }
    } export default PopupOver;
    Now to call the Component 1 in Component 2, use this code: import React from 'react'; class Header extends React.Component { constructor() {
        super();
    } checkClick(e, notyId) {
        alert(notyId);
    } render() {
        return (
            <PopupOver func ={this.checkClick } />
        )
    }
    }; class PopupOver extends React.Component { constructor(props) {
        super(props);
        this.props.func(this, 1234);
    } render() {
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
    } export default Header;

    41. What is React Router?

    React Router is the in-built routing library for React. React Router helps to keep your UI in sync with the respective URL. It works on a simple API having powerful features like lazy loading, locational transition, and dynamic route matching built right in.

    42. How to render an array of objects in react?

    Now, there are two ways to render this object as an array,

    First:

    render() {
        const data =[{“name”:”test1″},{“name”:”test2″}];
        const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

        return (
          <div>
          {listItems }
          </div>
        );
      }

    Or, you could directly write the map function in the return

    render() {
        const data =[{“name”:”test1″},{“name”:”test2″}];
        return (
          <div>
          {data.map(function(d, idx){
             return (<li key={idx}>{d.name}</li>)
           })}
          </div>
        );
      }

    43. What is the difference between state and props in React?

    StateProps
    This is the data maintained inside the component.This is the data passed in from a parent component.
    The component within shall update itself using the setState function.These are read-only functions present in the child component and have to be updated manually.

    Note: React is a widely used open-source library used for building interactive user interfaces. It is a web platform licensed under MIT. This is one of the very popular react interview questions.

    44. Which lifecycle method gets called by react as soon as a component is inserted into the DOM?

    45. How to use the spread operator to react?

    46. What are the steps to implement search functionality in reactjs?

    47. How to define property in the react component?

    48. What is StrictMode in React?

    49. How to avoid prop drilling in React?

    You can avoid Prop Drilling in the following ways:

    • Using a Context API
    • Using Render Props

    50. What are the key benefits of ReactJS development?

    Key Benefits of ReactJS Development
    • Allows Developers to Reuse the Components
    • It is Much Easier to Learn
    • The Benefit of Having JavaScript Library
    • SEO Friendly
    • It ensures faster rendering
    • The Increase in Community Base
    • The Support of Handy Tools
    • Scope for Testing the Codes etc

    51. What are synthetic events?

    It is a cross-browser wrapper that is around the native event of the same browser. This is the most important question in react interview questions.

    Top 20 React.Js Interview Questions

    Here you will find the list of Top React interview questions, which were written under the supervision of industry experts. These are the most common questions and usually asked in every interview for the role of the React Developers.

    • What is HOC?
    • What are the difference between Rest and Spread Operator?
    • What are the key benefits of using Arrow functions?
    • What is Pure Component?
    • What are Controlled and Uncontrolled components with example?
    • What is Refs?
    • What is the difference between class based component & function based components?
    • How to work React?
    • Why virtual Dom is faster than real dom?
    • How does virtual Dom work in react?
    • What are the difference between null & undefined?
  • Angular 8 Interview Questions and Answers

    Angular is one of the foremost frameworks, has released its latest version namely Angular 8 on 23rd of May, 2019. The latest version of Angular is incorporated with unique and attractive features. In general, Angular 8 supports new and unique features such as CLI (Command Line Interface), core framework, and angular material library. Angular 8 Interview Questions contain these important questions and answers. Read them carefully and score well.

    Quick Facts About Angular 8
    What is the latest version of Angular?Angular 11.0 released on 11th November 2024
    When did the Angular 8 release?28th May 2019
    What language does Angular use?TypeScript
    Who is the developer of Angular 8?Google

    This is a list of the most frequently asked Angular 8 interview questions and answers. Please have a good read and if you want to download it, it is available in a PDF format so that you can brush up your theoretical skills on this subject.

    Most Frequently Asked Angular 8 Interview Questions

    Here in this article, we will be listing frequently asked Angular 8 Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.1. What is the difference between Angular 7 and Angular 8?

    Angular 7Angular 8
    Angular 7 is difficult to useAngular 8 is easier to use
    It has features such as Virtual scrolling, CLI prompts, Application performance, Drag, and drop, Bundle budget, Angular compiler, Angular elements, NativeScript, Better error handling, etc.It has unique and advanced level features such as Differential Loading, Ivy rendering Engine, API builders, Bazel support, Support for $location, Router backward compatibility, Opt-In Usage sharing, web- workers, etc.
    Breaking changing in Angular 7 are- Component Dev Kit (CKD), Material design library and virtual scrolling.Breaking changing in Angular 8 are- Core framework, Angular, material library and CLI.
    It will support a lower version of typescript version 3.4.It will not support a lower version of typescript version 3.4.
    It supports all types Node.js versionIt supports Node.js version 12 or later

    2. What is bazel in Angular 8?

    In Angular 8, Bazel is a new build system and it is available for a short period of time. It is the new feature of Angular 8, which provides a platform to make your backends and frontends with a similar tool. It has the possibility to have remote builds as well as cache on the build farm.

    The main features of Bazel are-
    • It is an internal build tool, through which application can be customized.
    • It also tests the action and performance of multiple machines.
    • It constructs a graph through which you can identify the useful information.
    • It also supports customization.

    3. What is the purpose of Wildcard route?

    Wildcard routing is used in Angular 8 for defining the route of pages. Specific changes/updates can be made when defining the route using Wildcard.

    4. What is the difference between promise and observable in angular8?

    ObservablesPromises
    Both synchronous as well as asynchronousAlways asynchronous
    Can emit multiple valuesProvides only one single value
    It is lazyIt is eager

    5. What is the purpose of Codelyzer?

    Codelyzer is an open-source tool in Angular 8 whose main function is to check for errors in codes not following pre-defined guidelines. It runs on the tslint.json file and checks only the static code in Angular 8.

    6. What are the new features in angular 8?

    Angular 8 it has following new features such as
    • Differential loading– It is a technique that automatically makes your angular applications more performant. When you build applications for production, two bundles are created- One bundle for Modern browsers that support ES6+ and another bundle for older browsers that only support ESS.
    • Dynamic imports for lazy routes– In Angular version 8 there is nothing new in the concept of lazy routes itself but the syntax has totally changed. In the older version of Angular CustomString Syntax is used, but angular 8 uses standard dynamic import syntax so the syntax which is customized to Angular is migrated to industrial standard.
    • Ivy rendering Engine– It translates the templates and components into regular HTML and javascript that the browser can interpret and understand.
    • Bazel– It is a building tool through which angular developer can build backends and frontends.

    7. What are the limitations of Web Workers?

    Here are the limitations of a Web Worker:
    • A web worker cannot directly manipulate the DOM
    • It has limited access to methods and properties of the window object.
    • It cannot be run directly from the file system. A web worker needs a server to run.

    8. How Performance Improvements on the core in Angular 8?

    Angular 8 has advanced level features which ensure systematic workflow and performance improvements. It has apparent features such as differential loading, CLI workflow improvements, Dynamic imports for lazy routes, Ivy rendering engine, Bazel, etc.

    9. Why we used Service Workers in Angular?

    A Service Worker is used in Angular 8 to build the basic steps of converting an application into a Progressive Web App (PWA). Service workers function as network proxies and intercepting all outgoing HTTP requests made by the application and how to respond.

    10. How to upgrade angular 7 to 8?

    Steps to upgrade Angular 7 to 8
    • Install TypeScript 3.4
    • Use Node LTS 10.16 or its advanced version
    • Run command on terminal panel/CLI -> ng update @angular/cli@angular/core

    Alternative- use URL link- https://update.angular.io/

    11. How can you hide an HTML element just by a button click in Angular?

    Ng-hide command is used to hide HTML elements if an expression is true.

    Here’s an example:

    <div ng-app="DemoApp" ng-controller="DemoController">
       <input type="button" value="Hide Angular" ng-click="ShowHide()"/>
       <div ng-hide="IsVisible">Angular 8</div>
    </div>
    <script type="text/javascript">
       var app = angular.module('DemoApp',[]);
       app.controller('DemoController',function($scope){
       $scope.IsVisible = false;
       $scope.ShowHide = function(){
         $scope.IsVisible = $scope.IsVisible = true;
       }
    });
    </script>

    Now in the above, when the Hide Angular button is not clicked(the expression is set to false)

    12. Why typescript is used in angular 8?

    Angular uses TypeScript because:
    • It has a wide range of tools
    • It’s a superset of Angular
    • It makes abstractions explicit
    • It makes the code easier to read and understand.
    • It takes most of the usefulness within a language and brings it into a JS environment without forcing you out.

    13. What are new features in Angular 9?

    Here are the top new features of Angular 9
    • An undecorated class migration schematic added to the core.
    • Numeric Values are accepted in the formControlName.
    • Selector-less directives have now been allowed as base classes in View Engine in the compiler.
    • Conversion of ngtsc diagnostics to ts.Diagnostics is possible

    14. What is the use of RxJS in angular8?

    Angular 8 uses observables which are implemented using RxJS libraries to push code. The main job of RxJS is to work with asynchronous events.

    15. What is NgUpgrade?

    NgUpgrade in Angular 8 is a library which is used to integrate both Angular and AngularJS components in an application and also help in bridging the dependency injection systems in both Angular & AngularJS.

    16. Which command is used to run static code analysis of angular application?

    The ng lint command is used to run static code analysis within an Angular application.

    17. What is HostListener and HostBinding?

    18. What is authentication and authorization in Angular?

    AuthenticationAuthorization
    Process of verifying the userProcess of verifying that you have relevant access to any procedure
    Methods: Login form, HTTP Authentication, HTTP digest, X 509 Certificates, and Custom Authentication method.Methods: Access controls for URL, secure objects and methods and Access Control Lists (ACL)

    19. How to install Angular 8?

    Steps for the Installation of Angular 8 environmental setup
    Step 1

    Before installing Angular IDE using Angular CLI tool, make sure that Node.js has already installed in your system.

    • 1. If Node.js is not installed in your system install it using the following steps.
      • The basic requirement of Angular 8 is Node.js version 110.9.0 or later.
      • Download it using https//nodejs.org/en/
      • Install it on your system
      • Open node.js command prompt
      • Check the version run command, node-v in the console window
    Step 2

    In order to install Angular CLI, use the following commands 2) npm install –g @angular/cli or npm install –g @angular/cli@latest

    Step 3

    To check the node and angular CLI version, run command ng –version on the console terminal

    20. What is runGuardsAndResolvers in Angular 8?

    Angular 8 introduced a number of new and unique options to runGuardsAndResolvers. In general, runGuardsAndResolvers is an option which is used for the Angular router configuration in order to control the resolvers and guards. The first option available in runGuardsAndResolvers is pathParamsChange. Through, this option router will re-run the guards and resolvers. Whenever you want to control over the resolvers and guards, use runGuardsAndResolvers option in Angular 8.

    21. Why Incremental DOM is Tree Shakable?

    In Angular 8, the framework does not interpret components in an incremental DOM. It uses component references instructions, and if it does not refer to a particular instruction, it shall be left unused. Now, VIrtual DOM requires an external interpreter. Hence, not knowing which components to display, everything is shifted to the browser, making the DOM shakeable.

    22. What is the difference between real Dom and virtual Dom?

    Real DOMVirtual DOM
    DOM is a language-neutral interface allowing programs and scripts to dynamically access and update multiple objects like content, structure, and style of a document.Is a collection of modules designed to provide a declarative way to represent the DOM for an application.
    The DOM represents the document as nodes and objects.A virtual DOM object is a representation of a DOM object, like a lightweight copy.
    It is an object-oriented representation of a web page, modified with a scripting language like JavaScript.Virtual DOM is ideal for mobile-first applications.

    23. What is typeofchecks in Angular 8?

    The working of typesofchecks in Angular 8 is similar with the enabled and disabled flag, which means if you want to test whether the selected value is an object or not, then the following syntax is used ” Typeof value = = = ‘object’ “. In angular 8 the folwing types of checks are used such as “Typeof value.ngOnDestroy = = = ‘function’ “.

    24. How to rollback the whole object when navigating back to a page managed by Angular Router in Angular 8?

    The angular router in Angular 8 enables rollback the whole object to the next as users perform application work. To present a specific component view a given URL, Angular Router is the foremost service that presents. In order to import an Angular router, it is mandatory to install a library package, @angular/router.

  • Top 41 Angular Interview Questions and Answers

    Here is a List of essential Angular Interview Questions and Answers for Freshers and mid level of Experienced Professionals. All answers for these Angular questions are explained in a simple and easiest way. These basic, advanced and latest Angular questions will help you to clear your next Job interview.


    Angular Interview Questions and Answers

    These Angular interview questions are targeted for Angular 12, Angular 11, Angular 10, Angular 9, Angular 8, Angular 7 and all versions greater than Angular 2. You must know the answer of these frequently asked Angular interview questions to clear the interview. These Angular questions will help Full Stack developers, Java Developers, .Net Developers, UI or Front End developers and many more to clear the interview.


    1. What is Angular?

    Angular is an application design framework and a development platform to build sophisticated and efficient single page applications. This document applies to angular version 2.0 and later versions such as Angular 11, Angular 10, Angular 9, Angular 8, Angular 7 etc. For 1.x versions of angular we use the name as AngularJS.

    2. What is the latest version of Angular?

    You can check Angular version any time on this link Angular Latest Version

    3. How is Angular different from AngularJs?

    Angular and AngularJS both are the open source JavaScript based frameworks used to develop web based single page applications (SPAs). For angular versions 1.x we gave the name AngularJS and for angular version 2.0 and later we just call it Angular. There are a lot of differences between Angular and AngularJS as below.

    • Language – AngularJS is based on JavaScript, Whereas Angular is written in TypeScript superset of ECMAScript 6 (ES6). TypeScript provides object oriented features and better type checking.
    • Architecture – AngularJS has architecture of MVC (model-view-controller). Model manages its data with the help of $scope, the controller handles user interactions and the view displays the data. Angular has the architecture of components (that handles the logic and view part of the page) and directives. Directives with templates are called components. Angular provides 2 types of directives one is Structural and second attribute directives.
    • Expression Syntax – Both use double curly braces – {{ }} for expressions.
    • Mobile Support – Angular is built by keeping mobile browsers in mind but AngularJS was not built to support mobile devices.
    • Route Navigation – Both provide different configurations for routing as $routeProvider for AngularJS and RouteConfig in Angular.
    • Dependency Injection (DI) – Angular has its own Dependency Injection (DI) pattern which provides the efficiency and modularity in application design whereas AngularJS has not it’s own Dependency Injection.
    • Performance – Angular has better performance than AngularJS because of it’s DI and typescripts OOPs concept, type checking.
    • Structure – AngularJS has less complex structure whereas Angular provides better structure for Large single page applications.

    4. What are the advantages of using Angular over AngularJS?

    Angular is a typescript based free and open-source application design framework and platform for developers which comes with many advantages.

    • Angular has better architecture support for larger applications.
    • TypeScript provides OOPS features and better type checking.
    • Mobile support is a good feature.
    • Routing is simpler to configure.
    • Built in Dependency Injection.
    • Provide the capability to write the code in different languages typescript, ES5, Dart etc.
    • Upgrading to newer versions is easy.
    • Support of AOT compilation in Angular versions 4.0 onwards.

    5. What are the main building blocks of an Angular Application?

    Angular Architecture provides some basic concepts or main building blocks to develop an application. These main building blocks are:

    • NgModules – Angular application is a set of NgModules as angular supports modular programming. NgModules collect the related code into units for related functionality and provide the compilation context for the component. An application has at least one root module that is responsible for bootstrapping and other are the feature modules. You can create a module class using @NgModule decorator with some properties. Module can contain any components, service providers and other code for that module. @NgModule({ imports: [], declarations: [], providers: [], bootstrap: [AppComponent], }) export class AppModule { }
    • Components – Components define and control the view , it’s associated data and logic. Application has at least one component. The component decorator @Component() treats the class just below it as a component class and provides the information for the template and other meta-data information. Example is below. @Component({ selector: 'web-portal-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], }) export class HomeComponent { }
    • Services – Services are used to share the data across the components. The decorator @Injectable() defines the class just below it as a service that can be injected as a dependency. @Injectable() export class UserService { }
    • Dependency Injection – Dependency Injection is a design pattern that is used to resolve the dependencies in different classes or components. you can inject the service in a component’s constructor as below. constructor(private service: UserService) { }
    • Routing – Angular provides a RouterModule to handle the navigation between the states and view of application.

    6. What is the difference between NgModules and JavaScript modules?

    NgModules are different from JavaScript modules in the following ways.

    • NgModule binds to declared classes only not all as Angular compiler only understands declared classes.
    • JavaScript modules define all member classes in one giant file but Angular modules use the declaration array to include all member class files.
    • NgModules exports only classes available in it’s declaration and imported from other modules, not all.
    • An NgModules can extend the entire application with services by adding providers in it’s providers list but JavaScript modules can not do this.

    7. What is the host view in Angular?

    When a component is created it’s directly associated with a single view that is called host view.

    8. What are the directives? How many types of directives are available in Angular?

    Directives provide the Program logic and extend the power of HTML by providing new syntax.
    Angular supports 3 types of directives as below.

    • Components – These are the directives with templates.
    • Structure directives – You can change DOM structure by adding or removing the elements. we use asterisk (*) as a prefix to the directive name. Structure directive examples are *ngIf, *ngFor etc. &lt;span *ngIf="user" class="name"&gt;{{user.name}}&lt;/span&gt;
    • Attribute directives – When you want to change the appearance or behavior of a DOM element, you can use attribute directive. Attribute directive example. import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[highlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } } // directive usage &lt;span highlight&gt;High light content!&lt;/span&gt;

    9. What is Data Binding in Angular? Explain 2 way data binding.

    Data binding is the way to share the data between a component class and its associated template called view. Angular provides 2 way data binding means component properties can be used in view for data and if you make any changes in view then changes should reflect back in component’s properties.

    10. What is Interpolation and Template Expressions in Angular?

    Interpolation provides the easiest way to bind a component property in the view. In Interpolation you put the property in the double curly braces ‘{{property=name}}’.
    Template expression is used in double curly braces and produces a value like {{1+1}}, it will produce a value 2. In Property binding an expression is the right side part of ‘=’ operator.

    11. What are the different types of binding available?

    Angular provides different ways of binding as below.

    • Property Binding – binding is set in one direction from component’s property to template. Property binding example.&lt;img [src]="ImageUrl"&gt;
    • Event Binding – It’s used to bind any event. Event binding example.&lt;button (click)="onUpdate($event)"&gt;Save&lt;/button&gt;
    • Two way binding – It’s used for two-way binding. Two-way data binding example.&lt;input [(ngModel)]="name"&gt;
    • Attribute binding – It’s used to set the value of an attribute directly. Attribute binding example.&lt;button [attr.aria-label]="help"&gt;help&lt;/button&gt;
    • Class binding – It’s used to add or remove class names from class attributes. Class binding example. &lt;span [class.specialClass]="isSpecialClass"&gt;Special class&lt;/span&gt;
    • Style binding – It’s used to add or remove the style from the style attribute. Style binding example.&lt;button [style.color]="isSpecialClass ? 'blue' : 'black'"&gt;Click Me&lt;/button&gt;

    12. What are the lifecycle hooks in angular?Components and directives have a lifecycle managed by Angular. Angular creates and renders the components and checks when their data bound properties change and destroy them before unloading. Angular creates components by calling it’s constructor and follows the sequence of lifecycle hooks as below.

    • ngOnChanges() – called when Angular resets data bound properties.
    • ngOnInit() – used to initialize the directive or component and sets data bound properties.
    • ngDoCheck() – when the changes are not detected by angular own then it’s used to catch those changes.
    • ngAfterContentInit()
    • ngAfterContentChecked()
    • ngAfterViewInit()
    • ngAfterViewChecked()
    • ngOnDestroy() – used to cleanup the component or directive before Angular destroys it.

    For more visit Angular Lifecycle hooks.

    13. How will you share the data between components?

    In many scenarios you need to share the data between the components. it can be parent to child, child to parent and unrelated components. So let’s understand this with the help of an example.

    • Parent To Child Component – any data from parent to child can be shared with the help of @Input decorator. // parent component import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `&lt;app-child [childMessage]="parentMessage"&gt;&lt;/app-child&gt;`, styleUrls: ['./parent.component.css'] }) export class ParentComponent{ parentMessage = "message from parent" constructor() { } } // child component import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `Say {{ childMessage }}`, styleUrls: ['./child.component.css'] }) export class ChildComponent { @Input() childMessage: string; constructor() { } }
    • Child To Parent Component 1 – you can share the data from child to parent using @Output decorator. import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `Message: {{message}}&lt;app-child (messageEvent)="receiveMessage($event)"&gt;&lt;/app-child&gt;`, styleUrls: ['./parent.component.css'] }) export class ParentComponent { constructor() { } message:string; receiveMessage($event) { this.message = $event } } import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `&lt;button (click)="sendMessage()"&gt;Send Message&lt;/button&gt;`, styleUrls: ['./child.component.css'] }) export class ChildComponent { message: string = "Hello Testing!" @Output() messageEvent = new EventEmitter(); constructor() { } sendMessage() {this.messageEvent.emit(this.message) } }
    • Child To Parent Component 2 – you can share the data from child to parent using @Viewchild decorator. import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { ChildComponent } from "../child/child.component"; @Component({ selector: 'app-parent', template: ` Message: {{ message }} &lt;app-child&gt;&lt;/app-child&gt; `, styleUrls: ['./parent.component.css'] }) export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent) child; constructor() { } message:string; ngAfterViewInit() {this.message = this.child.message} } @Component({ selector: 'app-child', template: ``, styleUrls: ['./child.component.css'] }) export class ChildComponent { message = 'Hello Testing!'; constructor() { } }
    • Share data between Unrelated Components – for this you can write one service and that service can be injected in both components. So Angular Services are used to share the data between unrelated components.

    14. What are the Pipes in Angular?

    A Pipe provides the functionality of transforming the data from your data input to desired output. For example, You receive some lower case data from the back end and now you want to display that data as upper case then you can Angular built in pipe ‘uppercase’. You can also create your custom pipes in angular.
    To implement a custom pipe, decorate your class with ‘@Pipe’ metadata and implement PipeTransform interface’s transform method as below.

    
    @Pipe({name: 'exponentialStrength'})
    export class ExponentialPipe implements PipeTransform {
      transform(value: number, exponent?: number): number {
        return Math.pow(value, isNaN(exponent) ? 1 : exponent);
      }
    }
    

    15. Explain the AOT compilation? Or What is the difference between JIT and AOT?

    Angular provides two ways for the compilation of your application.

    • JIT – Just-in-Time (JIT), it compiles the application at runtime in the browser. JIT is the default compiler in angular. When you run ng-build or ng-server it will compile your application.
    • AOT – Ahead-of-Time (AOT), it compiles the application at build time. AOT compiler converts all HTML and TypeScript code into JavaScript code during build before browsers start downloading JavaScript code. It makes rendering faster. AOT provides a lot of benefits as below.
      • Browsers get pre-compiled code and do not wait for compilation that results in faster Rendering.
      • It reduces the size of Angular framework as there is no need to download the compiled code.
      • Errors can be detected earlier during the build phase only.
      • AOT reduces the chances of injection attacks as it compiles the code long before they are sent to the client.
      • AOT improves the number of asynchronous resource requests as it inlines the external HTML templates and styles.

    16. What are the Services in Angular?

    In Angular services are the classes with well defined purpose. Services provide the functionality in a modular way which can be reused across the components. To share the data between components you can use services. You can make your components efficient by delegating some functionality code to services like fetch the data from server, validation rules etc. By defining this code into services you can make your code reusable to any component. You can create a service by using @Injectable decorator.

    
     // It's a self registering service, now no need to put this service in providers array in module or component
    @Injectable({
      providedIn: 'root', // to inject the dependency in root. 
    })
    export class UserService {
    }
    
    // You register a service at module level by setting the 'providers' property of @NgModule decorator. 
    @NgModule({
      providers: [
      UserService
     ],
     ...
    })
    
    // You can also register a service at component level by settings 'providers' property of @Component decorator.
    @Component({
      selector:    'app-user-list',
      templateUrl: './user-list.component.html',
      providers:  [ UserService ]
    })
    

    17. How to make a service a singleton in Angular?

    There are two ways to make a service a singleton as below.

    • First way is – inject the service in root by setting ‘providedIn’ property to ‘root’ in @Injectable decorator.
    • Second way is – include the service in AppModule only or in a module that is imported only in AppModule no where else.

    18. What is the provider in Angular?

    In Angular, dependency injection is used to inject the dependencies of services, A Provider works as an instructor for dependency injection system to resolve the dependencies. When you create any service it comes with a default @Injectable decorator that contains a default property ‘providedIn’ which creates the provider for service.

    
    @Injectable({
      providedIn: 'root',
    })
    export class DataService {
    }
    

    You can inject the services in the root or particular module as well and you can limit the scope of a service to a particular component by using component providers.

    
    @Component({
    /* . . . . .*/
      providers: [DataService]
    })

    19. Explain the dependency injection in Angular?

    Dependency Injection (DI) is a design pattern. Angular provides it’s own dependency injection to Angular applications to increase their efficiency and modularity. Dependency is an object or class that another class needs to complete its operations, for example A ‘UserComponent’ needs ‘UserService’ to perform user operations. Angular DI framework injects the dependencies when it’s instantiating the class or component.
    In angular it’s mandatory to create the service with @Injecible decorator. To get injected the service by dependency injection you need to specify providers.

    
    @Injectable({
      providedIn: 'root', // to inject the dependency in root
    })
    export class UserService {
    }
    
    //In user component constructor you can inject the dependency like this
    
    constructor(userService: UserService){}
    

    To configure providers at NgModule and Component level you can set the ‘providers’ metadata option of @Component and @NgModule decorators.

    20. What is RxJS library?

    RxJS (Reactive Extensions for JavaScript) is a library that uses the observable sequences for asynchronous and event-based or callback-based code. RxJS library has one core type ‘Observable’ and satellite types including (Observer, Schedulers, Subjects).
    RxJS provides many operators to support the below features.

    • To map to different types.
    • Iteration
    • Filter
    • Composition of multiple streams
    • To perform asynchronous operations convert existing code into observables.

    For more you can refer RxJS Library and Angular RxJS Library.

    21. What are the observables in Angular?

    In Angular, observables are used to achieve some common asynchronous operations as below.

    • Custom events are used to send observable output data from child to parent components.
    • Observables are used to handle Ajax requests and responses by HTTP Modules.
    • Observables are also used to listen and respond to the user-input events by Forms and Router Modules.

    For More about Observables refer Observables in Angular.

    22. What are the differences between Promises and Observables in Angular?

    Observables are compared with Promises most of the time, there are a lot of differences in them as below.

    • Observables are declarative means execution starts only when you subscribe to them but Promises start the execution on the creation only.
    • Observables can provide multiple values over the time but Promises provide only one value.
    • Observables provide many functions to perform transformations but promises have only ‘.then’ function.
    • Promises pass errors to child promises but Observable’s subscribe method provides good error handling.

    23.What is the subscribe method in Angular?

    You need to subscribe to the instance to use published values from Observable instances. For this, observable instances provide the subscribe method and pass an object to receive notifications.

    
    // Create simple observable that emits three values
    const testObservable = of(4, 5, 6);
    
    // Create observer object
    const tstObserver = {
      next: value => console.log('Observer got a next value that is: ' + value),
      error: err => console.error('Observer got an error: ' + err),
      complete: () => console.log('Observer got a complete notification'),
    };
    
    // Execute with the observer object
    testObservable.subscribe(tstObserver);
    // Logs:
    // Observer got a next value: 4
    // Observer got a next value: 5
    // Observer got a next value: 6
    // Observer got a complete notification
    

    24. How does routing work in Angular?

    Angular configure routes in the AppRoutingModule file. To configure routes first import the AppRoutingModule file in your AppModule and add it to the imports array.

    
    import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [AppRoutingModule] // CLI adds AppRoutingModule to the AppModule's imports array
    .....
    })
    

    To define and configure the routes perform below steps.

    • In AppRoutingModule import RouterModule and Routes.
    • Use Routes array to define your routes.
    • Configure routes to your application code.
    
    import { Routes, RouterModule } from '@angular/router'; // 1. CLI imports router
    const routes: Routes = [ { path: 'first-route', component: FirstRoute },
      { path: 'second-route', component: SecondRoute }]; // 2. sets up routes constant where you define your routes
    
    // configures NgModule imports and exports
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { 
    }
    // 3. configure routes
    &lt;nav&gt;
        &lt;ul&gt;
        &lt;li&gt;&lt;a routerLink="/first-route" routerLinkActive="active"&gt;First Route&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a routerLink="/second-route" routerLinkActive="active"&gt;Second Route&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/nav&gt;

    25. Explain the route guards?

    A User can navigate anywhere to the application at a moment of time, but sometimes you want to control the user access for various reasons as below.

    • Users must login.
    • You want to save some data before the user navigates.
    • you want to authorize the user.
    • You might ask the user to discard pending changes.
    • Many other reasons.

    To handle these scenarios Angular provides the concept of guards that can be added to routes. Router’s behavior can be controlled by guard’s return value as below.

    • If value is true means navigation continues.
    • If the value is false, navigation stops.
    • If value is UrlTree means new navigation initiates for returned UrlTree.

    26.What is Root Module in Angular?

    Every Angular application has at least one module, You bootstrap that module to launch the application. This module is called Root Module. When you create an angular application then you get by default one NgModule with the name AppModule called root module.

    27. Explain the feature module and types of feature modules.

    Angular provides one NgModule by default when you create any new angular application. As your application functionality grows then you can create a feature module responsible for a particular set of functionality. for example you can create routingModule for routes, for customer functionality customerModule etc. You can create a feature module using the below command and then you can import this feature module to your root module’s import array.

    
    ng generate module CustomerDashboard
    

    There are 5 types of feature modules as below.

    • Domain feature modules
    • Routed feature modules
    • Routing modules
    • Service feature modules
    • Widget feature modules

    28. Explain the lazy loading of feature modules.

    In Angular by default all NgModules are eager loaded means they load as soon as the app loads. But for large applications where there are many routes you should prefer lazy loading. Lazy loading is a pattern that loads modules as needed. It improves loading time of application as initial size of bundle is less.
    You can create a lazy loaded feature module as below.

    • You should create a feature module with angular CLI, using –route flag.
    • Configure the routes as per lazy loading guideline visit here Lazy Loading Angular Module.

    29. What is the HTTP interceptor?

    HTTP Interceptor intercepts and handles an HTTP request or response. You create your own interceptor by implementing the HttpInterceptor interface.

    
    interface HttpInterceptor {
        intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt;
    }
    

    In case of multiple interceptors, the first interceptor transforms the request before passing it to next with ‘next.handle(transformedReq)’ method.
    To use the same instance of HttpInterceptor for the entire application, import HttpClientModule in your appModule and add the interceptor to the root application injector. If you want to override this interceptor then specify another interceptor in the feature module.

    30. Explain some common commands in Angular.

    Angular provides many commands to perform operations as below.

    • npm install -g @angular/cli – to install angular cli.
    • ng help – list available commands with descriptions.
    • ng new my-first-project – create new angular workspace.
    • cd my-first-project – go to your app directory.
    • ng generate – generate new files or modify existing.
    • ng build – compile the app into an output directory named ‘dist’.
    • ng serve – build and serve your application.
    • ng run – runs an application with custom build configuration.
    • ng update – update dependencies in your application.
    • ng version – gives current CLI version.
    • There are many other visit Angular CLI commands.

    31. How will you create the library in Angular?

    Some applications provide general solutions like a unified interface, some data operations apps etc. Developers can create these general applications as a library which can be reused in different applications via npm packages. An Angular library differs from an Angular Application in that it can not run on its own as it must be imported in any application.
    You can create, build, run, lint an angular library with below commands.

    
    ng generate library auth-lib  // to create library
    ng build my-lib
    ng test my-lib
    ng lint my-lib
    

    32. How will you publish any angular library?

    Once you are ready with your angular library you can publish it to NPM repositories with below commands.

    
    ng build my-lib --prod
    cd dist/my-lib
    npm publish
    

    Here –prod flag specify to use older compiler and runtime instead of using Ivy in angular 9.

    33. How to update your angular applications to the latest version of angular?

    You can run a basic update command to update the latest stable release of angular CLI and angular core.

    ng update @angular/cli @angular/core

    Above command will update your application to the latest angular CLI and angular core. You can also update from one major version to another by specifying the version as below.

    
    ng update @angular/cli@^9 @angular/core@^9
    

    To check other dependencies you can visit Angular Update Guide and to set any options visit Angular ng update command.

    34. What is Transpiling in Angular?

    In Angular, Transpiling refers to the process of converting Typescript code into JavaScript code. It’s done using a TypeScript compiler that’s called a transpiler.

    35. Describe the Bazel that was introduced in Angular 8.

    Bazel is a build tool that works with angular CLI to build your application. The @angular/bazel package provides this build tool. To include bazel in an existing application use the below command.

    ng add @angular/bazel

    To use Bazel in a new application, first you need to install it globally using the below command.

    npm install -g @angular/bazel
    // and to create new application
    ng new --collection=@angular/bazel
    

    Now Bazel will be used behind the scene for the commands like ng build, ng serve. You can put the Bazel output in the dist/bin folder.

    36. What is an Angular service worker?

    Angular Service Worker is a script that runs in the browser and manages the caching for an application. It provides a good user experience with performance and reliability.
    It works as a network proxy that intercepts all the HTTP requests and decides how to respond to them. It can serve the request from cache if it is available. Unlike Other Angular scripts, service worker is preserved after the user closes the tab. The next time the browser loads the application, first the service worker loads and intercept all the requests without the need of the network.

    37. On what port Angular runs by default?

    By default, Angular runs on the 4200 port that could be configured.

    38. Explain the SPA (Single Page Application).

    SPA (Single Page Application) is a type of web application that provides a good user experience by dynamically loading the selected part of the application instead of loading the full application. SPA has good speed and performance.

    39. What is an AOT compiler?

    Browser does not understand Angular code directly, so compilation is required to convert that code into efficient JavaScript code. A ahead-of-time (AOT) compiler compiles the Angular and HTML code during the build phase so that compiled JavaScript code is available for the browser to download and run. AOT compiler compiles the code during build phase so it makes rendering to be fast in the browser. For more visit AOT Compiler.

    Angular 9 Interview Questions:

    1. List some new features in Angular 9

    Angular 9 released on 6th Feb 2024 with a stable version 9.0.0 release. It’s a major release of Angular that covers the Angular Framework, CLI, Angular Material and Platform updates.
    There are many new features provided in Angular 9 as below.

    • Project Ivy – A new compiler and runtime that all angular 9 applications will use by default.
    • ng update – is more informative and reliable to automatically use latest CLI, clearer progress update and easier update debugging
    • New additional options for providedIn to inject the services. One is platform and other is any
    • Providing support for TypeScript 3.7
    • An alternative approach to test the components called Component Harnesses
    • Improvements in IDE and language service
    • New Components – you can use youtube and Google maps inline in your application.

    2. How to update to Angular version 9?

    To update your project to Angular 9 First update your project to Latest Release of Angular 8 for better update experience as below.

    ng update @angular/cli@8 @angular/core@8

    Once you have updated to Angular 8 then update to Angular 9 or latest version of Angular as below.

    ng update @angular/cli @angular/core

    For detailed update changes follow Angular Official document Update to Angular 9.

    3. What is Project Ivy in Angular 9?

    Angular 9 has come with project Ivy with a lot of advantages as below. Ivy is a compiler and runtime. Angular version 9 allows all applications to use this Ivy compiler and runtime by default. There are many advantages of Ivy compiler and runtime.

    • Bundle sizes reduced – Ivy compiler generates lesser code for each angular component by removing the extra code which is not being used via tree-shaking.
    • Faster Testing – TestBed Implementation has been changed in Angular 9, As TestBed will not recompile all the components during the tests unless there are any changes made to components. So this improvement in TestBed increases the test speed to 40-50% faster.
    • Better Debugging –
    • CSS class and style binding improvements –
    • Type checking improvements –
    • Build errors improvement –
    • Build time improvements, AOT on by default enabled 
    • Internationalization improvements –

    For more details on Project Ivy follow the link Project Ivy in Angular 9.

    4. What are Component Harnesses in Angular 9?

    Normally component testing relies on implementation details, if a component library changes it’s implementation then all the test dependent on that component needs to be updated. But component harness API provides the capability of insulating or isolating for a test against the updates to component’s internal changes in DOM structure.
    So Component Harness provides an alternate approach to test the components. it will be available to component authors as a part of Component Dev Kit (CDK). Multiple environments can be supported by component harnesses, as only single harness implementation can be used for both unit testing and end to end testing.
    Let’s take a look at the example of Component Harness.

    
    it("should switch to customer data template", async () => {
      expect(fixture.debugElement.query("customer-form")).toBeNull();
      const select = await loader.getHarness(MatSelect);
      await select.clickOptions({ text: "Bug" });
      expect(fixture.debugElement.query("customer-form")).not.toBeNull();
    });
    

    5. What are the new options for ‘providedIn’ in Angular 9?

    Angular services are added to the injector using @Injectable decorator. Angular 9 is providing 2 more options to inject the services with existing additional options as below.

    • platform – When all applications on that page share a special singleton platform injector and you want a service to be available in that then you can specify providedIn:’platform’.
    • any – Whenever you want unique instance in every module (including lazy modules as well) which injects the token then you can specify providedIn:’any’.

    6. How ‘ng update’ works in Angular 9?

    Angular 9 has made ‘ng update’ more informative and reliable.

    • Always Latest CLI is used – While updates, CLI is used from destination version not latest but going forward updates will take the benefit of new update features automatically.
    • Will see progress updates clearly – Now ‘ng update’ will provide you complete information about migration.
    • Update debugging is easier – ‘ng update’ runs all migrations and you can inspect all changes after completion. But Angular 9 provides additional flag –create-commits. So when you run ‘ng update –create-commits’ then all migrations will run and after that tools will commit the code base state so that you can inspect and debug the changes made in your code.

    7. What are the improvements in IDE and language service in Angular 9?

    You can see some improvements to the Angular Language Service extension on visual studio marketplace. There were some bugs that have been fixed. Some other improvements include:

    • TextMate grammar behavior that provides syntax highlight ability in both in-line and external templates.
    • Hover tooltip will provide NgModule and Type information.
    • For templateUrl and styleUrls you can check definition by “Go to definition”.

    Some General Interview Questions for Angular

    1. How much will you rate yourself in Angular?

    When you attend an interview, Interviewer may ask you to rate yourself in a specific Technology like Angular, So It’s depend on your knowledge and work experience in Angular.

    2. What challenges did you face while working on Angular?

    This question may be specific to your technology and completely depends on your past work experience. So you need to just explain the challenges you faced related to Angular in your Project.

    3. What was your role in the last Project related to Angular?

    It’s based on your role and responsibilities assigned to you and what functionality you implemented using Angular in your project. This question is generally asked in every interview.

    4. How much experience do you have in Angular?

    Here you can tell about your overall work experience on Angular.

    5. Have you done any Angular Certification or Training?

    It depends on the candidate whether you have done any Angular training or certification. Certifications or training are not essential but good to have.

  • How to read recursively a directory in Node.js

    Learn how to iterate throught the child directories and files of a directory recursively in Node.js

    Either to create some kind of file search algorithm or to get a list of all the files and folders inside a directory to compress it with zlib, this feature is often searched for Node.js developers (and the number of downloads and dependent packages on some known modules proves it).

    In this article we are going to show you how to loop recursively through a directory to list all its content with 3 different methods (custom snippets or by using open source modules).

    A. Using a custom snippet

    If you want to loop recursively through a directory in Node.js, you don’t need necessarily a module to achieve it as you can use a very simple recursive function. The following filewalker function will do the trick for you. It expects as first argument a string with the path of the folder that will be recursively explored and as second argument a function (the callback) executed once there are no mores directories inside the providen path. The callback receives 2 arguments, the error as first and the result array that contains all the mixed paths of files and subdirectories.

    Note

    If you only need to ignore all the folders and retrieve only the paths of the files, you can comment easily the line that stores the filepath in the array within the snippet.

    const fs = require('fs');
    const path = require('path');
    
    /**
     * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
     * 
     * @see http://stackoverflow.com/a/5827895/4241030
     * @param {String} dir 
     * @param {Function} done 
     */
    function filewalker(dir, done) {
        let results = [];
    
        fs.readdir(dir, function(err, list) {
            if (err) return done(err);
    
            var pending = list.length;
    
            if (!pending) return done(null, results);
    
            list.forEach(function(file){
                file = path.resolve(dir, file);
    
                fs.stat(file, function(err, stat){
                    // If directory, execute a recursive call
                    if (stat && stat.isDirectory()) {
                        // Add directory to array [comment if you need to remove the directories from the array]
                        results.push(file);
    
                        filewalker(file, function(err, res){
                            results = results.concat(res);
                            if (!--pending) done(null, results);
                        });
                    } else {
                        results.push(file);
    
                        if (!--pending) done(null, results);
                    }
                });
            });
        });
    };

    Copy snippet

    And it’s usage is very simple:

    filewalker("./some-existent-path", function(err, data){
        if(err){
            throw err;
        }
        
        // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
        console.log(data);
    });

    Copy snippet

    This solution is perfect if you don’t want to rely on a module to achieve something very simple and directly in your code.

    B. Using the readdirp module

    If your code isn’t so simple, then the solution with a single snippet may be not enough for you due to the complexity of your code. In this case, you can use the readdirp module, yes readdirp not readdir. readdirp is a very useful module that exposes a recursive version of the readdir function available in the filesystem module of Node.js, besides it exposes a stream api.

    To install this module in your project, execute the following command in your terminal:

    npm install readdirp

    Copy snippet

    The advantages of the usage of this module are very clear and it’s not so simple as the first solution that we exposed in this article. This module allows you to filter your recursive exploration by file extension and by directory name, besides it allow you to set a depth (max value of subfolders to explore in the providen directory). It works in the following way, you need to require the readdirp module that is basically a function. With this function you will be able to iterate recursively through a folder path, it requires an object that specifies the settings, you can see all the available options of readdirp here:

    var settings = {
        root: './a-folder-to-explore',
        entryType: 'all',
        // Filter files with js and json extension
        fileFilter: [ '*.js', '*.json' ],
        // Filter by directory
        directoryFilter: [ '!.git', '!*modules' ],
        // Work with files up to 1 subdirectory deep
        depth: 1
    };

    Copy snippet

    Basically you only need to provide the root property that indicates which directory will be explored.

    The module offers 2 ways to be used, the first is with callbacks:

    // Import the module
    var readdirp = require('readdirp');
    
    var settings = {
        root: './your-folder-path',
        entryType: 'all'
    };
    
    // In this example, this variable will store all the paths of the files and directories inside the providen path
    var allFilePaths = [];
    
    // Iterate recursively through a folder
    readdirp(settings,
        // This callback is executed everytime a file or directory is found inside the providen path
        function(fileInfo) {
            
            // Store the fullPath of the file/directory in our custom array 
            allFilePaths.push(
                fileInfo.fullPath
            );
        }, 
    
        // This callback is executed once 
        function (err, res) {
            if(err){
                throw err;
            }
    
            // An array with all the fileEntry objects of the folder 
            // console.log(res);
            console.log(allFilePaths);
            // ["c:/file.txt",""]
        }
    );

    Copy snippet

    Or through the stream API:

    // Import the module
    var readdirp = require('readdirp');
    
    var settings = {
        root: './',
        entryType: 'all'
    };
    
    // In this example, this variable will store all the paths of the files and directories inside the providen path
    var allFilePaths = [];
    
    // Iterate recursively through a folder
    readdirp(settings)
        .on('data', function (entry) {
            // execute everytime a file is found in the providen directory
    
            // Store the fullPath of the file/directory in our custom array 
            allFilePaths.push(
                entry.fullPath
            );
        })
        .on('warn', function(warn){
            console.log("Warn: ", warn);
        })
        .on('error', function(err){
            console.log("Error: ", err);
        })
        .on('end', function(){
    
            console.log(allFilePaths);
            // ["c:/file.txt","c:/other-file.txt" ...]
        })
    ;

    Copy snippet

    Every fileEntry object, has the following structure, so you will get not only the full path but more useful information about the file or directory:

    {
        name: 'index.js',
        path: 'node_modules\\string_decoder\\index.js',
        fullPath: 'C:\\Users\\sdkca\\Desktop\\node-workspace\\node_modules\\string_decoder\\index.js',
        parentDir: 'node_modules\\string_decoder',
        fullParentDir: 'C:\\Users\\sdkca\\Desktop\\node-workspace\\node_modules\\string_decoder',
        stat:
        Stats {
            dev: -469691281,
            mode: 33206,
            nlink: 1,
            uid: 0,
            gid: 0,
            rdev: 0,
            blksize: undefined,
            ino: 562949954035272,
            size: 7796,
            blocks: undefined,
            atime: 2017 - 03 - 31T18: 27:30.703Z,
            mtime: 2017 - 03 - 31T18: 27:30.724Z,
            ctime: 2017 - 03 - 31T18: 27:30.724Z,
            birthtime: 2017 - 03 - 31T18: 27:30.703Z 
        }
    };

    Copy snippet

    For more information, please visit the repository of the module in Github here.

    C. Using klaw and klaw-sync modules

    Originally, a lot of developers used to rely on the wrench module (and many still rely on), however it’s now officialy deprecated and we love to promote standards, you should not use it anymore (we do not prohibit it, so feel free to explore the module if you want but think on that’s deprecated). The project now recommends to use the fs-extra module, however the module doesn’t support the walk() and walkSync() functions anymore (reason why the developers used the wrench module to explore recursively a directory).

    As the recursive functions aren’t available anymore, the fs-extra module recommends to use the klaw module. This module exposes an asynchronous Node.js file system walker with a Readable stream interface originally extracted from the fs-extra module.

    To install this module, execute the following command in your terminal:

    npm install klaw

    Copy snippet

    Klaw is very easy to use and customizable. To loop recursively through a directory, use the following snippet:

    // Import the klaw module
    var klaw = require('klaw');
    
    // an array to store the folder and files inside
    var items = [];
    
    var directoryToExplore = "./some-folder";
    
    klaw(directoryToExplore)
        .on('data', function (item) {
            items.push(item.path)
        })
        .on('end', function () {
            console.log(items);
        })
        .on('error', function (err, item) {
            console.log(err.message)
            console.log(item.path) // the file the error occurred on
        })    
    ;

    Copy snippet

    As it’s asynchronous, you need to rely on the end callback to do whatever you want with the list of found files and directories in the providen directory.

    For more information about the asynchronous klaw module, please visit the official repository in Github here.

    If you need the same functionality but synchronous, you can use the klaw-sync module. klaw-sync is a Node.js recursive file system walker, which is the synchronous counterpart of klaw. It lists all files and directories inside a directory recursively and returns an array of objects that each object has two properties: path and stats. path is the full path of the file or directory and stats is an instance of fs.Stats.

    To install this module, execute the following command in your terminal:

    npm install klaw-sync

    Copy snippet

    The synchronous version of klaw is so easy to use as the asynchronous version, however it’s more customizable than its counterpart. You can use the following snippet to explore a directory:

    // Require the module
    var klawSync = require('klaw-sync');
    
    // Create an empty variable to be accesible in the closure
    var paths;
    
    // The directory that you want to explore
    var directoryToExplore = "./folder-to-explore";
    
    try {
        paths = klawSync(directoryToExplore);
    } catch (err) {
        console.error(err);
    }
    
    // [
    //   {path:"c:/file.txt", stats: {..File information..}},
    //   {path:"c:/file.txt", stats: {..File information..}},
    //   {path:"c:/file.txt", stats: {..File information..}},
    // ]
    console.log(paths);

    Copy snippet

    klaw-sync allows you to filter directories and files by extension, name. Besides you can search only for directories or files by setting up the options:

    var klawSync = require('klaw-sync');
    
    var directoryToExplore = "./some-folder";
    
    var files = klawSync(directoryToExplore, {
        nodir: true
    });
    
    // [
    //   {path:"c:/file.txt", stats: {..File information..}},
    //   {path:"c:/file2.txt", stats: {..File information..}},
    //   {path:"c:/file3.txt", stats: {..File information..}},
    // ]
    console.log(files);
     
    var paths = klawSync(directoryToExplore, {
        nofile: true
    });
    
    // [
    //   {path:"c:/folder", stats: {..Folder information..}},
    //   {path:"c:/folder2", stats: {..Folder information..}},
    //   {path:"c:/folder3", stats: {..Folder information..}},
    // ]
    console.log(paths);

    Copy snippet

    For more information about the synchronous klaw module, please visit the official repository in Github here.

    Klaw stands for walk (but backwards) and it turned out (as of January 25, 2017) for the most cases that klaw and klaw-sync is faster than other modules.

    Happy coding !

  • 20 Common UI Developer Interview Questions 2024

    As a user interface developer, you must be well-versed in markup language, design concepts, and debugging. You are in charge of how a website looks and how users interact with it. If you are being interviewed for a position as a UI developer, you must answer questions about your knowledge, decision-making, and UI developer interview questions 2024 process. Preparing responses to frequently asked questions might assist you in organizing your ideas and increasing your confidence.

    SQL Interview Questions and Answers

    This post will look at some common interview questions and present sample solutions to help you prepare your own successful responses.

    General interview questions 2024

    When you are interviewed for a job as a UI developer, your interviewer may first ask you general interview questions. As an example:

    • Tell me about yourself.
    • Where do you see yourself in five years? In 10 years?
    • What makes you think you would be a good fit for this company?
    • What do you love most about being a UI developer?
    • What are your greatest strengths and weaknesses as a UI developer?

    Your interviewer may also ask you general questions connected to your UI role. For example:

    • How do XHTML, HTML4 and HTML5 differ?
    • What does the term “semantic HTML” mean?
    • Why are HTML, CSS and JavaScript referred to as front-end technologies?
    • What does web accessibility mean?
    • Discuss the position property in CSS and how it functions.
    • How can you test a website’s performance?
    • What is an Ajax Request?
    • What is jQuery?

    Sample UI developer interview questions 2024 and answers

    During your interview, you may be asked to share your professional experience with specific tasks and scenarios. The STAR approach can be used to explain the problem, clarify the work at hand, outline the activities you performed, and reveal the results of your efforts.

    Here are some detailed questions you might be asked in a UI developer interview:

    1. Can you describe your normal design process?

    This is a comprehensive topic, and your response may assist the interviewer in determining your suitability for any established web design team. Your design method may differ from that of other UI designers, but the interviewer may want to know if your procedures are meaningfully similar to those of the organization. When answering this question, be honest about what makes your design approach unique, but also demonstrate that you are capable of and ready to follow standard processes.

    I begin my design process by asking my clients what they want their site or application to look like or how they want their users to feel. Some of my clients may have some idea of how they want their website to look and feel while others give me specific details and data related to the purpose of their websites I can use to guide my design.

    My next step is to review visitor feedback. I may create and send out my own feedback forms or use those my clients already collected. I use both positive and negative feedback to inform my design. After this research, I create thumbnails and digital wireframes for website pages. I show my clients the designs and assets I create throughout the process to get quick feedback and make any changes as soon as possible. Then, I test the pages on a practice website. If the pages look and feel great, they can go live.

    2. Describe a normal working day for a UI designer.

    If your interviewer asks you this question, they may be interested in learning more about your ability to operate as part of a team. Consider what you regularly do as a UI designer on a daily basis, such as what your regular tasks are, how you do temporary jobs, and how you communicate with coworkers, supervisors, and clients.

    Usually, my day starts with a team meeting. We discuss our progress with certain aspects of website improvement and what we need to do to finish our tasks for the day or week. After our discussion, we spend an hour or two inspecting our code and testing it in a “sandbox,” or test website, before going live, if our coding and asset creation is finished that day.

    Throughout the day, I may receive messages from my supervisors and any clients who want updates on my projects. I make sure to promptly respond to each. I also spend some extra time I have each day reading up on any new developments on the UI industry and taking notes so I can discuss the changes with my team the next time we meet.

    3. If my website was slow, how would you diagnose the problem and fix it?

    This is another question that helps your interviewer to assess your method, but this time you can discuss your troubleshooting knowledge. When answering this question, walk the interviewer through the steps you’d take to determine out what’s slowing down webpages and what you’d do to speed them up.

    I would inspect various factors on your website. One thing I would do is use a link analysis tool to see if there are any dead links on the website. I would also check the coding on various pages of the site. One solution to the latter problem is to link similar pages to one CSS sheet and simplify the coding.

    Another thing I might do is move the JavaScript coding near the bottom of a page’s HTML document. This allows the page to show before all JavaScript coding is downloaded. Additionally, I would check the servers of the website. If allowed, I would change the distribution of the website to a content delivery network. This allows users to access the website via a server that is closer to their locations. After all this, I will again test the speeds of the website.

    4. What do you like the most about UI design?

    This question allows you to discuss what motivates you to do your job. Consider talking about the aspects of your prior job that you liked. For an even more effective response, underline the challenges you anticipate in this new role.

    You may hear this often, but my favorite part of UI design is when a system I have worked on is finally in the hands of users. I like to see how users interact with the websites and applications and to know that my hard work has made life easier for them in some way. Now, if a user experiences a problem with the system or website I worked on, that might mean that I have made a mistake. However, I relish the opportunity to take in user feedback and improve the system or website.

    5. How do you deal with negative user feedback?

    All UI designers will receive bad feedback; what matters is what you do with that feedback. You can apply the STAR technique with this question. Discuss a bad feedback experience you had and what you did to rectify the situation.

    One time, I worked on a free smartphone game app that required users to tap the screen with precise timing, but three out of five users left comments saying that the app was nonresponsive for them. Most of them left a rating of one or two stars.

    After corresponding with some users and having them investigate if there were outside issues, like magnets, that made their screens unresponsive on their end, I checked the coding of my app and realized that it was too large for certain phone operating systems. I revised the coding and resubmitted the app. The users I talked to all noticed a vast improvement in the system.

    6. Can you describe any other projects you have worked on 2024?

    The inquiry concerning user input may lead to another about your experience as a user interface designer. This is your chance to discuss how you collaborated with a team on a larger project. Consider talking about a time when you had to overcome a hurdle and detail what you did to get positive results.

    I was once on a four-person team whose job was to overhaul the website of an accomplished author and motivational speaker. The website had a lot of broken links, much of the text and assets were relegated to tables, there was a lot of colorful text and the site navigation was not intuitive. I worked with a writer, a graphic designer and an IT person to improve over 150 pages of content.

    After two months, I was able to redesign each page of the site, moving the navigation from the side to the top of each page. I even included a site map. Six months later, the website experienced more than triple its normal traffic. The owner of the website was so impressed with the design of the website that he recommended me to one of his friends.

    7. Can you describe a time where you had difficulties while working on a team?

    If you’re applying for a job that requires teamwork, your interviewer may want to know what teamwork abilities you have and how you’ve used them in the past. Discuss another example in which you worked in a team but where the team encountered difficulties working together. Consider emphasizing how you collaborated on solutions, resolving problems, or increased productivity.

    I once worked on a remote four-person team for a software startup. One of the challenges of working with the team was figuring out how to communicate despite different time zones. To get around this problem, we used conferencing software and scheduled one-on-one meetings.

    One day, I even asked the team leader, who was often unapproachable, what he thought about the conferencing software’s user interface. That led to a long discussion during which we talked about the tasks at hand for our team. That week, we figured out how to break up the workload among teammates, based on our strengths and the times we would likely upload our work. After a month, we were able to submit a product that users tested and provided feedback for. Through this experience, I learned more about correspondence and how to apply user feedback to my work.

  • 21+ Advanced JavaScript Interview Questions and Answers

    According to the 2024 Stack Overflow Annual Report, JavaScript has been the most commonly used programming language for six years in a row. Let’s face it, JavaScript is the core of your Full Stack Development skills and can’t be avoided at any Development Interview. Follow through and read the Indiahires.in the collection of the most popular and tricky JavaScript Interview Questions and Answers to get the next dream job.

    While typeof foo === “object” is a reliable way to test whether foo is an object, the surprising thing in JavaScript is that null is also considered an object!

    Therefore, to the surprise of most developers, the following code must log true (not false) to the console:

    	
    		var foo = null;
    		console.log(typeof foo === "object");  // logs true!				
    	
    

    As long as one is aware of this, the issue can easily be avoided by checking that the foo is null:

    				
    		console.log((foo !== null) && (typeof foo === "object"));  // logs false
    	
    

    To be absolutely comprehensive in our response, there are two other things worth noting:

    First, the above solution returns false if the foo is a function. In most cases, this is the optimal action, but in circumstances where you want to return true for functions as well, the following solution may be modified to:

    				
    		console.log((foo !== null) && ((typeof foo === "object") || (typeof foo === "function")));
    	
    

    Second, the above solution returns true if the foo is an array (e.g. if var foo =[];). In most cases, this is the optimal action, because arrays are actually objects, but in circumstances where you want to false for arrays as well, the above solution may be modified to:

    				
    		console.log((foo !== null) && (typeof foo === "object") && (toString.call(foo) !== "[object Array]"));
    
    		// However, there is another option that returns false for nulls, arrays, and functions, but valid for objects:
    
    		console.log((foo !== null) && (foo.constructor === Object));
    	
    

    Or, if you’re using jQuery:

    				
    		console.log((foo !== null) && (typeof foo === "object") && (! $.isArray(foo)));
    	
    

    ES5 makes the case of the array quite easy, including its own null check:

    				
    		console.log(Array.isArray(foo));
    	
    

    An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

    	
    		(function () {
    		    statements
    		})();				
    	
    

    It is a design pattern which is also known as the Self-Executing Anonymous Function and contains two key parts:

    1. The first is an anonymous lexical function contained within the grouping operator (). This restricts access to variables within the IIFE syntax and pollutes the global context.
    2. The second component generates the instantly invoked function expression () from which the JavaScript engine explicitly interprets the function.
    Examples

    The function becomes an expression of the function that is performed immediately. The element inside the expression can not be reached from outside the expression.

    				
    		(function () {
    		    var aName = "Barry";
    		})();
    		// Variable aName is not accessible from the outside scope
    		aName // throws "Uncaught ReferenceError: aName is not defined"
    	
    

    Assigning the IIFE to a variable stores the return value of the function, not the function description itself.

    				
    		var result = (function () {
    	    var name = "Barry"; 
    		    return name; 
    		})(); 
    		// Immediately creates the output: 
    		result; // "Barry"
    	
    

    I’m now using the following rule of thumb for functions in ES6 and beyond:

    1. Use function in the global framework and for Object.prototype properties.
    2. Using the class Object Constructor Method.
    3. Usage => somewhere else.

    Why do you use arrow functions almost everywhere?

    • Scope Security: Since arrow functions are used continuously, it is assumed to use the same object as the root. If even a single regular function callback is mixed in with a lot of arrow functions, there’s a risk that the target will get messed up.
    • Compactness: The arrow functions are easier to read and write to.
    • Clarity: When nearly all is an arrow function, every normal function automatically sticks  out for defining the scope. The developer will still look up the next-higher function statement and see what the object is.

    The code shown above will output the following to the console:

    outer func: this.foo = bar
    outer func: self.foo = bar
    inner func: this.foo = undefined
    inner func: self.foo = bar

    In the outer function, both this and self refer to myObject and then both may properly refer to and access foo.

    In the inner function, though, this no longer refers to myObject. As a consequence, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.

    The shortest and most important answer here is that use strict is a way to voluntarily implement stricter parsing and error handling of your JavaScript code during runtime. Code errors that may either have been overlooked or failed quietly would now result in errors or exceptions. It’s a safe practice in general.

    key benefits of strict mode:
    • Makes debugging easier: Code bugs that might otherwise have been overlooked or failed quietly would now create bugs or throw exceptions, warn you faster to problems with your code, and send you more quickly to their source.
    • Prevents accidental globals:Without a strict mode, assigning a value to an undeclared variable immediately generates a global variable with that name. This is one of the most popular JavaScript errors. In strict mode, trying to do so will create an mistake.
    • Eliminates this coercion: Without a strict mode, the reference to this value of null or undefined is automatically linked to the global. This can trigger a lot of head-fakes and pull-out bugs. In strict mode, referencing a null or undefined value may cause an error.
    • Disallows duplicate parameter values: Strict mode throws an error when it detects a duplicate named argument for a function ( e.g., function foo(val1, val2, val1)}), thereby finding what is almost certainly an error in your code that you would otherwise have spent a lot of time monitoring.

      Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g. var object = {foo: "bar", foo: "baz"};) but as of ECMAScript 2015 this is no longer the case.

    • Makes eval() safer: There are some differences in the behavior of eval() in strict mode and in non-strict mode. Most importantly, in strict mode, variables and functions declared within the eval() statement are not created within the scope of the statement (they are created within the scope of the statement in non-strict mode, which can also be a common source of problems).
    • Throws error on invalid usage of delete: The delete operator (used to remove properties from objects) can not be used for non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to remove a non-configurable property, whereas strict mode will cause an error in such a case.

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    It took me a while to understand how 'this' keyword works, but after reading about the bind method, it’s starting to make sense when it comes to the context of an object set explicitly and being able to use 'this' keyword.

    A common problem that occurs when we use functions is the scope of the function and the context of the object.

    Every function has its own scope with visible and accessible variables, but when we define closures, these internal functions often have their own scope. If we were to access the context of the external function from the inner functions (closures), we would have to define a variable specifying the context of the outer function.

    	
        	var self = this;
        
    

    To avoid polluting the scope of an external function, we may use the bind approach instead. If we invoke a function with  bind method, our closure or inner function is bound to the scope of the outer function.

    	
        	var foo = function() {
    			// some content
    			console.log(this);
    		}.bind(this);
        
    
    Code sample
    	
        	var user = {
    		  // this just holds our data in json object format
    		  data:[
    		    {name:"T. Woods", age:37},
    		    {name:"P. Mickelson", age:43}
    		  ],
    		  
    		  // this is an event handler we will use with our 'Get Random Person' button
    		  clickHandler: function(event) {
    		    // generates random number between 0 and 1
    		    var randomNum = ((Math.random () * 2 | 0) + 1) - 1;
    		    
    		    /*
    		      This line is adding a random person from the data array to the text field
    		      Note, that we are using 'this' keyword
    		      As of now, 'this' keyword is bound to the user object since we have not executed this function
    		    */
    		    $("input").val(this.data[randomNum].name + " " + this.data[randomNum].age);
    		  }
    		}
    		/*
    		  Now, we are assigning an event handler to the button's click event.
    		  We are invoking the clickHandler method from the user object.
    		  Once the button is clicked, the user.clickHandler method will be executed.
    		  Since we are invoking clickHandler method inside of click method.
    		  Our 'this' keyword inside of user.clickHandler is actually bound
    		  to our button HTML element and NOT user object.
    		  Executing code below will output an error because
    		  it cannot find the data property item from our user object.
    		*/
    		//$("button").click(user.clickHandler); // Uncaught TypeError: Cannot read property '--' of undefined
    
    		/*
    		  But when we use bind() on our method invocation.
    		  bind() sets the scope of our clickHandler method to the user object.
    		  Assigning the 'this' keyword to point to the user object rather
    		  then the button HTML element.
    		*/
    		$("button").click(user.clickHandler.bind(user));
        
    

    The NaN property is a value that is “not a number.” This special value is the result of an operation that could not be done either because one of the operands are non-numeric (e.g. “abc”/4) or because the outcome of the operation is non-numeric.

    Although this seems clear enough, there are a few very surprising features of NaN that can lead to hair-pulling bugs if one is not aware of them.

    For one thing, even though NaN means “not a number,” its form is, believe it or not, Number:

    	
        	console.log(typeof NaN === "number");  // logs "true"
    
        	/*Additionally, NaN compared to anything – even itself! – is false:*/
        	console.log(NaN === NaN);  // logs "false"
        
    

    The semi-reliable way to verify if a number is equal to NaN is with built-in function isNaN(), but even using isNaN() is an incomplete solution.

    Then a better way would be to use value !== value, which will only be valid if the value is equal to NaN. ES6 also provides a new Number isNaN() function, which is different and more accurate than the old global isNaN()function.

    Since Anonymous Functions are function expressions, rather than regular function declarations, which are statements. Function expressions are often more versatile. We can assign functions to variables, object properties, move them as arguments to other functions, and even write a single line code enclosed in anonymous functions.

    Example
    	
        	var squaredArray = inputArray.map(function(x) { return x * x; });
        
    

    This becomes much more concise with the ES6 syntax.

    	
        	var squaredArray = inputArray.map(x => x * x);
        
    

    Another common example will be the anonymous function used by the famous frameworks such as the IIFE (immediate Invoked Feature Expression) feature.

    	
        	(function() { })();
        
    

    const and Object.freeze() serve totally different purposes.

    • const

      const is there for declaring a variable which has to assinged right away and can’t be reassigned. variables declared by const are block scoped and not function scoped like variables declared with var

      Example 1: Can’t reassign const
      	
          	const foo = 5;
      
      		foo = 6;
          
      

      The following code throws an error because we are trying to reassign the variable foo who was declared with the const keyword, we can’t reassign it.

      Example 2: Data structures which are assigned to const can be mutated
      	
          	const object = {
      		  prop1: 1,
      		  prop2: 2 
      		}
      
      		object.prop1 = 5;   // object is still mutable!
      		object.prop3 = 3;   // object is still mutable!
      
      		console.log(object);  // object is mutated
          
      

      In this example we declare a variable using the const keyword and assign an object to it. Although we can’t reassign to this variable called object, we can mutate the object itself. If we change existing properties or add new properties this will this have effect. To disable any changes to the object we need Object.freeze().

    • Object.freeze()

      Object.freeze() is a method which accepts an object and returns the same object. Now the object cannot have any of its properties removed or any new properties added.

      Example 1: Can’t mutate a frozen object
      	
          	object1 = {
      		  prop1: 1,
      		  prop2: 2
      		}
      
      		object2 = Object.freeze(object1);
      
      		console.log(object1 === object2); // both objects are refer to the same instance
      
      		object2.prop3 = 3; // no new property can be added, won't work
      
      		delete object2.prop1; // no property can be deleted, won't work
      
      		console.log(object2); // object unchanged
          
      

      In this example when we call Object.freeze() and give object1 as an argument the function returns the object which is now ‘frozen’. If we compare the reference of the new object to the old object using the === operator we can observe that they refer to the same object. Also when we try to add or remove any properties we can see that this does not have any effect (will throw error in strict mode).

      Example 2: Objects with references aren’t fully frozen
      	
          	const object = {
      		  prop1: 1,
      		  nestedObj: {
      		    nestedProp1: 1,
      		    nestedProp2: 2,
      		  } 
      		}
      
      
      		const frozen = Object.freeze(object);
      
      		frozen.prop1 = 5; // won't have any effect
      		frozen.nestedObj.nestedProp1 = 5; //will update because the nestedObject isn't frozen
      
      		console.log(frozen);
          
      

      This example shows that the properties of nested objects (and other by reference data structures) are still mutable. So Object.freeze() doesn’t fully ‘freeze’ the object when it has properties which are references (to e.g. Arrays, Objects).

    This which sound trivial and, in fact, it is trivial with ECMAscript 6, which introduces a new Number.isInteger() function for this very reason. However, this is a little more complicated before ECMAScript 6, as no equivalent Number.isInteger() method is given.

    The problem is that integers only exist conceptually in the ECMAScript specification; i.e. numeric values are only represented as floating point values.

    With that in mind, the easiest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as string or null is passed to the function) will be the following use by the Bitwise XOR operator:

    	
    		function isInteger(x) { return (x ^ 0) === x; } 				
    	
    

    The following solution will also work, but not as elegant as the one mentioned above:

    	
    		function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); } 
    	
    

    The following function (or with Math.ceil() or Math.floor() instead of Math.round() )might also seem useful, but the results are not exactly the same as the following two functions:

    	
    		function isInteger(x) { return Math.round(x) === x; }
    	
    

    The difference is that these Math-based solutions return true to Infinity and-Infinity, while the others (and in particular ES6’s Number.isInteger()) return false.

    Another reasonably common incorrect solution is as follows:

    	
    		function isInteger(x) { return parseInt(x, 10) === x; }
    	
    

    Although this parseInt-based approach will work well for many values of x, once x becomes very high, it will not work properly.The problem is that parseInt() pushes its first parameter to a string before parsing the digits. Therefore, until the number becomes sufficiently large, the representation of the string will be shown in exponential form (e.g., 1e+21). parseInt() will then attempt to parse 1e+21, but will avoid parsing when the e character is reached and will then return a value of 1. Remarks:

    	
    		> String(1000000000000000000000)
    		'1e+21'
    
    		> parseInt(1000000000000000000000, 10)
    		1
    
    		> parseInt(1000000000000000000000, 10) === 1000000000000000000000
    		false
    	
    

    Callbacks are a smart way to do something when something important has been done. We mean the execution of a function by something here. If we want to perform a function right after some other function is returned, then callbacks can be used.

    The JavaScript functions have an object type. So, just like any other object (string, arrays, etc.), it can be passed as an argument to any other function when calling.

    	
    	// add() function is called with arguments a, b 
      // and callback, callback will be executed just  
      // after ending of add() function 
      
      function add(a, b , callback){ 
       document.write(`The sum of ${a} and ${b} is ${a+b}.` +"
    "); callback(); } // add() function is called with arguments given below // Calling add() function add(5,6,function disp(){ document.write('This must be printed after addition'); });

    Callbacks are mainly used when performing asynchronous operations, such as making an API request to Google Maps, retrieving / writing data from / to a file, recording event listeners and related stuff. The callbacks are used for all the operations listed. This way, once the data / error from the asynchronous operation is returned, the callbacks are used to do something within our code.

    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.

    Lexical scoping

     
      function init() {
        var name = 'Mozilla'; // name is a local variable created by init
        function displayName() { // displayName() is the inner function, a closure
          alert(name); // use variable declared in the parent function
        }
        displayName();
      }
      init();
      
    

    init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

    Closure

     
      var globalVar = "xyz";
    
    (function outerFunc(outerArg) {
        var outerVar = 'a';
        
        (function innerFunc(innerArg) {
        var innerVar = 'b';
        
        console.log(
            "outerArg = " + outerArg + "\n" +
            "innerArg = " + innerArg + "\n" +
            "outerVar = " + outerVar + "\n" +
            "innerVar = " + innerVar + "\n" +
            "globalVar = " + globalVar);
        
        })(456);
    })(123);
      
    
    Output
     
      outerArg = 123
      innerArg = 456
      outerVar = a
      innerVar = b
      globalVar = xyz
    

    The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

    In this case, myFunc is a reference to the instance of the function displayName that is created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use, and “Mozilla” is passed to alert.

     
      function makeAdder(x) {
        return function(y) {
          return x + y;
        };
      }
    
      var add5 = makeAdder(5);
      var add10 = makeAdder(10);
    
      console.log(add5(2));  // 7
      console.log(add10(2)); // 12
      
    

    n this example, we have defined a function makeAdder(x), that takes a single argument x, and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.

    Reference Link

    a) No matter what button the user presses, the number 5 will still be logged in to the console. This is because, at the point where the onclick method is invoked (for each of the buttons), the for loop has already been completed and the variable I already has a value of 5. 

    b) The key to this work is to catch the value of I at each pass through the for loop by passing it to the newly generated function object. Here are four potential ways to do this:

    	
    	for (var i = 0; i < 5; i++) {
        var btn = document.createElement('button');
        btn.appendChild(document.createTextNode('Button ' + i));
        (function (i) {
          btn.addEventListener('click', function() { console.log(i); });
        })(i);
        document.body.appendChild(btn);
      }
    

    The logged output will be:

     
      "array 1: length=5 last=j,o,n,e,s"
      "array 2: length=5 last=j,o,n,e,s"
    

    arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e',"']) after the above code has been executed for the following reasons:

    1. Calling the reverse() method of an array object not only returns the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1).
    2. The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a response, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when something is done with arr2 (i.e. when we invoke arr2.push(arr3), arr1 will be affected as well, because arr1 and arr2 are simply references to the same object.

    The above code will output the following to the console:

     
      "122"
      "32"
      "02"
      "112"
      "NaN2"
      "NaN"
    

    The main issue here is that the JavaScript (ECMAScript) is a loosely typed language and performs automatic type conversion on values to accommodate the operation being performed. Let's see how this is achieved for each of the examples above.

    • Example 1: 1 + "2" + "2"

      Outputs: "122"
      Explanation:

      The first operation to be done in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes that it needs to perform string concatenation and thus converts the type 1 to "1", 1 + "2" returns "12" Then, "12" + "2" returns code>"122"

    • Example 2: 1 + +"2" + "2"

      Outputs: "32"
      Explanation:

      Based on the order of operation, the first operation to be performed is + "2" (extra + before the first "2" is regarded as a single operator). As a result, JavaScript converts the form of "2" to numeric and then applies the unary + sign to it (i.e. treats it as a positive number). As a consequence of this, the next operation is now 1 + 2 which, of course, yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so again, JavaScript converts the type of the numeric value to a string and performs a string concatenation, yielding "32."

    • Example 3: 1 + -"1" + "2"

      Outputs: "02"
      Explanation:

      The explanation here is the same as the previous example, except that the unary operator is - rather than +. Thus, "1" becomes 1, which then becomes -1 when applied, which is then added to 1 yielding 0, which is then converted to a string and concatenated to the final "2" operand, yielding "02"

    • Example 4: +"1" + "1" + "2"

      Outputs: "112"
      Explanation:

      While the first "1" operand is typed to a numeric value based on the unary + operator that precedes it, it is automatically transformed back to a string when it is concatenated to the second "1" operand, which is then concatenated to the final "2" operand, yielding the string "112."

    • Example 5: "A" - "B" + "2"

      Outputs: "NaN2"
      Explanation:

      Since the-operator can not be applied to strings, and because neither "A" nor "B" can be converted to numeric values, "A"-"B" produce NaN which is then concatenated to string "2" to produce "NaN2."

    • Example 6: "A" - "B" + 2

      Outputs: "NaN"
      Explanation:

      Since the-operator can not be applied to strings, and because neither "A" nor "B" can be converted to numeric values, "A"-"B" produce NaN. But any operator applied to NaN with any other numeric operand will still produce "NaN"

    The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5.

    The explanation for this is that each function executed inside the loop will be executed after the entire loop has been completed and all will then apply to the last value stored in I which was 5.

    Closures can be used to avoid this issue by creating a specific scope for each iteration, and by storing each specific value of the variable within its scope as follows:

     
      for (var i = 0; i < 5; i++) {
          (function(x) {
              setTimeout(function() { console.log(x); }, x * 1000 );
          })(i);
      }
    

    This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.

    The output of this code will be 456 (not 123).

    The explanation for this is as follows: when setting an object property, JavaScript will implicitly string the value of the parameter. In this case, since b and c are both objects, both objects will be translated to "[object object]." As a result, a[b] and a[c] are both similar to a ['[object object]'] and can be used interchangeably. Setting or referencing a[c] is also exactly the same as setting or referencing a[b].

    The code will output the value of 10 factorial (i.e., 10!, or 3,628,800).

    The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1. Here, therefore, is what this does:

     
    
      f(1): returns n, which is 1
      f(2): returns 2 * f(1), which is 2
      f(3): returns 3 * f(2), which is 6
      f(4): returns 4 * f(3), which is 24
      f(5): returns 5 * f(4), which is 120
      f(6): returns 6 * f(5), which is 720
      f(7): returns 7 * f(6), which is 5040
      f(8): returns 8 * f(7), which is 40320
      f(9): returns 9 * f(8), which is 362880
      f(10): returns 10 * f(9), which is 3628800
    
    

    Node JS Interview Questions

    The output will be 1, even though the value of x is never set in the inner function. Here’s why:.

    Closure is a function, along with all variables or functions that were in-scope at the time the closure was made. In JavaScript, a closure is performed as a "inner function;" i.e. a function specified within the body of another function. An significant feature of closures is that the inner function always has access to the variables of the outer function.

    Therefore, in this case, since x is not specified in the inner function, the scope of the outer function is searched for the given variable x, which is found to have a value of 1.

    Output:

    
      10
      2
    

    First, as fn is passed as a parameter to the function method, the scope (this) of the fn function is a window. var length = 10; is stated at the window level. You may also view it as window.length or length or this.length (when this === window).

    Method is bound to Object obj, and obj.method is named for parameters fn and 1. Although the method accepts just one parameter, it has passed two parameters when invoking; the first is a callback function and the second is just an amount.

    When fn() is called inside method, which passed the function as a global parameter, this.length will have access to var length = 10 (declared globally) not length = 5 as described in Object obj.

    Now, we know that we can use the arguments[] array to access any number of arguments in the JavaScript function. Hence arguments[0]() is nothing but a call to fn(). Inside fn now, the scope of this function becomes the arguments list, and logging the duration of the arguments[] returns 2.

    Output:

    
      1
      undefined
      2
    

    var statements are hoisted (without their initialization value) to the top of the global or function range to which they belong, even if they are within a with or catch row. However, the error identifier is only visible inside the catch block. It is equivalent to the following:

    
      (function () {
        var x, y; // outer and hoisted
        try {
            throw new Error();
        } catch (x /* inner */) {
            x = 1; // inner x, not the outer one
            y = 2; // there is only one y, which is in the outer scope
            console.log(x /* inner */);
        }
        console.log(x);
        console.log(y);
      })();
    
    
      var obj = {a: 1 ,b: 2}
      var objclone = Object.assign({},obj);
    

    Now the value of objclone is {a: 1 ,b: 2} but points to a different object than obj.

    Note the possible pitfall, though: Object.clone() can only create a shallow copy, not a deep copy. This ensures that the nested objects are not copied. They still refer to the same nested objects as the original ones:

    
      let obj = {
          a: 1,
          b: 2,
          c: {
              age: 30
          }
      };
    
      var objclone = Object.assign({},obj);
      console.log('objclone: ', objclone);
    
      obj.c.age = 45;
      console.log('After Change - obj: ', obj);           // 45 - This also changes
      console.log('After Change - objclone: ', objclone); // 45
    

    The first statement returns true which is as expected.

    The second returns false because of how the JavaScript engine works regarding operator associativity for < and >. It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1. true has value 1, so it then compares 1 > 1, which is false.

    ES5:

    
        var myArray = ['a', 'b', 'c', 'd'];
        myArray.push('end');
        myArray.unshift('start');
        console.log(myArray); // ["start", "a", "b", "c", "d", "end"]
    

    With ES6:

    
        myArray = ['start', ...myArray];
        myArray = [...myArray, 'end'];
    
    
        myArray = ['start', ...myArray, 'end'];
    

    A Set is a collection of items that are unique, i.e. no element can be replicated. Set in ES6 are ordered: the Set elements can be iterated in the insertion order. Set can store any kind of value, whether primitive or entity.

    Syntax:

    
        new Set([it]);
    
        Parameter: 
        it - It is an iterable object whose all elements are 
        added to the new set created, 
        If the parameter is not specified or null is passed 
        then a new set created is empty.
    
        Returns:
        A new set object
    

    Example:

    
        // it contains 
        // ["sumit","amit","anil","anish"] 
        var set1 = new Set(["sumit","sumit","amit","anil","anish"]); 
          
        // it contains 'f', 'o', 'd' 
        var set2 = new Set("fooooooood"); 
          
        // it contains [10, 20, 30, 40] 
        var set3 = new Set([10, 20, 30, 30, 40, 40]); 
          
         // it is an  empty set 
        var set4 = new Set(); 
    

    Properties:

    Set.prototype.size – It returns the number of elements in the Set.

    Methods:

    1. Set.prototype.add() – It adds the new element with a specified value at the end of the Set object.

      Syntax:

      
          set1.add(val);
      
          Parameter:
          val - It is a value to be added to the set.
      
          Returns: 
          The set object
      
    2. Set.prototype.delete() – It deletes an element with the specified value from the Set object.

      Syntax:

      
          set1.delete(val);
      
          Parameter:
          val - It is a value to be deleted from the set.
      
          Returns: 
          true if the value is successfully deleted from the set else returns false.
      
    3. Set.prototype.clear() – It removes all the element from the set.

      Syntax:

      
          set1.clear();
      
          Parameter:
          No parameters
      
          Returns: 
          undefined
      
    4. Set.prototype.entries() – It returns an iterator object which contains an array having the entries of the set, in the insertion order.

      Syntax:

      
          set1.entries();
      
          Parameter:
          No parameters
      
          Returns: 
          It returns an iterator object that contains an
          array of [value, value] for every 
          element of the set, in the insertion order.
      
    5. Set.prototype.has() – It returns true if the specified value is present in the Set object.

      Syntax:

      
          set1.has(val);
      
          Parameter:
          val - The value to be searched in the Set
      
          Returns: 
          True if the value is present else it returns false.
      
    6. Set.prototype.values() – It returns all the values from the Set in the same insertion order.

      Syntax:

      
          set1.values();
      
          Parameter:
          No parameters
      
          Returns: 
          An iterator object that contains all the values of the set in the same order 
          as they are inserted.
      
    7. Set.prototype.keys() – It also returns all the values from the Set in the insertion order.

      Syntax:

      
          set1.keys();
      
          Parameter:
          No parameters
      
          Returns: 
          An iterator object that contains all the 
          values of the set in the same order
          as they are inserted.
      
    8. Set.prototype.forEach() – It executes the given function once for every element in the Set, in the insertion order.

      Syntax:

      
          set1.forEach(callback[,thisargument]);
      
          Parameter:
          callback - It is a function which is to be executed for each element of the Set.
          thisargument - Value to be used as this when executing the callback.
      
          Returns: 
          Undefined
      

      The callback function is provided with three parameters as follows:

      • the element key
      • the element value
      • the Set object to be traversed

      Example:

      
          // Using Set.prototype.forEach(callback[, thisarg]) 
          // creating set  
          var set1 = new Set(); 
            
          // adding element to the set 
          set1.add({Firstname: "India", Lastname: "Hires"}); 
          set1.add(50); 
          set1.add(30); 
          set1.add(40); 
          set1.add("Geeks"); 
          set1.add("GFG"); 
            
          // Declaring a call back function 
          // we are using only one parameter value 
          // so it will ignore other two . 
          function printOne(values) 
          { 
              console.log(values); 
          } 
            
          // It prints value of all the element  
          // of the set 
          set1.forEach(printOne); 
            
          // Declaring a call back function 
          // we are using two parameter value 
          // so it will ignore last one  
          function printTwo(key, values) 
          { 
              console.log(key+"  "+values); 
          } 
            
          // As key and values are same in set 
          // so it will print values twice 
          set1.forEach(printTwo); 
            
          // Declaring a call back function 
          // we are using all three parameter value 
          function printThree(key, values, set) 
          { 
              // it will print key and value  
              // and the set object 
                            
              console.log(key+"  "+values); 
              console.log(set); 
          } 
            
          // It prints key and value of each  
          // element and the entire set object 
          set1.forEach(printThree); 
      
    9. Set.protoype[@@iterator]() – It returns a Set iterator function which is values() function by default.

      Syntax:

      
          set1[Symbol.iterator]();
      
          Parameter:
          No parameters
      
          Returns: 
          A Set iterator function and it is values() by default.
      

      Example:

      
          // using Set.protoype[@@Iterator]() 
          var 
  • Node JS Interview Questions

    Node JS Interview Questions

    If you wish to make a career in Node JS, below are the top Node JS interview questions with answers which will make you interview-ready.

    A comprehensive, community-driven list of essential Node js interview questions. Whether you're a candidate or interviewer, these interview questions will help prepare you for your next Node.js interview ahead of time.

    Basic understanding of Node JS

    Node js can be used to build different types of applications, such as web applications, real-time chat applications, REST API servers, etc. Nonetheless, it is primarily used to create network programs such as web servers, similar to PHP, Java, or ASP.NET. Node js was created in 2009 by Ryan Dahl.

    Node js is a run-time JavaScript environment developed on top of the Chrome V8 engine. Uses an event-driven, non-blocking I / O model. It's lightweight and it's so effective. Node js has an architecture module called npm.

    In its elementary sense, Node js is a JS runtime built using the Chrome V8 JavaScript engine as a platform. Node js has gained popularity as it is lightweight and efficient, mainly due to its event-driven and non-blocking I / O model. Built with performance as its primary goal, Node js is responsible for translating the JavaScript code into the native machine code, which can then be used by your computer to execute the operation.

    While it is based on the V8 engine used in Google Chrome and other chromium-based browsers (Vivaldi, Brave and Opera), it does not run in the browser itself. Throughout creation, various features such as file system API, HTTP server, and OS utility methods have been added to the engine so that Node js can be run as a program on a device.

    Event-Driven Programming is a concept that is commonly used when referring to the flow of events by tapping, loading, and so on. EDP is very significant when it comes to the most common programming languages of today, such as java and c #.

    The event-driven method is used in Node JS. What is surprising is that the Node JS application runs through a single thread but with a callback system, it is very possible to achieve concurrence.

    How does the Node application work?

    Callback is an event that is invoked immediately after the completion of a certain task. Most Node JS APIs are single threaded; therefore, asynchronous function calls are required to allow concurrency maintenance.

    The Observer Pattern helps the Node JS thread to manage the event loop. As a consequence, the corresponding task is initialized immediately and sends a signal to the event-listener to start its execution.

    An overview of the Event Driven Programming.
    Node JS Interview Questions

    In this concept, the event emitter emits several events and the main loop immediately listens to them, which causes a callback function to be triggered after the loop event is detected. The function of the event emitter is therefore to simplify the interaction of the event loop. The callback functions like an case, but it is only called in the case that the asynchronous returns its output.

    Node JS relies heavily on the use of events , making it a relatively fast application compared to other similar technologies. Once the server node begins, it initiates the variables, announces and waits for the event to operate. Several built-in modules within Node JS, together with the Event Emitter, connect the event types to a simplified and personalized listener.

    It is also clear that Node JS event modules are responsible for the creation of events, event handlers and emitters. An event loop consists of an entry region where an event is triggered by invoking the event handler to produce more than one event that will execute the event one after the other, thereby generating the event drive programming.

    Callback Hell is a phenomenon that affects JavaScript developers when they seek to run several asynchronous operations one after the other. Some people call it the doom pyramid. Let's take a look at an example of what we call hell back.

     
      
        doSomething(param1, param2, function(err, paramx){
            doMore(paramx, function(err, result){
                insertRow(result, function(err){
                    yetAnotherOperation(someparameter, function(s){
                        somethingElse(function(x){
                        });
                    });
                });
            });
        });   
      
    

    This is looking bad just from the skeleton itself. In real code you will obviously have other statements like if, for or some other operations along with these nested functions. Add those to the above code and it would get really messy and unmanageable.

    Suggestion:

    Don't strain your tasks. Most of the time, it may be likely that the real problem you 're facing isn't a callback hell, it's a badly written function. For these instances, the solutions we'll see below will structure your code, but they're not going to solve the real problem. So, as a rule of thumb, make your role do less, that is, write small functions that perform a single task.

    Techniques for avoiding callback hell

    There are a number of techniques for dealing with callback hell. In particular, we'll take a look at the three below.

    1. Using Async.js
    2. Using Promises
    3. Using Async-Await
    Managing callbacks with Async.js

    Async is a very powerful npm module for managing the asynchronous nature of JavaScript. It also works for JavaScript written for browsers, along with Node JS.

    Async provides a lot of powerful utilities to work with asynchronous processes under different scenarios.

    async.waterfall()

    Async Waterfall is useful when you want to perform certain tasks one after the other and at the same time move the outcome from the previous task to the next.

    async.waterfall() takes in an array of functions 'tasks' and a final 'callback' function which is called after all the functions in tasks have completed or a callback is called with an error.

     
      
        var async = require('async');
        async.waterfall([
            function(callback) {
                //doSomething
                callback(null, paramx); //paramx will be availaible as the first parameter to the next function
                /**
                    The 1st parameter passed in callback.
                    @null or @undefined or @false control moves to the next function
                    in the array
                    if @true or @string the control is immedeatly moved
                    to the final callback fucntion
                    rest of the functions in the array
                    would not be executed
                */
            },
            function(arg1, callback) {
                //doSomething else
              // arg1 now equals paramx
                callback(null, result);
            },
            function(arg1, callback) {
                //do More
                // arg1 now equals 'result'
                callback(null, 'done');
            },
            function(arg1, callback) {
                //even more
                // arg1 now equals 'done'
                callback(null, 'done');
            }
        ], function (err, result) {
            //final callback function
            //finally do something when all function are done.
            // result now equals 'done'
        });   
      
    

    So using async.waterfall() you would be writing you code vertically instead of indenting it horizontally and entering the pyramid of doom. Plus your code would be much more structured and easy to read.

    async.series()

    Async provides another method for managing series execution, async.series(). Async series works in the same way as Async waterfall, by executing functions in the array one after the other, with the difference that it will not pass data from one function to another, instead, when all functions have completed their execution, the function result will be available as an array in the final callback.

    Similar to async.waterfall() in async.series() as well, when all of the functions are called with an error callback, no further functions are performed in the list and the final callback is immediately called with an error value. Have a look for a direct picture below.

     
      
        var async = require('async');
        async.series([
            function(callback){
                // do some stuff ...
                callback(null, 'one');
                /**
                    The 1st parameter passed in callback.
                    @null or @undefined or @false control moves to the next function
                    in the array
                    if @true or @string the control is immedeatly moved
                    to the final callback fucntion with the value of err same as
                    passed over here and
                    rest of the functions in the array
                    would not be executed
                */
            },
            function(callback){
                // do some more stuff ...
                callback(null, 'two');
            }
        ],
        // optional callback
        function(err, results){
            // results is now equal to ['one', 'two']
        }); 
      
    

    There are more interesting functions available with the Async module to make sure you check them out and use them in your Node JS projects.

    Visit Async.js Website

    Managing callbacks with Promises

    Promises are an alternative to callbacks when dealing with asynchronous code. Promises return the value of the result or an exception to the error. The center of the promise is the .then() function, which waits for the promise object to be returned. The .then() function takes two optional functions as arguments and, depending on the promise status, only one will be called. The first role is named when the promise is fulfilled (a positive outcome). The second function is called when the promise has been rejected.

    Let's see the structure of a typical vow.

     
      
        var outputPromise = getInputPromise().then(function (input) {
            //handle success
        }, function (error) {
            //handle error
        });
      
    
    Chaining promises

    We may also render chain guarantees, this is an identical option to nesting callbacks. There are two ways to keep promises in chains. Promises can be chained within or outside the handler (.then() function). Chaining promises outside the handle is a lot clean and easy to read, but we may have to chain promises within the handler if we want to use any parameter in our next handler that is accessible within the reach of the previous handler.

    But too much chaining within the handler will again result in a horizontal code that we are trying to prevent. We may also make chain guarantees with a mixture of inner and outer chains. For a general rule, I would recommend that you stop chaining within the handler.

    However, another positive thing about chaining promises is that we can, however, add a catch block at the end of the chain to capture any error that happens in any of the relevant functions.

     
      
        return getUsername().then(function (username) {
            return getUser(username);
        })
        .then(function (user) { //example of chaining outside the handler
           return userPassword().then(function(password){
                /**
                    example of chaining inside the handler,
                    since we need to use the @user param
                    from the previous handler scope
                */
                if(user.password !== password){
                    //reject promise or throw error
                    return;
                }
            });
        })
        .catch(function(e){
             //handle error
             console.log(e);
        });
      
    
    Creating a function that returns a Promise

    To create a function that works with promises we can use the in-built Promise class.

     
      
        const test = function(){
            return new Promise((resolve, reject)=>{
                setTimeout(() => {
                    resolve('done');
                }, 10);
            });
        }
    
        //call it like this
        test().then((resp)=>{
            console.log(resp);
        })
        .catch((e)=>{
            console.log(e);
        });
      
    

    A promise is considered successful if the value is returned with the resolve method and unsuccessful if it is returned with the reject method.

    Managing callbacks with Async Await

    Some of the best things to come out of Node JS recently is the Async-Wait function. Async Wait makes the asynchronous code look like it's synchronous. It was only possible because of the re-introduction of promises into Node JS. Async-Await only works with a promise-returning feature.

    For now, the only way to prevent a callback is to use async-wait in Node JS. Let's use an example to understand this.

     
      
        const getrandomnumber = function(){
            return new Promise((resolve, reject)=>{
                setTimeout(() => {
                    resolve(Math.floor(Math.random() * 20));
                }, 1000);
            });
        }
    
        const addRandomNumber = async function(){
            try {
                const sum = await getrandomnumber() + await getrandomnumber();
                console.log(sum);
            } catch (error) {
                //handle error
                console.log(error);
            }
        }
    
        addRandomNumber();
      
    

    As you see above, we have a function that returns a random number after 1 sec. This function returns a promise. Use the await keyword, we tell JavaScript to wait for the response before going on. But this await keyword only works within functions that are declared to be async. If we declare a function to be async, we 're asking JavaScript to pause the execution before the result arrives when it comes to the await keyword.

    Now, in promises to handle the failure, we might directly chain the catch block. How would you do it in the above case?  Okay, we can only use the try-catch block. 

    Node JS is basically a single thread operation. This does not expose the developer to child threads and thread management methods. Technically, Node JS creates child threads for certain functions, such as asynchronous I / O, but they run behind the scenes and do not execute any JavaScript code or block the main event loop.

    If threading support is desired in a Node JS application, there are tools available to enable it, such as the ChildProcess module.

    ES6 Interview Questions and Answers

    Node JS is a single-threaded event-driven platform capable of non-blocking, asynchronous programming. These functions of Node JS make memory efficient. The event loop allows Node JS to perform non-blocking I / O operations despite the fact that JavaScript is single threaded. It is achieved by assigning tasks to the operating system whenever and wherever possible.

    Most operating systems are multi-threaded and hence can handle multiple operations executing in the background. When one of these operations is completed, the kernel tells Node JS and the respective callback assigned to that operation is added to the event queue which will eventually be executed. This will be explained further in detail later in this topic.

    Event Loop features:

    1. Event loop is an infinite loop that waits for tasks, executes them, and then sleeps before more tasks are provided.
    2. The event loop executes tasks from the event queue only when the call stack is empty, i.e. there is no ongoing task.
    3. The event loop makes it possible for us to use callbacks and commitments.
    4. The event loop will perform tasks starting from the oldest one.
     
      
        console.log("This is the first statement"); 
       
        setTimeout(function(){ 
            console.log("This is the second statement"); 
        }, 1000); 
           
        console.log("This is the third statement");  
    
        //output
        This is the first statement
        This is the third statement
        This is the second statement
    
      
    
    Explanation

    In the example above, the first console log statement is moved to the call list, and "This is the first statement" is logged in to the console, and the function is popped out of the list. First, the setTimeout is moved to the queue and the task is sent to the operating system and the timer is set to the task. This function is then popped out of the stack. Next, the third console log statement is moved to the call list, and "This is the third message" is logged in to the console, and the job is popped out of the list.

    When the timer set by the setTimeout function (in this case 1000 ms) is run out, the callback is sent to the event queue. The event loop on finding the call stack empty takes the task to the top of the event queue and sends it to the call stack. The callback function for the setTimeout function will run the instruction and "This is the second message" will be logged in to the console and the task will pop up from the stack.

    Working of the Event loop:

    As Node JS begins, it initializes the event loop, processes the input script that can render async API calls, schedule timers, and then begins processing the event loop. In the previous case , the initial input script consisted of console.log() statements and the setTimeout() function, which sets the timer.

    When using Node JS, a special library module called libuv is used to perform async operations. This library is also used, along with the back logic of Node, to handle a special thread pool called the libuv thread pool. This thread pool consists of four threads used to delegate operations that are too heavy for the event loop. I / O operations, Opening and closing connections, setTimeouts are examples of these operations.

    When a thread pool completes a task, a callback function is called that handles an error (if any) or some other operation. This callback function is sent to the queue of the event. When the call stack is empty, the event passes through the event queue and sends the call back to the call stack.

    SQL Interview Questions and Answers
    Phases of the Event loop
    1. Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in this phase.
    2. Pending Callbacks: I/O callbacks deferred to the next loop iteration are executed here.
    3. Idle, Prepare: Used internally only.
    4. Poll: Retrieves new I/O events.
    5. Check: It invokes setIntermediate() callbacks.
    6. Close Callbacks: It handles some close callbacks. Eg: socket.on(‘close’, …)

    Node js is a simplified model created because there have been several problems recorded in server side programming. Node.js uses different modules that are responsible for different core features. It runs on a number of operating systems, such as MacOS, Linux , and Windows. To optimize the use of both a single CPU and memory, we use non-blocking and asynchronous operations. They will use only one thread to satisfy all requests.

    Asynchronous:

    The word determines that it is not synchronous. The asynchronous architecture states that the sent message does not give an immediate reply just like we send the mail, but will not receive an immediate reply. It has no reliance or order. This increases the quality and performance of the program. The server stores the details and will be alerted when the action is taken.

    Non-Blocking:

    Immediately unblocking reactions with whatever data is available. In addition, it does not block any execution and continues to run as per requests. If a response can not be retrieved, the API will return immediately with an error. Non-blocking is often used for I / O ( input / output). Node.js is based on a non-blocking I / O pattern. There are few means of interacting that have been achieved by a non-blocking I / O. The callback function is to be called when the process is over. The nonblocking call uses the support of a javascript that provides a callback function.

    Asynchronous VS Non-Blocking

    You can point out the differences with these definitions of asynchronous and nonblocking. But few major differences are:

    1. Asynchronous does not respond immediately, while Nonblocking responds immediately if the data is available and if not, it simply returns an error.
    2. Asynchronous increases performance by completing the job quickly as the response can come later, whereas other tasks can be completed. Nonblocking does not obstruct any execution and, if the data is available, retrieves the information quickly.
    3. Asynchronous is the opposite of synchronous whereas non-blocking I / O is the opposite of blocking. They are both fairly similar, but they are also different because asynchronous is used with a wider range of operations, while non-blocking is mostly used with I / O.

    Tracing provides a mechanism for collecting tracking information generated by V8, Node Core and userspace code in a log file. Tracing can be allowed by passing the --trace-events-enabled flag when beginning the Node.js program.

    	
    		node --trace-events-enabled --trace-event-categories v8, node server.js
    	
    

    The set of categories for which traces are recorded can be specified using the --trace-event-categories flag followed by a list of comma-separated category names. The node and v8 categories are enabled by default.

    Running Node.js with tracing enabled will produce log files that can be opened in the chrome://tracing tab of Chrome.

    setTimeout

    It is simply like calling the function after delay has finished.  Once a function is called, it is not executed immediately, but is queued in such a way that it is executed after all the running and currently queued eventhandlers finish first. SetTimeout(,0) effectively implies that all existing functions in the existing queue are executed. There can be no assurances as to how long it will take.

    setImmediate

    It is similar in this regard, except that it does not use the function queue. Checks the queue of I / O event handlers. If all I / O events in the current snapshot are processed, the callback will be executed. It queues them immediately after the last I / O handler a bit like process.nextTick. It's quicker, then.

    Even (setTimeout,0) will be slow because the timer must be tested at least once before running. It can be twice as slow at times. Here's the comparison.

    	
    	
    		setTimeout(function() {
    		  console.log('setTimeout')
    		}, 0)
    
    		setImmediate(function() {
    		  console.log('setImmediate')
    		})
    	
    

    As you try to grasp the Node.js event loop, the process.nextTick() is an important part of it. Every time the event loop goes on a full trip, we call it a tick. When a function is transferred to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts:

    	
    	
    		process.nextTick(() => {
    		  //do something
    		})		
    	
    

    The event loop is busy processing the current function code. Once this operation finishes, the JS engine must run all the functions passed to nextTick during this process.

    That is the way we can tell the JS engine to process the function asynchronously (after the current function), but as soon as possible, not queue it. Calling setTimeout(() => {}, 0) would execute the function at the end of the next tick, much later than using nextTick() to prioritize the request and execute it just before the start of the next tick. Using nextTick() to make sure that the code is already executed in the next event loop iteration.

    21 React js Interview Questions and Answers

    There are two solutions to addressing unhandled exceptions in Node.js that are discussed below:

    1. Using try-catch block:

    We know that Node.js is a platform built on JavaScript runtime to easily create fast and scalable network applications. Being part of JavaScript, we know that the most important way to deal with the exception is to try and catch a block.

    	
    	
    		try {       
    		    // The synchronous code that 
    		    // we want to catch thrown 
    		    // errors on 
    		    var err = new Error('Hello') 
    		    throw err 
    		} catch (err) { 
    		      
    		    // Handle the error safely 
    		    console.log(err) 
    		} 	
    	
    

    2. Using Process:

    Good practice states that you will use the Process to handle the exception. A process is a global object that provides information on the current Node.js process. The process is a feature of the listener who often listens to events.

    Some process events are:
    1. Disconnect
    2. Exit
    3. Message
    4. Multiple Resolves
    5. Unhandled Exception
    6. Rejection Handled
    7. Uncaught Exception
    8. Warning

    The most effective and efficient solution is the use of the Process. If any uncaught or uncontrolled exception occurs in your code flow, the exception will be caught in the code shown below:

    	
    	
    		process.on('uncaughtException', function(err) {  
    		    // Handle the error safely 
    		    console.log(err) 
    		})  	
    	
    

    The above code should be able to handle any kind of unhandled exception that exists in Node.js.

    Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources.

    Node Js is supporting clustering to take full advantages of your cpu. If you are not not running it with cluster, then probably you are wasting your hardware capabilities.

    Clustering in Node.js allows you to create separate processes which can share same server port. For example, if we run one HTTP server on Port 3000, it is one Server running on Single thread on single core of processor. Code shown below allow you to cluster your application. This code is official code represented by Node.js.

    	
    	
    		var cluster = require('cluster');
    		var numCPUs = require('os').cpus().length;
    
    		if (cluster.isMaster) {
    		    // Fork workers.
    		    for (var i = 0; i < numCPUs; i++) {
    		        cluster.fork();
    		    }
    
    		    Object.keys(cluster.workers).forEach(function(id) {
    		        console.log("I am running with ID : " + cluster.workers[id].process.pid);
    		    });
    
    		    cluster.on('exit', function(worker, code, signal) {
    		        console.log('worker ' + worker.process.pid + ' died');
    		    });
    		} else {
    
    		    //Do further processing.
    		} 	
    	
    

    Node.js uses the Events Module to create and manage custom events. The EventEmitter class can be used to build and manage custom event modules.

    The syntax for importing the event module is given below:

    Syntax:
    	
    	
    		const EventEmitter = require('events');		
    	
    

    All EventEmitters emit a newListener event when new listeners are added and removeListener when current listeners are removed. It also provides one more option

    boolean captureRejections

    	
    	

    Default Value: false

    It automatically captures rejections.

    Listening events:

    before any event is emitted, the functions(callbacks) must be registered to listen to the events.

    Syntax:
    	
    	
    		eventEmitter.addListener(event, listener)
    		eventEmitter.on(event, listener)		
    	
    

    EventEmitter.on(event, listener) and eventEmitter.addListener(event, listener) are quite similar. At the end of the listener's sequence, it adds the listener to the specified event. Several calls to the same event and the listener can connect the listener multiple times and trigger multiple times. Both functions return the emitter, so that calls can be chained.

    Emitting Events:

    Each event is named event in nodejs. The event can be triggered by the emit(event, [arg1], [arg2], [...]) function. We may transfer an arbitrary set of arguments to the function of the listener.

    Syntax:
    	
    	
    		eventEmitter.emit(event, [arg1], [arg2], [...])	
    	
    
    Example
    	
    	
    		// Importing events 
    		const EventEmitter = require('events'); 
    
    		// Initializing event emitter instances 
    		var eventEmitter = new EventEmitter(); 
    
    		// Registering to myEvent 
    		eventEmitter.on('myEvent', (msg) => { 
    		console.log(msg); 
    		}); 
    
    		// Triggering myEvent 
    		eventEmitter.emit('myEvent', "First event"); 
    
    	
    

    Removing Listener:

    The eventEmitter.removeListener() takes two argument event and listener, and eliminates the listener from the listener array that is subscribed to that event. Although eventEmitter.removeAllListeners() removes all listeners from the array that are subscribed to the event.

    Syntax:
    	
    	
    		eventEmitter.removeListener(event, listener)
    		eventEmitter.removeAllListeners([event])
    	
    

    Special Events:

    All EventEmitter instances emit the event 'newListener' when new listeners are added and existing listeners 'removeListener' deleted.

    • Event: 'newListener'

      EventEmitter must emit its own 'new listener' event before the listener is added to its internal array of listeners. Listeners registered for the 'newListener' event will be transferred to the name of the event and a reference will be added to the listener. The 'newListener' event is triggered before the listener is added to the array.

      	
      	
      		eventEmitter.once( 'newListener', listener)
      		eventEmitter.on( 'newListener', listener)
      	
      
    • Event: 'removeListener'

      The 'removeListener' event is emitted after a listener is removed

      	
      	
      		eventEmitter.once( 'removeListener', listener)
      		eventEmitter.on( 'removeListener', listener)
      	
      
    • Event: 'error'

      If an error occurs inside the EventEmitter instance, the typical behavior is to emit a 'error' event. If the EventEmitter does not have at least one listener registered for the 'error' event, and the 'error' event is released, the error is thrown, the stack trace is written, and the Node.js process exits.

      	
      	
      		eventEmitter.on('error', listener)
      	
      
    Example:
    	
    	
    		// Importing events 
    		const EventEmitter = require('events'); 
    		  
    		// Initializing event emitter instances  
    		var eventEmitter = new EventEmitter(); 
    		  
    		// Register to error 
    		eventEmitter.on('error', (err) => { 
    		    console.error('Attention! There was an error'); 
    		}); 
    		  
    		// Register to newListener 
    		eventEmitter.on( 'newListener', (event, listener) => { 
    		    console.log(`The listener is added to ${event}`); 
    		}); 
    		  
    		// Register to removeListener 
    		eventEmitter.on( 'removeListener', (event, listener) => { 
    		    console.log(`The listener is removed from ${event}`); 
    		}); 
    		  
    		// Declaring listener Indiahires1 to myEvent1 
    		var Indiahires1  = (msg) => { 
    		    console.log("Message from Indiahires1: " + msg); 
    		}; 
    		  
    		// Declaring listener Indiahires2 to myEvent2 
    		var Indiahires2 = (msg) => { 
    		    console.log("Message from Indiahires2: " + msg); 
    		}; 
    		  
    		// Listening to myEvent with Indiahires1 and Indiahires2 
    		eventEmitter.on('myEvent', Indiahires1); 
    		eventEmitter.on('myEvent', Indiahires2); 
    		  
    		// Removing listener 
    		eventEmitter.off('myEvent', Indiahires1); 
    		  
    		// Triggering myEvent 
    		eventEmitter.emit('myEvent', 'Event occurred'); 
    		  
    		// Triggering error 
    		eventEmitter.emit('error', new Error('Attention!')); 
    	
    

    Reference: https://nodejs.org/api/events.html#events_class_eventemitter

    A stream is an abstract interface for streaming data in Node.js. The stream module provides an API for the implementation of the stream interface. There are a lot of stream objects supported by Node.js. For example, a request to an HTTP server and process.stdout are both stream instances. Streams may be readable, writeable, or both. All streams are EventEmitter instances.

    To access the stream module:

    	
    	
    		const stream = require('stream');
    	
    

    The stream module is useful to create new types of stream instances. Typically, it is not appropriate to use the stream module to access streams.

    Types of streams

    There are four fundamental stream types within Node js:

    • Writable:

      Streams to which data can be written (for example,fs.createWriteStream()).

    • Readable:

      Streams to which data can be written (for example,fs.createReadStream()).

    • Duplex:

      Streams that are both Readable and Writable (for example,net.Socket).

    • Transform:

      Duplex streams that can modify or transform the data as it is written and read (for example, zlib.createDeflate()

    In addition, this module contains the stream.pipeline(), stream.finished() and stream.Readable.from() utility functions.

    Every Stream type is an instance of EventEmitter and throws many events at different times. Many of the widely used cases , for example, are −

    1. data − This event is fired when there is data is available to read.

    2. end − This event is fired when there is no more data to read.

    3. error − This event is fired when there is any error receiving or writing data.

    4. finish − This event is fired when all the data has been flushed to underlying system.

    Reading from a Stream

    Create a js file named main.js with the following code −

    	
    	
    		var fs = require("fs");
    		var data = '';
    
    		// Create a readable stream
    		var readerStream = fs.createReadStream('input.txt');
    
    		// Set the encoding to be utf8. 
    		readerStream.setEncoding('UTF8');
    
    		// Handle stream events --> data, end, and error
    		readerStream.on('data', function(chunk) {
    		   data += chunk;
    		});
    
    		readerStream.on('end',function() {
    		   console.log(data);
    		});
    
    		readerStream.on('error', function(err) {
    		   console.log(err.stack);
    		});
    
    		console.log("Program Ended");		
    	
    

    Writing to a Stream

    Create a js file named main.js with the following code −

    	
    	
    		var fs = require("fs");
    		var data = 'Simply Easy Learning';
    
    		// Create a writable stream
    		var writerStream = fs.createWriteStream('output.txt');
    
    		// Write the data to stream with encoding to be utf8
    		writerStream.write(data,'UTF8');
    
    		// Mark the end of file
    		writerStream.end();
    
    		// Handle stream events --> finish, and error
    		writerStream.on('finish', function() {
    		   console.log("Write completed.");
    		});
    
    		writerStream.on('error', function(err) {
    		   console.log(err.stack);
    		});
    
    		console.log("Program Ended");	
    	
    

    Now open output.txt that has been created in your current directory; it should contain the following.

    Piping the Streams

    Piping is a mechanism that provides the output of one stream as input to another stream. Typically, it is used to get data from one stream and transfer the output of that stream to another source. There is no limit to pipe operations. Now we're going to demonstrate a pipe example to read from one file and write it to another file.

    Create a js file named main.js with the following code −

    	
    	
    		var fs = require("fs");
    
    		// Create a readable stream
    		var readerStream = fs.createReadStream('input.txt');
    
    		// Create a writable stream
    		var writerStream = fs.createWriteStream('output.txt');
    
    		// Pipe the read and write operations
    		// read input.txt and write data to output.txt
    		readerStream.pipe(writerStream);
    
    		console.log("Program Ended");		
    	
    

    Chaining the Streams

    Chaining is a mechanism to connecting the output of one stream to another stream and forming a chain of multiple stream operations. It is normally used for pipe operations. Now we're going to use pipe and chaining to first compress a file and then decompress the same one.

    	
    	
    		var fs = require("fs");
    		var zlib = require('zlib');
    
    		// Compress the file input.txt to input.txt.gz
    		fs.createReadStream('input.txt')
    		   .pipe(zlib.createGzip())
    		   .pipe(fs.createWriteStream('input.txt.gz'));
    		  
    		console.log("File Compressed.");	
    	
    

    Node JS core modules, as well as most community-published modules, follow a pattern where the first argument for every callback handler is an optional error object. If there is no error, the argument is null or undefined.

    Therefore, the typical callback handler could perform error handling as follows:

    	
    	
    		function callback(err, results) {
    		    // usually we'll check for the error before handling results
    		    if(err) {
    		        // handle error somehow and return
    		    }
    		    // no error, perform standard callback handling
    		}
    	
    

    Node.js is an open-source JavaScript running-time environment built on the Chrome JavaScript Engine(V8). Node.js is used to create fast and scalable applications and is an event oriented, non-blocking I / O model.

    REPL (RED, EVAL, PRINT, LOOP) is a programming environment close to Shell (Unix / Linux) and a command prompt. Node comes with the REPL system when it's built. The program communicates with the user via the output of the commands / expressions used. It is useful for writing and debugging codes. The function of REPL can be understood in its full form:

    • Read :

      It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.

    • Eval :

      The parsed JavaScript data structure is evaluated for the results.

    • Print :

      The result is printed after the evaluation.

    • Loop :

      Loops the input command. To come out of NODE REPL, press ctrl+c twice

    fs.createReadStream(); and fs.readFile(); both are asynchronous, right !!

    Well, aside from the fact that fs.createReadStream() explicitly returns a stream object, and fs.readFile() requires a callback function in the second statement, there's another big difference.

    Yes, they 're both asynchronous, but that doesn't change the fact that fs.readFile() doesn't send you any data unless the entire file has been buffered into memory. It is much less memory-efficient and slower when it comes to relaying data back via server responses. With fs.createReadStream(), you can directly pipe the stream object to the server response object, which ensures that your client will automatically start receiving data even if the file is 500 MB.

    Not only that, but you 're also enhancing memory capacity by working with a single chunk file at a time rather than all at once. This means that your memory only needs to buffer the contents of the file a few kilobytes at a time rather than all at once.

    Here are two snippets showing:

    	
    	
    		const fs = require('fs');
    		const http = require('http');
    
    		// using readFile()
    		http.createServer(function (req, res) {
    		    // let's pretend this is a huge 500MB zip file
    		    fs.readFile('some/file/path.zip', function (err, data) {
    		        // entire file must be buffered in memory to data, which could be very slow
    		        // entire chunk is sent at once, no streaming here
    		        res.write(data);
    		        res.end();
    		    });
    		});
    
    		// using createReadStream()
    		http.createServer(function (req, res) {
    		    // processes the large file in chunks
    		    // sending them to client as soon as they're ready
    		    fs.createReadStream('some/file/path.zip').pipe(res);
    		    // this is more memory-efficient and responsive
    		});		
    	
    

    Crypto is a module in Node.js that deals with an algorithm that performs data encryption and decryption. This is used for security purposes, such as user authentication, where the password is stored in an encrypted form in the Database.

    The Crypto module provides a set of classes such as hash, HMAC, cipher, decipher, sign, and verify. This class instance is used to create Encryption and Decryption. Node.js is unable to construct a class object using a new keyword.

    How to use?

    To use the crypto module in Node.js then first require crypto.

    	
    	
    		var crypto = require('crypto');
    	
    

    To get all Cipher algorithms that support crypto in a Node js run following command.

    	
    	
    		require("crypto").getCiphers()
    	
    
    Encryption

    The method of transforming readable text to an unreadable format called Encryption. Encryption is used in Node.js, then the following method is used.

    	
    	
    		const crypto = require('crypto');
    		const password ='crypto@123';
    		const cipher = crypto.createCipher('aes128', 'a password');
    		var encrypted = cipher.update(password, 'utf8', 'hex');
    		encrypted += cipher.final('hex');
    		console.log(encrypted);
    	
    

    Cipher is a class in which crypto.createCipher) (is a method that creates an instance of that class. The instance of that class is used to convert plain text into an unreadable format.

    In Example string ‘crypto@123’ is a plain password and using .update() and .final() method with ‘aes128’ algorithm to encrypt that plain password in coded format. i.e ‘6ac2b3b08ce481c8016ee2067ba44081’.

    Decryption

    The process of converting readable text to an unreadable format is called Decryption. The following method is used in Node.js to create Decryption.

    	
    	
    		const crypto = require('crypto');
    		const encrypt_password = '6ac2b3b08ce481c8016ee2067ba44081';
    		const decipher = crypto.createDecipher('aes128','a password');
    		var decrypted = decipher.update(encrypt_password,'hex', 'utf8');
    		decrypted += decipher.final('utf8');
    		console.log(decrypted);
    	
    

    Decipher is a class in which crypto.createDecipher() is a method that creates an instance of that class. The instance of that class is used to transform encrypted data into a human-readable format.

    In Example string '6ac2b3b08ce481c8016ee2067ba44081' is a encrypted password and using .update() and .final() method with ‘aes128’ algorithm to decrypt that encrypted password in readable format i.e 'crypto@123'

    The dns module that provides the underlying system name resolution and the DNS facility to look up. The DNS module is made up of an asynchronous network wrapper.

    The most widely used features of the DNS module are:

    • dns.lookup(adress, options, callback)

      The dns search method takes any website address as its first parameter and returns the corresponding first IPV4 or IPV6 record. The choice parameter can be an integer or an entity. If no options are provided, both IPV4 and IPV6 inputs are valid. The third parameter is the callback function.

    • dns.lookupservice(address, port, callback)

      This function converts any physical address, such as "www.indiahires.com," to a set of record types. Record types are defined by the second "rrbyte" parameter. The third form is the callback function.

    • dns.getServers()

      This feature returns an IP address string sequence, formatted according to rfc5952, which is currently designed for DNS resolution. If a custom port is used, a string will include a port section.

    • dns.setServers()

      This function sets the IP address and port of the servers to be used for DNS resolution. The dns.setServers() method can not be called while the DNS query is in progress.

    Callback is a function that is called when a task is completed, which helps prevent any kind of blockage, and a callback function enables another code to run in the meantime.

    Callback is called when the task is completed and is an asynchronous function equivalent. Using the Callback principle, Node.js can process a large number of requests without waiting for any function to return the result that makes Node.js highly scalable. For example, in Node.js, when a function begins reading the file, it immediately returns the control to the execution environment so that the next command can be executed. When the file I / O is done, the callback feature will be called to prevent blocking or waiting for File I / O.

    Example:

    Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file file1.txt with the following content:

    	
    	
    		var fs = require("fs");       
    		fs.readFile('file1.txt', function (ferr, filedata) {   
    		    if (ferr) return console.error(ferr);   
    		    console.log(filedata.toString());   
    		});  
    		console.log("End of Program execution"); 		
    	
    

    Explanation:

    The fs library is loaded to handle related file-system operations. The readFile() function is asynchronous and the control returns immediately to the next command in the program while the function keeps running in the background

  • Top 21 Essential Java Developer Interview Questions

    When you're a fresher and seriously planning for a Java Developer interview, you will also gain from the main Java Interview questions.

    In this post, we 're trying to ask you a particular collection of questions from which you can really take advantage of the resources you need to get hired for Java Developer positions.

    Cracking an interview to become a Java Developer is not an easy feat, but we're here to direct you through every step of the interview process.

    As part of your training, we 're providing you with Java Developer Interview Questions and Answers that will certainly help you secure your dream job and a competitive salary.

    Interview Questions and Answers for Java Developer Interview

    ArrayList and Vectors both implement the List interface and both use (dynamically resizable) arrays for their internal data structure, much like using a common array.

    Syntax:

    	
    		ArrayList<T> al = new ArrayList<T>();
    		Vector<T> v = new Vector<T>();
    	
    
    Major Differences between ArrayList and Vector:
    1. Synchronization:

      Vector is synchronized, which means that only one thread at a time can access the code, while arrayList is not synchronized, which means that several threads can operate on arrayList at the same time. For example, if one thread performs an add operation, another thread may perform a remove operation in a multi-threaded environment.

      If multiple threads access arrayList at the same time, then we need to synchronize the code block that modifies the list structurally or, alternatively, allow simple changes to the element. Structural modification means the addition or deletion of the item(s) from the list. Setting the value of an existing entity is not a structural change.

    2. Performance:

      ArrayList is faster because it is non-synchronized, while vector operations are slower because they are synchronized (thread-safe). If one thread is working on a vector, it has acquired a lock on it, which forces any other thread that wants to work on it to have to wait until the lock is released.

    3. Data Growth:

      ArrayList and Vector both grow and shrink dynamically to maintain optimal storage use – but the way they are resized is different. ArrayList increases the current array size by 50 percent if the number of elements exceeds its capacity, while the vector increases by 100 percent – essentially doubling the current array size.

    4. Traversal

      Vector can use both Enumeration and Iterator to pass through vector elements, while ArrayList can only use Iterator to pass through.

    5. Applications:

      Most of the time, programmers prefer ArrayList over Vector, because ArrayList can be explicitly synchronized using Collections.synchronizedList.

    How do you choose between ArrayList and Vector?
    1. The ArrayList is non-synchronized and not thread-safe, whereas the vectors are. Only one thread can call Vector methods at a time that is a slight overhead, but useful when safety is a concern. Therefore, in a single-threaded case, arrayList is an obvious choice, but in the case of multithreading, vectors are often preferable.
    2. If we don't know how much data we 're going to have, but know the rate at which it's going to grow, Vector has an advantage, because we can set the increment value in vectors.
    3. The ArrayList is both newer and faster. If we don't have any explicit requirements to use either of them, we use the ArrayList over the vector.
    Difference between ArrayList and LinkedList in Java

    ArrayList and LinkedList both implement the List interface and their methods and results are almost identical. Nevertheless, depending on the criteria, there are little variations between them, which make one better.

    1. Search:

      ArrayList search operation is quite fast compared to the LinkedList search operation. Get(int index) in the ArrayList gives the performance of O(1) while the LinkedList output is O(n).

      Reason: ArrayList maintains an index-based system for its elements, as it implicitly uses array data structure , which makes it faster to search for an element in the list. On the other hand, LinkedList implements a double-linked list that requires a crossover of all the elements to search for an element.

    2. Deletion:

      LinkedList delete operation gives O(1) performance while ArrayList gives variable performance: O(n) in the worst case (while removing the first element) and O(1) in the best case (while removing the last element).

      Conclusion: The deletion of the LinkedList element is faster than the ArrayList.

      Reason: Each element of LinkedList has two pointers (addresses) that point to the two neighboring elements in the list. Consequently, removal only requires a change in the location of the pointer in the two nearby nodes (elements) of the node that will be removed. While in ArrayList all the elements need to be moved to fill in the space created by the deleted element.

    3. Inserts Performance:

      LinkedList add method gives O(1) performance while ArrayList gives O(n) performance in the worst case. Reason is the same as explained for deletion.

    4. Memory Overhead:

      ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighboring nodes, so the memory consumption in LinkedList is relatively high.

    How do you choose between ArrayList and LinkedList?
    1. As explained above, inserting and removing operations provides good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Therefore, if there is a requirement for frequent addition and deletion in the application, then LinkedList is the best choice.
    2. Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so if less add and remove operations and more search operations are required, ArrayList would be your best bet.

    Difference between fail-fast and fail safe in Java

    Key Fail-Fast Fail-Safe
    Exception Any modifications to the array, such as adding , removing, and modifying the array during a thread, are iterating the collection, then Fail fast throwing the concurrent adjustment exception. The fail-safe collection doesn't throw exception.
    Type of collection ArrayList and hashmap collection are the examples of fail-fast iterator CopyOnWrite and concurrent modification are the examples of a fail-safe iterator
    Performance and Memory Instead, it's focusing on the actual album. So, this iterator doesn't need extra time and memory This works on the replica of the set instead of the real version. It's overhead in terms of time and memory
    Modifications Iterators do not make adjustments to the set when iterating. Fail-Safe iterators make adjustments to the set while iterating.

    Difference between throw and throws in Java

    There are a lot of variations between throwing and throwing keywords. Here is a list of variations between throws and throws:

    throw throws
    throw keyword is used to throw an exception explicitly. throws keyword is used to declare one or more exceptions, separated by commas.
    Only single exception is thrown by using throw. Multiple exceptions can be thrown by using throws.
    throw keyword is used within the method. throws keyword is used with the method signature.
    Syntax wise throw keyword is followed by the instance variable. Syntax wise throws keyword is followed by exception class names.
    Checked exception cannot be propagated using throw only.Unchecked exception can be propagated using throw. For the propagation checked exception must use throws keyword followed by specific exception class name.
    Java throw example
    	
    		void m(){  
    			throw new ArithmeticException("sorry");  
    		}  					
    	
    
    Java throws example
    	
    		void m() throws ArithmeticException{  
    			throw new ArithmeticException("sorry");  
    		}  					
    	
    
    	
    		void m()throws ArithmeticException{  
    			throw new ArithmeticException("sorry");  
    		} 
    	
    

    21 React js Interview Questions and Answers

    A wait() only makes sense when there is also a notify(), so it's always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:

    Semantically, you never just wait(). You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is

    	
    		if(!condition){
    		    wait();
    		}			
    	
    

    But the condition is set by a separate thread, so you need synchronization to get this job done correctly. A few more things are wrong with it, where just because your thread stops waiting doesn't mean that the condition you 're looking for is true:

    1. You can get spurious wake-ups (meaning that a thread will wake up from waiting without ever getting a notification)
    2. The condition can be set, but the third thread can make the condition false again when the waiting thread wakes up (and reacquires the monitor).

    When deal with these situations, what you really need is always some combination of the following:

    	
    		synchronized(lock){
    		    while(!condition){
    		        lock.wait();
    		    }
    		}		
    	
    

    Better yet, don't mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent packages.

    Within Java programming, for any occurrence of an exception, an exception object is created which holds all the details of the exception. The software must then check for its respective exception handler. When detected, the violation must be addressed or fixed, or the execution of the program must end.

    Java generates two types of exceptions

    1. Checked exception
    2. Unchecked exception

    Difference Between Checked and Unchecked Exceptions in Java

    Checked Exception Unchecked Exception
    Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
    The compiler checks a checked exception. The compiler does not check these types of exceptions.
    These types of exceptions can be handled at the time of compilation. These types of exceptions cannot be a catch or handle at the time of compilation, because they get generated by the mistakes in the program.
    They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the Exception class.
    Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and handle.
    Examples of Checked exceptions:
    1. File Not Found Exception
    2. No Such Field Exception
    3. Interrupted Exception
    4. No Such Method Exception
    5. Class Not Found Exception
    Examples of Unchecked Exceptions:
    1. No Such Element Exception
    2. Undeclared Throwable Exception
    3. Empty Stack Exception
    4. Arithmetic Exception
    5. Null Pointer Exception
    6. Array Index Out of Bounds Exception
    7. Security Exception

    Lambda expression is a new feature implemented in Java 8. The expression of the lambda is an anonymous function. A category that has no name and does not belong to any class. The definition of lambda expression was first implemented in the programming language of LISP.

    Java Lambda Expression Syntax

    To create a lambda expression, define the input parameters (if any) on the left side of the lambda operator->, and place the expression or sequence of the statements on the right side of the lambda operator. For example, the lambda expression (x, y)- > x + y specifies that the lambda expression takes two arguments, x and y, and returns the sum of those arguments.

    	
    		//Syntax of lambda expression
    		(parameter_list) -> {function_body}				
    	
    
    The lambda expression in Java has the following key parts:

    The Lambda expression only has a description of the body and parameter.

    1. No name-function is anonymous, so we don't care about the name.
    2. List of parameters
    3. Body – that's the key part of the body.
    4. No return type – the Java 8 compiler should be able to infer the return type by testing the code. You don't need to mention it directly.

    Where to use the Lambdas in Java

    You need to either build your own functional interface or use the predefined functional interface given by Java to use the lambda expression. The interface with a single abstract method is called a functional interface (or a single abstract method interface), e.g.: Runable, Callable, ActionListener, etc.

    Java Lambda expression Example

    By using Lambda expression:

    prior to Java 8 we used an anonymous inner class to implement the only abstract method of the functional interface.

    	
    		import java.awt.*;  
    		import java.awt.event.*;  
    		public class ButtonListenerOldWay {  
    		    public static void main(String[] args) {  
    		       Frame frame=new Frame("ActionListener Before Java8");  
    		    
    		       Button b=new Button("Click Here");  
    		       b.setBounds(50,100,80,50);  
    		  
    		       b.addActionListener(new ActionListener(){  
    		          public void actionPerformed(ActionEvent e){  
    		    	     System.out.println("Hello World!"); 
    		          }  
    		       });  
    		       frame.add(b);		    
    		       frame.setSize(200,200);  
    		       frame.setLayout(null);  
    		       frame.setVisible(true);   
    		    }  
    		}				
    	
    

    Java Lambda expression Example

    Without using Lambda expression:

    Instead of creating an anonymous inner entity, we might create a lambda expression like this:

    	
    		import java.awt.*;  
    		public class ButtonListenerNewWay {  
    		   public static void main(String[] args) {  
    		      Frame frame=new Frame("ActionListener java8");  
    		     
    		      Button b=new Button("Click Here");  
    		      b.setBounds(50,100,80,50); 
    		  
    		      b.addActionListener(e -> System.out.println("Hello World!")); 
    		      frame.add(b);
    		  
    		      frame.setSize(200,200);  
    		      frame.setLayout(null);  
    		      frame.setVisible(true);   
    		   }  
    		}				
    	
    

    Encapsulate:

    Encapsulate covers variables or any kind of specification that can be modified very frequently in a class to prevent others from directly accessing it. They must have access to this through getter and setter methods.

    Abstraction

    Abstraction is used to cover something in a higher degree (class, interface). Clients are using an abstract class(or interface) that doesn't matter who or what it was, they just need to know what it can do.

    Difference between Encapsulation and Abstraction

    Abstraction Encapsulation
    Abstraction is the process or method of gaining the information. While encapsulation is the process or method to contain the information.
    In abstraction, problems are solved at the design or interface level. While in encapsulation, problems are solved at the implementation level.
    Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
    We can implement abstraction using abstract class and interfaces. Whereas encapsulation can be implemented using by access modifier i.e. private, protected and public.
    In abstraction, implementation complexities are hidden using abstract classes and interfaces. While in encapsulation, the data is hidden using methods of getters and setters.
    The objects that help to perform abstraction are encapsulated. Whereas the objects that result in encapsulation need not be abstracted.

    Polymorphism is one of the main principles of the OOPS model. The concept of polymorphism is that it exists in a variety of different ways.

    What is Polymorphism?

    Polymorphism is the tendency to do various actions in different circumstances. Often polymorphism is dependent on the input parameters of the function. Polymorphism can also be present in the case of inheritance. The functions behave differently on the basis of the actual implementation.

    Polymorphism Real Life Example

    • It is one of the functions of a individual to write. When a person is faced with a pencil and a paper, he will write a few words on it. If a individual offers an oil painting and a coloring book, he will make a painting. Here, the method behaves differently on the basis of input arguments.
    • The delivery person shall deliver the items to the address in question. If he's a postman, he's going to deliver letters and packages to his house. If he's a Pizza delivery guy, he'll bring Pizza to you. Here, polymorphism in the distribution function is accomplished through various implementations.

    Polymorphism in Java

    Java supports polymorphism and it can be divided into two types.

    1. Compile Time Polymorphism: If the compiler is able to evaluate the actual function, it is called compile-time polymorphism. There are two types of compile-time polymorphisms.
      1. Method Overloading:

        When different functions in a class have the same name but a different signature, this is called overloading. The signature method includes the reasons for the name and process. So, overloaded methods have a number of arguments. The arguments can vary in number or form of argument. The form of return method is not part of the signature.

        Here's a simple example of Java overloading process.

        	
        		import java.io.File;
        		class Printer{
        			
        			void print(String message) {
        				// printing string message
        			}
        			
        			void print(String message, int count) {
        				// printing message count times
        			}
        			
        			boolean print(Object obj, File f) {
        				//printing object to file
        				return true;
        			}
        		}					
        	
        

        When you're looking for method overloading in the JDK modules, you'll find a lot of them in the String and Primitive Wrapper groups. For example, String valuesOf() methods, Integer parseInt() methods, etc.

      2. Operator Overloading

        Java does not require us to override operators. Nevertheless, the additional (+) operator is overloaded for the String objects. If the add-on operator uses string objects, it concatenates them and returns a new string object.

        	
        		jshell> 10 + 5
        		$1 ==> 15
        
        		jshell> 10.5 + 20.1
        		$2 ==> 30.6
        
        		jshell> "ABC" + "abc"
        		$3 ==> "ABCabc"
        
        		jshell> new Object() + new Object()
        		|  Error:
        		|  bad operand types for binary operator '+'
        		|    first type:  java.lang.Object
        		|    second type: java.lang.Object
        		|  new Object() + new Object()
        		|  ^-------------------------^
        
        		jshell>			
        	
        
    2. Runtime Polymorphism:

      Runtime polymorphism is accomplished by an over-the-counter process. When the superclass method is overridden in the subclass, it is considered an overridden method. In this case, the compiler will not be able to decide if the superclass or subclass form will be named. The method of resolution occurs at runtime based on the particular object type. That's why this is called runtime polymorphism. It's also called the Dynamic Dispatch Process.

      Here's an example of Java runtime polymorphism.

      	
      		package com.journaldev.examples;
      		import java.util.Random;
      
      		public class DeliveryBoy {
      			void deliver() {
      				System.out.println("Delivering Item");
      			}
      
      			public static void main(String[] args) {
      				DeliveryBoy db = getDeliveryBoy();
      				db.deliver();
      			}
      
      			private static DeliveryBoy getDeliveryBoy() {
      				Random rand = new Random();
      				int num = rand.nextInt(10);
      				return num % 2 == 0 ? new PizzaDeliveryBoy() : new Postman();
      			}
      		}
      
      		class PizzaDeliveryBoy extends DeliveryBoy {
      
      			@Override
      			void deliver() {
      				System.out.println("Delivering Pizza");
      			}
      		}
      
      		class Postman extends DeliveryBoy {
      			@Override
      			void deliver() {
      				System.out.println("Delivering Letters");
      			}
      		}		
      	
      

      The delivery() method is overridden in the PizzaDeliveryBoy and Postman sections. The compiler can not decide if PizzaDeliveryBoy or Postman will be returned to getDeliveryBoy). Therefore, the process of resolution is going to happen at runtime. If you run the program, the performance will differ between "Delivery Letters" and "Delivery Pizza."

    Simple example: Let's say you've got a Students table and a Lockers table. For SQL, the first table you enter in the join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

    Each student can be assigned to a locker, so there's a Locker Number column in the Student Row. More than one student may possibly be in a single locker, but particularly at the beginning of the school year, you may have some incoming students without lockers and some lockers who are not assigned to students.

    In this example , let's assume that you have 100 students, 70 of whom have lockers. You have a total of 50 lockers, 40 of which have at least 1 student, and 10 lockers have no student at all.

    Difference between Left, Right, Outer and Inner Joins?

    • INNER JOIN is similar to "showing all students with lockers to me." Students without lockers or lockers without students are absent. Returns to 70 rows
    • LEFT OUTER JOIN will be "to show me all the teachers, with their respective lockers, if they have one." It could be a general student list, or it could be used to classify students without a locker. Returns to 100 points
    • RIGHT OUTER JOIN would be "show me all lockers, and the students would be allocated to them if they had any." This may be used to classify lockers that are not assigned to students, or lockers that have too many students. Returns 80 rows (list of 70 students in 40 lockers plus 10 lockers without a student)
    • Complete OUTER JOIN will be dumb and probably not very useful. Something like "Show me all the students and all the lockers and fit them where you can" Returns 110 rows (all 100 students, including those without lockers, plus 10 lockers without students)
    • CROSS JOIN is still pretty dumb in this case. It doesn't use the related locker number field in the student table, so you essentially end up with a big list of all potential student-to-locker pairings, whether or not they actually exist

    TCS Possible Technical Interview Questions and Answers

    You must have seen public, private and secure keywords when running java programs, which are called access modifiers. The access modifier limits access to a class, constructor, data element, and process in another class. For Java, we have four access-modifiers:default, private, protected, public

    Default

    If we do not mention a change in access, it is called a default change in access. The scope of this amendment is limited to the kit only. This means that only those classes that are in this package can access this class if we have a class with the default access modifier in the package. No other class outside this package will be able to access this class. Similarly, if we have a default method or a data component in a module, it will not be available in another package module.

    Private

    The purpose of the private alteration is limited to the class only.

    1. Private Data Members and methods are only available inside the class.
    2. Class and Framework can not be considered private
    3. If a class has a private constructor, you can not create the object of that class from outside the class.

    Protected

    The covered data member and method can only be accessed by members of the same package and subclasses present in any package. You can also say that the protected Access Modifier is similar to the default Access Modifier, except that it has visibility in subclasses. Groups shall not be declared safe. This access change is generally used in a parent child relationship.

    Public

    Members, methods and classes that have been made public can be accessed from anywhere. This modifier does not impose any limits on access.

    The scope of access modifiers in tabular form

    ------------+-------+---------+--------------+--------------+--------
                | Class | Package | Subclass     | Subclass     |Outside|
                |       |         |(same package)|(diff package)|Class  |
    ————————————+———————+—————————+——————————----+—————————----—+————————
    public      | Yes   |  Yes    |    Yes       |    Yes       |   Yes |    
    ————————————+———————+—————————+—————————----—+—————————----—+————————
    protected   | Yes   |  Yes    |    Yes       |    Yes       |   No  |    
    ————————————+———————+—————————+————————----——+————————----——+————————
    default     | Yes   |  Yes    |    Yes       |    No        |   No  |
    ————————————+———————+—————————+————————----——+————————----——+————————
    private     | Yes   |  No     |    No        |    No        |   No  |
    ------------+-------+---------+--------------+--------------+--------

    The final keyword in Java can also be used for methods. The Java method with the final keyword is considered the final method and can not be overridden in the subclass. You will render the Java method final if you think it is complete and the behavior of the Java method will remain constant in subclasses.

    In general, final methods are faster than non-final methods because they are not expected to be resolved during run-time and bind to compile time.

    Here is an example of a final method in Java:

    	
    		class PersonalLoan{
    			public final String getName(){
    			    return "personal loan";
    			}
    		}
    		class CheapPersonalLoan extends PersonalLoan{
    		    @Override
    		    public final String getName(){
    		        return "cheap personal loan"; //compilation error: overridden method is final
    		    }
    		}		
    	
    

    RESTful web services are loosely coupled, lightweight web services that are especially well suited for building client APIs distributed around the internet. Representational State Transfer (REST) is an architectural form of client-server application based on the transfer of resource representations through requests and responses. Data and features are called tools in the REST architectural style and are accessed using Uniform Resource Identifiers (URIs), usually web links. Resources are expressed by documents and are accompanied by a set of simple, well-defined operations.

    For example, the REST resource may be the current weather conditions for a city. This resource can be represented by an XML document, an image file, or an HTML page. A client can retrieve a particular representation, change the resource by updating its data, or remove the resource entirely.

    The REST architectural style is designed to use stateless communication protocols, usually HTTP. In the REST architecture model, clients and servers share resource representation using a structured interface and protocol.

    The following principles encourage RESTful applications to be simple, lightweight and quick:

    1. Identification of resources by URI: The RESTful web service provides a collection of resources to define the purposes of contact with its clients. Assets are defined by URIs, which provide a global resource and service discovery address space.
    2. Uniform interface: The resources are managed using a fixed set of four development, reading, updating, deleting operations: PUT, GET, Publish, and DELETE. PUT generates a new resource that can be removed using DELETE. For certain representations, GET retrieves the current state of the property. POST is passing a new state to a tool.
    3. Self-descriptive messages: Documents are decoupled from their representation so that they can be viewed in a variety of formats, such as HTML , XML, plain text, PDF, JPEG, JSON, and other document formats. Resource metadata is accessible and used, for example, to manage caching, detect transmission errors, negotiate an correct representation format, and perform authentication or access control.
    4. State-of-the-art interactions across links: any contact with a resource is stateless; that is, requests for messages are self-contained. Stateful relations are based on the principle of clear transition of state. There are many strategies for state exchange, such as URI rewriting, cookies, and secret type fields. State may be inserted in answer messages to suggest true future states of interaction.

    Reflection is an API used to analyze or change the actions of methods, classes, interfaces at runtime.

    • The appropriate classes for reflection are given in the java.lang.reflect package.
    • Reflection provides us knowledge about the class to which the object belongs, as well as the methods of the class that can be implemented by using the object.
    • Through means of reflection, we can invoke methods at runtime irrespective of the access specifier used for them.

    Reflection can be used to get information about –

    1. Class The getClass() method is used to get the name of the class the object belongs to.
    2. Constructors The getConstructors() method is used to get the public constructors of the class the object belongs to.
    3. Methods The getMethods() function is used to get the public methods of the class to which the objects belong.
    Advantages of Using Reflection:
    • Extensibility Features: An application can use external, user-defined classes by creating extensibility object instances using their fully qualified names.
    • Debugging and testing tools: Debuggers use the reflection property to analyze classes for private members.
    Drawbacks:
    • Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts and should be avoided in code sections that are frequently referred to in performance-sensitive applications.
    • Exposure of internals: the reflective code removes abstractions and can therefore alter the behavior of the device upgrades.

    Association mapping is always the most difficult thing to execute correctly. In this section , we discuss some canonical cases one by one, beginning with unidirectional mapping and then bidirectional mapping. In all the instances, we will use Person and Email.

    Associations would be categorized by multiplicity and whether or not they correspond to the intermediate joint table.

    Null foreign keys are not known to be good practice in conventional data modeling, so our examples do not use null foreign keys. It is not a prerequisite of Hibernate, and mappings will work if you remove the nullity constraints.

    1. one to one

      A one-to-one partnership on a joint table is probable, but highly rare.

      	
      		<class name="Person">
      		    <id name="id" column="personId">
      		        <generator class="native"/>
      		    </id>
      		    <join table="PersonAddress" 
      		        optional="true">
      		        <key column="personId" 
      		            unique="true"/>
      		        <many-to-one name="address"
      		            column="addressId" 
      		            not-null="true"
      		            unique="true"/>
      		    </join>
      		</class>
      
      		<class name="Address">
      		    <id name="id" column="addressId">
      		        <generator class="native"/>
      		    </id>
      		</class>	
      
      
      		create table Person ( personId bigint not null primary key )
      		create table PersonAddress ( personId bigint not null primary key, addressId bigint not null unique )
      		create table Address ( addressId bigint not null primary key )	
      	
      
    2. one to many

      The best choice is a one-to-many one-to-many partnership on a joint table. Specifying unique="true, "switches the multiplicity from many to many to one-to-many.

      	
      		<class name="Person">
      		    <id name="id" column="personId">
      		        <generator class="native"/>
      		    </id>
      		    <set name="addresses" table="PersonAddress">
      		        <key column="personId"/>
      		        <many-to-many column="addressId"
      		            unique="true"
      		            class="Address"/>
      		    </set>
      		</class>
      
      		<class name="Address">
      		    <id name="id" column="addressId">
      		        <generator class="native"/>
      		    </id>
      		</class>		
      
      
      		create table Person ( personId bigint not null primary key )
      		create table PersonAddress ( personId not null, addressId bigint not null primary key )
      		create table Address ( addressId bigint not null primary key )		
      	
      
    3. many to one

      A many-to-one unidirectional association on a joint table is common when an association is optional. For instance:

      	
      		<class name="Person">
      		    <id name="id" column="personId">
      		        <generator class="native"/>
      		    </id>
      		    <join table="PersonAddress" 
      		        optional="true">
      		        <key column="personId" unique="true"/>
      		        <many-to-one name="address"
      		            column="addressId" 
      		            not-null="true"/>
      		    </join>
      		</class>
      
      		<class name="Address">
      		    <id name="id" column="addressId">
      		        <generator class="native"/>
      		    </id>
      		</class>		
      
      
      		create table Person ( personId bigint not null primary key )
      		create table PersonAddress ( personId bigint not null primary key, addressId bigint not null )
      		create table Address ( addressId bigint not null primary key )		
      	
      
    4. many to many

      Finally, here is an example of a unidirectional many-to-many association.

      	
      		<class name="Person">
      		    <id name="id" column="personId">
      		        <generator class="native"/>
      		    </id>
      		    <set name="addresses" table="PersonAddress">
      		        <key column="personId"/>
      		        <many-to-many column="addressId"
      		            class="Address"/>
      		    </set>
      		</class>
      
      		<class name="Address">
      		    <id name="id" column="addressId">
      		        <generator class="native"/>
      		    </id>
      		</class>	
      
      
      		create table Person ( personId bigint not null primary key )
      		create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) )
      		create table Address ( addressId bigint not null primary key )	
      	
      

    Selenium-RC operated the same way for each browser enabled. It inserted the JavaScript functions into the browser when the tab was loaded and then used the JavaScript to control the AUT in the tab. Selenium WebDriver plays the same function as Selenium-RC and implements the original 1.x bindings and contains the WebDriver API. It applies to both the language bindings and the implementations of the individual browser-control code. This is usually referred to as a Webdriver. In short, WebDriver is a remote control interface that enables user agents to be introspected and managed. WebDriver offers a forum and language-neutral wire protocol as a medium for out-of-process programs to remotely control the actions of web browsers.

    Key points of WebDriver
    1. WebDriver is equipped with a simpler and more succinct programming interface, along with some limitations in the Selenium-RC API.
    2. WebDriver is a lightweight object-oriented API similar to Selenium1.0.
    3. It drives the browser even more efficiently and overcomes the shortcomings of Selenium 1.x that have plagued our usable test coverage, such as uploading or installing files, pop-ups and dialogs.
    4. WebDriver overcomes the limitation of the Single Host Origin Policy of Selenium RC.

    ClassNotFoundException and NoClassDefFoundError both occur when the class is not found during runtime. They're connected to the Java classpath.

    ClassNotFoundException

    ClassNotFoundException occurs when you attempt to load a class at runtime using either Class.forName) (or loadClass) (methods, and the requested classes are not found in the classpath. Most of the time this exception happens when you attempt to run an application without updating the JAR file classpath. This exception is a verified exception originating from the class java.lang. Exception and you need to have specific handling for it.

    An exception often happens when you have two file loaders, and when a ClassLoader attempts to access a file that is loaded by another classloader in Java. You must be wondering what the Java classloader actually is. Java ClassLoader is a part of the Java Runtime Framework that dynamically loads Java classes into JVM(Java Virtual Machine). Because of classloaders, the Java Runtime System does not need to learn about the module and file system.

    	
    		// Java program to illustrate 
    		// ClassNotFoundException 
    		public class Example { 
    		      
    		    public static void main(String args[]) { 
    		        try 
    		        { 
    		            Class.forName("India Hires"); 
    		        } 
    		        catch (ClassNotFoundException ex) 
    		        { 
    		            ex.printStackTrace(); 
    		        } 
    		    } 
    		} 
    	
    
    NoClassDefFoundError

    NoClassDefFoundError occurs when the class was present during compile time and the program was compiled and successfully connected, but the class was not present during runtime. This is an error that is derived from LinkageError. Linkage error occurs when a class has some dependency on another class, and the latter class changes after the previous class has been compiled. NoClassFoundError is the product of implicit class loading by calling a method or accessing a variable from that object. This error is more difficult to diagnose and to find the explanation why this error occurred. So in this case, you should always test the classes that depend on the class.

    	
    		// Java program to illustrate 
    		// NoClassDefFoundError 
    		class Products  
    		{ 
    		    void getProduct() 
    		    { 
    		        System.out.println("India Hires!"); 
    		    } 
    		} 
    		  
    		class ProductInfo { 
    		    public static void main(String args[])  
    		    { 
    		        Products products = new products(); 
    		        products.getProduct(); 
    		    } 
    		} 
    	
    

    Above program will be successfully compiled and generate two classes Products.class and ProductInfo.class. Now remove Products.class file and run ProductInfo.class. At Java runtime NoClassDefFoundError will be thrown.

    ClassNotFoundException Vs NoClassDefFoundError

    1. As the name suggests, ClassNotFoundException is an exception, while NoClassDefFoundError is an error.
    2. ClassNotFoundException occurs when classpath is not modified with the correct JAR files while error occurs when the required class description is not present at runtime.

    First and foremost-all spring beans are managed-they "live" inside a container, called the "application context."

    Second, every application has an entry point in that context. Web applications have a server, JSF uses a el-resolver, etc. Often, there is a position where the program context is bootstrapped and all beans are autowired. It can be a startup listener in web applications.

    Autowiring occurs by placing an instance of one bean in the desired field in an instance of another bean. Both classes should be beans, i.e. they should be specified to live in the sense of the application.

    What is "working" in the sense of the application? This means that the environment must instantiate the objects, not you. I.e.-You never create a new UserServiceImpl()-the container finds will injection point and sets an instance there.

    In your controllers, you just have the following:

    	
    		@Controller // Defines that this class is a spring bean
    		@RequestMapping("/users")
    		public class SomeController {
    
    		    // Tells the application context to inject an instance of UserService here
    		    @Autowired
    		    private UserService userService;
    
    		    @RequestMapping("/login")
    		    public void login(@RequestParam("username") String username,
    		           @RequestParam("password") String password) {
    
    		        // The UserServiceImpl is already injected and you can use it
    		        userService.login(username, password);
    
    		    }
    		}
    	
    
    Key notes
    1. In your applicationContext.xml you can allow <context: component-scan> so that classes are scanned for annotations such as @Controller, @Service, etc.
    2. The entry point for the Spring-MVC code is the DispatcherServlet, but it is hidden from you, and thus the actual contact and bootstrapping of the application context takes place behind the scenes.
    3. UserServiceImpl can also be known as bean-either by using <bean id=".." class=".."> or by using the @Service annotation. Because it will be the only UserService provider, it will be inserted.
    4. Including the @Autowired tag, Sp
  • 21 React js Interview Questions and Answers

    React js Interview Questions and Answers for experienced software developer

    If you're an aspiring front end developer and are getting ready for interviews, then this blog is for you. This blog on Top 21 Questions for React Interviews is the perfect guide for you to learn all the concepts necessary to clear an interview with React. But before we continue with the questions of the reaction interview, let's take a quick look at the demand and status of React on the market.

    The JavaScript tools are slowly and steadily firming their roots on the marketplace and the demand for React certification is exponentially increasing. It is becoming increasingly difficult to choose the appropriate technologies to create an application or website. React is considered by others to be the fastest-growing Javascript framework.

    Creating React Components the ES5

              	
    	
    	var Comments = React.createClass({
    	    displayName: 'Comments',
    
    	    getInitialState: function(){
    	        return {comments: []}
    	    },
    
    	    getDefaultProps: function(){
    	        return {some_object: {a:1, b:2, c:3}}
    	    },
    
    	    _handleClick: function(){
    	        alert('hello world!')
    	    },
    
    	    render: function(){
    	        return <div>
    	            There are {this.state.comments.length} comments
    	            <button onClick={this._handleClick}>click me!</button>
    	        </div>
    	    }
    	})
    
    

    This Comments Component can now be rendered either within another React Object, or directly in ReactDOM.render() call

    ReactDOM.render(, document.querySelector('.app'))

    ES5 Components have certain unique qualities which we will note

    1. Just like the example above, create the getInitialState() function on the Component to set the state to an initial value. When made, what it returns will be the initial state of a Variable.
    2. Alternatively, with the getDefaultProps() method on the ES5 version you can set the default props for the item having a certain value.
    3. The displayName is used with React to test and record errors. If you use JSX, the displayName will be filled out automatically.
    4. For some, denoting a custom method added to a React Component by prefixing it with an underscore, hence handleClick is common practice. handleClick shall be passed as the onClick callback button in the above code. In React's ES6 API we can't do this so easily, because the ES5 version has autobinding, but the ES6 does not. Let's take a look at what delivers autobinding:
    Auto-binding

    Consider the following example

              	
    	
    		var indiaData = {
    		    name: 'India Hires',
    		    speak: function(){ console.log(this.name) }
    		}
    
    		window.addEventListener('keyup', indiaData.speak)
    	
    

    Invoking indiaData.speak() will log "India Hires" in the console, but pressing a key will log undefined, as the callback context is the global entity. The global object of the user-window-is this inside the indiaData() function, so that this.name is the undefined window.name, which is undefined

    React in ES5 automatically does autobinding, effectively doing the following:
              	
    	
    		window.addEventListener('keyup', indiaData.speak.bind(indiaData));
    	
    

    Autobinding automatically binds our functions to the instance of the React Component so that the render() smoothly works by passing the function by reference. The ES6 way of creating react components works a little differently and favors the ES6 class ... Spreads out ... Syntax, and no autobonding function:

    	
    	class Comments extends React.Component {
    	    constructor(props){
    	        super(props)
    	        this.state = {comments: []}
    	    }
    
    	    _handleClick(){
    	        alert('hello world!')
    	    }
    
    	    render(){
    	        return <div>
    	            There are {this.state.comments.length} comments
    	            <button onClick={() => this._handleClick}>click me!</button>
    	        </div>
    	    }
    	}
    	Comments.defaultProps = {a:1, b:2, c:3}
    	Comments.displayName = 'Comments'
    	
    

    Notice that in ES6, we have a constructor() that we use to set the initial state, We can add default props and a display name as properties of the new class created, and The render() method, which works as normal, but we’ve had to alter how we pass in the callback function. This current approach (<button onClick={() => this._handleClick}>click me!</button>) will create a new function each time the component is re-rendered; so if it becomes a performance bottleneck, you can always bind manually and store the callback:

    	
    	class Comments extends React.Component {
    		constructor(...args) {
    			super(...args);
    			this.state = { toggledOn: false };
    			this._handleClick = this._handleClick.bind(this);
    		}
    
    		_handleClick() {
    			this.setState(prevState => ({ toggledOn: !prevState.toggledOn });
    		}
    
    		render() {
    			return <button onClick={this._handleClick}> { this.state.toggledOn ? 'ON' : 'OFF' } </button>
    		}
    	}
    	
    

    React uses Virtual DOM to update the real DOM which makes it efficient and faster. The browser follows the HTML instructions to construct the Document Object Model or DOM. All the elements in the HTML document become DOM elements when the browser loads HTML and renders the user interface.

    DOM is a hierarchy of elements starting with the root element.

    How Does Virtual DOM Works

    Virtual DOM is nothing but the javascript object representation of real DOM. Updating javascript objects is easier and faster when compared with updating the real DOM.

    SQL Interview Questions and Answers

    Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.

    • Mounting – Birth of your component
    • Update – Growth of your component
    • Unmount – Death of your component

    Common React Lifecycle Methods

    Render()

    The render() method is the most used lifecycle method. This is the only required method within a class component in React. it handles the rendering of your component to the UI. It happens during the mounting and updating of your component.

      	
    		class Hello extends Component{
    		   render(){
    		      return <div>Hello {this.props.name}</div>
    		   }
    		}
    	
    

    Render method is a pure function and pure functions always return the same output when the same inputs are passed. This means that we can not setState() within the render();

    Mounting

    Constructor

    The first thing that gets called is our component constructor if our component is a class component. The constructor gets called with the component props. We must call super and pass in the props. We can then initialize our state, setting the default values and use the constructor for function binding as well.

      	
    		class MyComponent extends Component {
    		  constructor(props) {
    		    super(props);
    		    this.state = {
    		      counter: props.initialCounterValue,
    		    };
    		  }
    		}
    
    	
    

    Note that using a constructor is optional, and you can initialize your state like so if your Babel setup has support for class fields:

    getDerivedStateFromProps()

    When mounting, getDerivedStateFromProps is the last method called before rendering. We can use it to set state according to the initial props. This will be a safer alternative to the componentWillReceiveProps() method. It is called just before calling the render() method. This is a static function that does not have access to “this“. This method returns an object to update state in response to prop changes. It can return a null if there is no change to state.

      	
    		static getDerivedStateFromProps(props, state) {
    		    if (props.currentRow !== state.lastRow) {
    		      return {
    		        isScrollingDown: props.currentRow > state.lastRow,
    		        lastRow: props.currentRow,
    		      };
    		    }
    		    // Return null to indicate no change to state.
    		    return null;
    		  }
    	
    

    Note that we could have placed this code in the constructor. The advantage of getDerivedStateFromProps is that it is only meant for setting state, whereas a constructor has multiple uses. getDerivedStateFromProps is also called both before mount and before updating, as we’ll see in a bit.

    componentDidMount()

    componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls, if you need to load data from a remote endpoint. Calling the setState() here will update state and cause another rendering but it will happen before the browser updates the UI. This is to ensure that the user will not see any UI updates with the double rendering.

      	
    		componentDidMount() {
    		    this.bricks = initializeGrid(this.grid.current);
    		    layoutInitialGrid(this.bricks)
    		    this.interval = setInterval(() => {
    		      this.addBlocks();
    		    }, 2000);
    		  }
    
    	
    

    Updating

    getDerivedStateFromProps()

    If we need to update our state based on a prop changing, we can do it here by returning a new state object. Here’s some examples:

    1. Resetting a video or audio element when the source changes
    2. Refreshing a UI element with updates from the server
    3. closing an accordion element when the contents change
      	
    		static getDerivedStateFromProps(props, state) {
    		  if (state.blocks.length > 0) {
    		    return {};
    		  }
    		  return { blocks: createBlocks(props.numberOfBlocks) };
    		}
    	
    

    (One last point about static methods like getDerivedStateFromProps: We don’t have access to the component via this. So we couldn’t access our grid ref, for example.)

    shouldComponentUpdate()

    This lifecycle method is called whenever there is an update to the props or state and it returns a boolean value true by default. We can return false if you don’t want to re render the DOM for this change. This is really useful to improve the performance of the app. Anytime setState() is called, the component re-renders by default.

      	
    		shouldComponentUpdate(nextProps, nextState) {
    		 return this.props.title !== nextProps.title || 
    		  this.state.input !== nextState.input 
    		}
    	
    
    getSnapshotBeforeUpdate()

    This will be a safer alternative to the previous lifecycle method componentWillUpdate(). It is called right before the DOM is updated. The value that is returned from getSnapshotBeforeUpdate() is passed on to componentDidUpdate().

      	
    		getSnapshotBeforeUpdate(prevProps, prevState) {  
    		  if (prevState.blocks.length < this.state.blocks.length) {
    		      const grid = this.grid.current;
    		      const isAtBottomOfGrid =
    		        window.innerHeight + window.pageYOffset === grid.scrollHeight;
    		      return { isAtBottomOfGrid };
    		    }
    		    return null;
    		  }
    	
    

    Most Common Use Case: Taking a look at some attribute of the current DOM, and passing that value on to componentDidUpdate.

    componentDidUpdate()

    This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

    You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop

      	
    		componentDidUpdate(prevProps) {
    			 //Typical usage, don't forget to compare the props
    			 if (this.props.userName !== prevProps.userName) {
    			   this.fetchData(this.props.userName);
    			 }
    		  }
    	
    

    Unmounting

    componentWillUnmount()

    This is invoked just before the component is unmounted and destroyed. We cannot modify the component state in componentWillUnmount lifecycle. This component will never be re-rendered and because of that we cannot call setState() during this lifecycle method.

      	
    		componentWillUnmount() {
    		 window.removeEventListener('resize', this.resizeListener)
    		}
    	
    

    Errors

    getDerivedStateFromError()

    This lifecycle method is used in ErrorBoundary class. Actually, any class becomes ErrorBoundary if it uses this lifecycle method. This is used to render the fallback UI if something goes wrong in the component tree instead of displaying some weird errors on the screen.

      	
    		static getDerivedStateFromError(error) {
    		  return { hasError: true };
    		}
    	
    
    componentDidCatch()

    This lifecycle method is used in ErrorBoundary class. Actually, any class becomes ErrorBoundary if it uses this lifecycle method. This is used to log the errors if something goes wrong in the component tree.

      	
    		componentDidCatch(error, info) {
    		  sendErrorLog(error, info);
    		}
    	
    

    Note that componentDidCatch only works for errors in the render/lifecycle methods. If our app throws an error in a click handler, it will not be caught.

      	
    		class ErrorBoundary extends Component {
    		  state = { errorMessage: null };
    		  static getDerivedStateFromError(error) {
    		    return { errorMessage: error.message };
    		  }
    		  componentDidCatch(error, info) {
    		    console.log(error, info);
    		  }
    		  render() {
    		    if (this.state.errorMessage) {
    		      return <p>Oops! {this.state.errorMessage}</p>;
    		    }
    		    return this.props.children;
    		  }
    		}
    	
    

    Other lifecycle methods

    componentWillMount()

    This lifecycle method is called, as the component enters the DOM and we have the last chance to edit the state so that it will be displayed on the screen. It occurs only once.

    componentWillReceiveProps()

    Whenever there is a change in the props, the component enters into the update phase. This lifecycle method is called to receive the props and we can check the previous props and current props here and we can update the state depending on the result.

    componentWillUpdate()

    Whenever there is a change in the props or state, this lifecycle method is called. We can have a chance to access the state and edit it before rendering the UI.

    component Lifecycle Methods

    TCS Possible Technical Interview Questions and Answers

    The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events. Props (short for properties) are a Component’s configuration. Props are how components talk to each other. They are received from above component and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data — callback functions may be passed in as props.

    There is also the case that we can have default props so that props are set even if a parent component doesn’t pass props down.

    	          	
    		class Search extends Component{
    			constructor(props){
    				super(props);
    				this.state = { term: ''}
    			}
    		   	render(){
    		   		return(
    			   		<div>
    			   			<input value={this.state.term} onChange={e => this.onInput(e.target.value)} />
    			   		</div>
    		   		);
    		   	}
    
    		   	onInput(search){
    		   		this.setState({search});
    		   		this.props.onSearchTermChange(search);
    			}
    		}
    	
    

    Props and State do similar things but are used in different ways. The majority of our components will probably be stateless. Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed. The state is used for mutable data or data that will change. This is particularly useful for user input.

    Higher order components are the components which take a component as an argument and produces another component. Array.map, Array.filter and Array.reduce are the higher order functions

    Exp:
    	
    		const numbers = [10,20,40,50,60,70,80];
    		const out1 = numbers.map(num => num * 100);
    		console.log(out1);
    
    		const isPassed = marks=> marks > 80; // function
    		const message = msg => "The student  is "+ msg; // function
    		function isStudentPassed(marks, isPassed, message) {
    		    const returnMessage = isPassed(marks)?message("passed"):message("failed");
    		    return returnMessage;
    		}
    		// passing functions as an arguments
    		console.log(isStudentPassed(85, isPassed , message))
    		// The student is passed
    	
    
    Exp:
      	
    		DOM.render(
    	    <LazyLoad>
    	        <img src="https://media.giphy.com/media/HhvUpQhBWMtwc/200.gif"/>
    	        <img src="https://media2.giphy.com/media/3oEduUDvycvu3GYkdG/200w.gif"/>
    	        <img src="https://media0.giphy.com/media/142UITjG5GjIRi/200w.gif" />
    	    </LazyLoad>, document.body)
    	
    
    Creating an HOC means handling this.props.children in the Component’s code:
      	
    		class LazyLoad extends Component {
    		    constructor(p){
    		        super(p)
    		        this.state = { loaded:0 }
    		        this._scroll = this._scroll.bind(this)
    		    }
    		    _scroll(){
    		        let el = DOM.findDOMNode(this)
    		        let {top} = el.getBoundingClientRect()
    		        let viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
    		        if(top < (viewportHeight + this.props.top)) {
    		            window.removeEventListener('scroll', this._scroll)
    		            this.setState({loaded:1})
    		        }
    		    }
    		    componentDidMount(){
    		        window.addEventListener('scroll', this._trackYPosition)
    		        this._scroll()
    		    }
    		    componentWillUnmount(){
    		        window.removeEventListener('scroll', this._trackYPosition)
    		    }
    		    render(){
    		        let {children} = this.props,
    		            {loaded} = this.state
    		        return <div> {loaded && children} </div>
    		    }
    		}
    
    		LazyLoad.defaultProps = {
    		    top: 100
    		}
    
    	
    
    	
    		const hoc = (WrappedComponent) => (props) => {
    		  return (
    		    <div>
    		      <WrappedComponent {...props}>
    		        {props.children.toUpperCase()}
    		      </WrappedComponent>
    		    </div>
    		  )
    		}
    
    		const Username = (props) => (
    		  <div>{props.children}</div>
    		)
    
    		const UpperCaseUsername = hoc(Username)
    
    		const App = () => (
    		  <div>
    		    <UpperCaseUsername>Kingsley</UpperCaseUsername>
    		  </div>
    		);
    	
    

    Of your application, lists are an important feature. Growing application is expected to use the lists in every way. A list of tasks like a calendar app, a list of pictures like Instagram, a list of shopping cart items, and much more could be available. There are numerous case applications. Lists can be heavy performance in an application. Imagine an app with an enormous list of videos or photos and scroll thousands more. The performance of the app could take a toll.

    As performance is an important aspect, it is necessary to ensure the optimal performance when using lists.

    Do you know that in React, each list element needs a unique key while using lists? Let's learn more about React 's lists and keys, and how to implement it in the correct way.

    Exp:
    	
    		class List extends Component {
    		    constructor(p){
    		        super(p)
    		        this.state = {
    		            items: Array(5).fill(1).map((x,i) => ({id:i}))
    		        }
    		    }
    
    		    componentDidMount(){
    		        const random = (a,b) => Math.random() < .5 ? -1 : 1
    
    		        setInterval(() => {
    		            this.setState({
    		                items: this.state.items.sort(random)
    		            })
    		        }, 20)
    		    }
    
    		    render() {
    		        let {items} = this.state
    		        return <ul>
    		            	{items.map(item => <li key={item.id}>{item.id}</li>)}
    		        </ul>
    		    }
    		}
    		DOM.render(<List />, document.body)
    	
    

    The setInterval() occurring on mount reorders the items array in this.state every 20ms. Computationally, if React is reordering the items in the state, then it would manipulate the DOM elements themselves instead of “dragging” them around between positions in the <ul>.

    It is worth noting here that if you render a homogenous array of children – such as the <li>'s above – React will actually console.warn() you of the potential issue, giving you a stack trace and line number to debug from. You won’t have to worry about React quietly breaking.

    Can I just use indexes as keys? — Only under some exceptions

    Using Index as a key is an anti-pattern. You may wonder, why don’t we just use indexes as keys when looping through an array. Although, many developers have done that in their code it is not necessarily ideal. React recommends that you do not use indexes as keys since it could impact performance negatively and could lead to some unstable component behavior.

    Exp:
    	
    		const todoItems = todos.map((todo, index) =>
    		  // Only do this if items have no stable IDs
    		  <li key={index}>
    		    {todo.text}
    		  </li>
    		);
    	
    

    In the above example you can see that we loop through the todos and assign the index of each item as the key. For some use cases which we will see below, this is acceptable. Reordering a list, or adding and removing items from a list, when indexes are used as keys can cause problems with the component state. If the key is an index it changes to reorder an item. The component state can, therefore, be mixed up and the old key can be used for a different instance of the component.

    Hence avoid this practice, and ensure that unique ids are created to be assigned as the key. There are some situations when it might be acceptable to assign the index as a key.

    What are some exceptions where use of index as key is safe?
    1. If your list is static and will not change.
    2. The list will never be re-ordered.
    3. The list will not be filtered (adding/removing items from the list).
    4. There are no ids for the items in the list.

    Note: Using index as a key can lead to potential unexpected behaviour within the component.

    Keys must be Special, but only among their siblings

    It's useful to keep in mind that although a key needs to be unique for each item, this rule applies only within an array. In other words, every item within an array needs to have a unique key, but it doesn't need to be unique globally. The same key may be used for a variety of other unrelated components and lists.

    Keys are not automatically passed onto the component as a prop

    In the example below, you can see that I specifically transfer the item.id which is the key to the component as another prop I d). This is because React doesn't pass the key automatically like a prop. If you wanted to use the key for some computation, you 'd have to pass it as another prop as we did in this instance.

    Refs is a feature that React provides to access the DOM element and the reaction element that you might have generated on your own. They are used in cases where we want to adjust a child's component value, without using props and all. They also offer us good flexibility, since with them we can use callbacks.

    Exp:
    	
    		// using refs 
    		class App extends React.Component { 
    		 constructor(){ 
    		  super(); 
    		  this.state = { sayings: ""}; 
    		 } 
    		 update(e){ 
    		  this.setState({ sayings: this.refs.anything.value}); 
    		 } 
    		 render(){ 
    		  return ( 
    		   <div>
    		   		India Hires Says:- <input type="text" ref="anything" onChange = {this.update.bind(this)}/> 
    			   	<p>					   
    				   <em>{this.state.sayings}</em> 
    				</p>
    			</div> 
    		  ); 
    		 } 
    		} 
    		 ReactDOM.render(< App />, document.getElementById('root'));
    	
    

    In the above we make use of refs provided by React, they can also be used to add callback functions inside them which is helpful in many cases.

    When to use refs
    1. Helpful when using third party libraries.
    2. Helpful in animations.
    When not to use refs
    1. Should not be used with functional components because they dont have instances.
    2. Not to be used on things that can be done declaritvely.

    Functional components are very useful in React, especially when you want to isolate state management from the component. That’s why they are often called stateless components.

    However, functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since they are not classes by definition.

    In fact, if you have a functional component and you want React to treat it as a pure component, you will have to convert the functional component to a class component that extends React.PureComponent.

    Here is a simple example:
    	
    		// FUNCTIONAL COMPONENT
    		function Percentage({ label, score = 0, total = Math.max(1, score) }) {
    		  return (
    		    <div>
    		      <h6>{ label }</h6>
    		      <span>{ Math.round(score / total * 100) }%</span>
    		    </div>
    		  )
    		}					
    	
    
    	
    		// CONVERTED TO PURE COMPONENT
    		class Percentage extends React.PureComponent {
    
    		  render() {
    		    const { label, score = 0, total = Math.max(1, score) } = this.props;
    
    		    return (
    		      <div>
    		        <h6>{ label }</h6>
    		        <span>{ Math.round(score / total * 100) }%</span>
    		      </div>
    		    )
    		  }
    
    		}
    	
    

    PropTypes provides type checking for your components and serves as nice documentation to the other developers. We can also define the Default Props for each component to display if the component doesn’t receive any props

    Here is a simple example:
    	          	
    	import React, {Fragment} from 'react';
    	import PropTypes from 'prop-types';
    	export const UserDisplay = ({name, address, age}) => {
    		UserDisplay.defaultProps = {
    		    name: 'myname',
    		    age: 100,
    		    address: "0000 onestreet"
    		};
    		return (
    		    <Fragment>
    		    <div>
    		        <div class="label">Name:</div>
    		        <div>{name}</div>
    		    </div>
    		    <div>
    		        <div class="label">Address:</div>
    		        <div>{address}</div>
    		    </div>
    		    <div>
    		        <div class="label">Age:</div>
    		        <div>{age}</div>
    		    </div>
    		</Fragment>
    
    		)
    	}
    	UserDisplay.propTypes = {
    		name: PropTypes.string.isRequired,
    		address: PropTypes.objectOf(PropTypes.string),
    		age: PropTypes.number.isRequired
    	}
    	UserDisplay.propTypes = {
    		counts: PropTypes.array,
    		users: PropTypes.arrayOf(PropTypes.object),
    		alarmColor: PropTypes.oneOf(['red', 'blue']),
    		description: PropTypes.oneOfType([
    			PropTypes.string,
    			PropTypes.instanceOf(Title)
    		]),
    		userWithName: (props, propName, componentName) => { // Custom type
    		    if (!props[propName] || !props[propName].name) {
    		    	return new Error( "Invalid " + propName + ": No name property defined for component " + componentName)
    		    }
    		}
    	}					
    				
    			

    PropTypes can be used to test Props for value of any kind. Here are a few fast type checkers which React has built-in types for JavaScript:

    • React.PropTypes.array,
    • React.PropTypes.bool,
    • React.PropTypes.func,
    • React.PropTypes.number,
    • React.PropTypes.object,
    • React.PropTypes.string,
    • React.PropTypes.symbol,

    We can also test that props are React and DOM types:

    • React.PropTypes.node,
    • React.PropTypes.element,

    And we have the ability to test more complex types, such as "shapes", "instances of", or "collections of":

    • React.PropTypes.instanceOf(Message),
    • React.PropTypes.oneOf(['News', 'Photos']),
    • React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.instanceOf(Message)])
    • React.PropTypes.arrayOf(React.PropTypes.number),
    • React.PropTypes.shape({ color: React.PropTypes.string, fontSize: React.PropTypes.number })

    Using these PropTypes to make errors, and track bugs. PropTypes should prevent the team from wasting too much time during the debugging and documentation process when used efficiently, ensuring tighter standards and understanding of the can component library.

    In designing a React application, a deeply nested component is often needed to use data generated by another component that is much higher in the hierarchy.

    Consider the following example components:

    • <EditUsersPage />, which includes selectedUserAddress in its component state and renders a <User /> component
    • <User />, which renders a <UserDetails /> component
    • <UserDetails />, which renders a <UserAddress /> component
    • A <UserAddress /> component that requires the selectedUserAddress property stored in the <EditUsersPage /> state

    The easiest solution is to simply move from the source component to the deeply nested component a selectedUserAddress prop from each component into the next in the hierarchy. It is called drilling with prop.

    The main disadvantage of prop drilling is that components which otherwise should not be aware of the data — in this case < User/ > and < UserDetails/ > — become unnecessarily complicated and more difficult to maintain.

    A common solution is to use the React context to prevent prop-drilling. It allows for the creation of a Provider component that provides data, and allows nested components to consume context data through either a User component or a useContext button.

    Although context can be used directly for sharing global state, context can also be used indirectly through a module for state management, such as Redux.

    React's StrictMode is sort of a helper component that will help you write better react components, you can wrap a set of components with and it'll basically:

    1. Verify that the inside components meet any of the required procedures, and alert you if not in the console.
    2. Verify that the deprecated methods are not being used, and you will be warned in the console if they are used strict mode.
    3. Support you prevent such side-effects by identifying possible threats.

    Strict mode is growth-driven and you don't have to think about it impacting your production construction.

    I find it especially useful when I work on new codebases to enforce strict mode because I want to see what kind of code/components I'm facing. Even if you're on bug hunting mode, sometimes it's a good idea to cover the components/blocks of code you think could be the root of the issue with < StrictMode/ >.

    So hey, you 're on the right direction to understand the strict mode, keep it up, I guess it's one of those things that you should understand when playing with them, so go ahead and have some fun.

    When it comes to React vs Angular, just take a quick look at their website and you'll know the most basic yet crucial difference between React, the JS library and Angular, the front-end development framework.

    Here's what you 're going to find:

    Angular: a framework. Mobile & Desktop

    React: A JavaScript library to build user interfaces

    This basic conceptual difference in development is based on React vs Angular comparison to the next level. It is true that comparing a framework with a library is not fair in itself. However, a comparison is worthwhile and essential to understanding how the differences between React and Angular have an impact on the web or mobile app development process.

    Here we have created this React vs Angular Comparison Guide which will help you choose between React and Angular as well as Angular native app development company or React app development company.

    Angular Vs React Architectural Difference
    Angular:

    This is a robust front-end development framework that allows you to structure your application. You start coding your application without worrying about the routing of libraries. Angular JS, as a front-end development framework, provides various advanced functionalities to Angular developers, such as:

    1. Templates for building UI views with a strong template syntax
    2. Command line tools to add and test components
    3. Intelligent code completion IDEs
    4. Protractor to make the test run quicker and easier
    5. Intuitive APIs for complex choreography and animation timelines
    6. ARIA enabled components and built-in test infrastructure
    7. Injection of Dependency
    8. Protection of XSS
    React:

    It is an open-source JavaScript library, which is also called V (View) in the MVC framework, and the React developer must consider M (Model) and C (Controller). Views are logical-less files that are controlled by the controllers. So, the big question is, if the framework already has a view, then why do we need React? This is because React does not remove views but applies them to interchangeable UI components such as tab bars, pop up modals, sortable modals, lists, and comment boxes.

    Some of the key functionality of React JS are

    1. JSX, JavaScript syntax extension
    2. Easy-to-create reaction elements
    3. Respond to the DOM to change the DOM and suit the Respond elements
    4. Component API to break the UI into separate, reusable sections
    5. Protection of XSS

    Now that we know the main strengths of Angular and React, let 's dive deeper into the details that classify the features and functions that add power to Angular vs React debate.

    Type Angular React

    Type

    Framework

    Frontend Library

    Data Binding

    Two-way Binding

    One-way Binding

    DOM

    Real

    Virtual

    Template

    HTML+Typescript

    JavaScript + JSX

    Application logic

    Services

    Flux/Redux

    Mobile Development

    Ionic framework

    Native UI experience

    Abstraction

    Strong

    Medium

    Technology

    Complete MVC framework written in javascript

    View in MVC, requires flux to implement architecture

    According to the State of Javascript Survey 2019, we find React as one of the top choices of Javascript Framework and received the overwhelmed response from developers.

    Front-end frameworks and libraries
    React vs. Angular: Choosing one of two robust options

    JavaScript frameworks and libraries are very popular for web app development, and both React and Angular are very popular. We explained their differences and advantages, and we also outlined the factors that should be considered before selecting the correct JavaScript framework/library.

    You need to weigh between React and Angular on the basis of your specific project requirements. For example, if you are running a large project, you will benefit more from using React since its one-way data-binding provides a better overview of the data. On the other hand, because of its two-way data-binding, you will find Angular to be a better approach in a smaller project.

    When to Use React?

    Not every smartphone or web application development project needs React. This is used along with a flow patterned library, such as Mobx and Redux. Below are the cases where you can use React to create web applications:

    1. When your project has several components in a changing state, such as dynamic inputs, extended / collapsed accordion parts, access permissions, and more.
    2. Complex applications where change is common. It helps to fight the spaghetti code, where the organization and structure of the code do not match.
    3. When managing DOM operations, it is tough
    4. If you desperately need to complete the project, it has modular components that save a lot of developers' time.
    5. You have a small team of HTML, CSS , and JavaScript experts.
    When to Use Angular?

    Angular has released a range of versions since AngularJS was introduced. It has advanced features, including the use of nglf with "other," strong animations, and support for Angular CLI. Below are the cases where you can use Angular for your project:

    1. When you need a good navigation service. DOM shadowing and maintenance of data using services
    2. Full configuration of the server is needed
    3. Maintain styling with encapsulation style and part
    4. Building progressive web applications (PWAs)
    5. Want to create a large-scale, feature-rich application

    Angular is an excellent choice for the development of enterprise applications. Angular development companies are widely used to create web applications for large enterprises.

    Using a Class Component

    The componentDidMount() lifecycle hook can be used with class components:

    	
    		class Home extends Component {
    		  componentDidMount() {
    		    trackPageView('Homepage');
    		  }
    		  render() {
    		    return <div>Homepage</div>;
    		  }
    		}		
    	
    

    Any actions specified within the componentDidMount() lifecycle hook will be called only once the component is first installed.

    Using a Function Component

    The useEffect() hook can be used with function components:

    	
    		const Homepage = () => {
    		  useEffect(() => {
    		    trackPageView('Homep');
    		  }, []);
    		  
    		  return <div>Homepage</div>;
    		};
    	
    

    The useEffect() hook is more flexible than the life-cycle methods used for class components. It has two parameters:

    1. The first parameter to be used is the callback function to be executed.
    2. The optional second parameter to be used is an array containing any variables to be monitored.

    When the callback is executed, the value passed as the second argument controls:

    1. If the second parameter is not defined, the callback is executed every time the component is rendered.
    2. If the second parameter contains an array of variables, the callback will be executed as part of the first render cycle and will be executed again every time an item in the array is modified.
    3. If the second parameter contains an empty array, the callback will be executed only once as part of the first rendering cycle. The example above shows how passing an empty array can result in a similar behavior to the componentDidMount() hook within the function component.

    Method #1: Inline styling of React components

    We can add inline styles to any React component that we want to render. These styles are written as attributes and passed to the element. Let's use inline styles to style parts of our component:

    	
    		class Home extends Component {
    		  render() {
    		    return <div style={{ backgroundColor: "#44014C", width: "300px", minHeight: "200px"}}>
    				        <h2 style={{ padding: "10px 20px", textAlign: "center", color: "white"}}>ToDo</h2>
    				    </div>
    		  }
    		}		
    	
    
    Creating a style object variable

    We create a variable style object in the same way that we create a JavaScript object. This object is then passed to the style attribute of the element that we want to style. So instead of adding the inline styles directly, as we did in the previous example, we 're just passing the variables of the object:

    	
    		const TodoComponent = {
    		  width: "300px",
    		  margin: "30px auto",
    		  backgroundColor: "#44014C"
    		}
    		const Header = {
    		  padding: "10px 20px",
    		  color: "white"
    		}
    		class Home extends Component {
    		  render() {
    		    return <div style={TodoComponent}>
    				        <h2 style={Header}>ToDo</h2>
    				    </div>
    		  }
    		}		
    	
    

    Note: The camelCase to dash-separated string change applies only to the property names and not property values.

    Sharing styles across many React components
    	
    		const Header = {
    		  padding: "10px 20px",
    		  textAlign: "center"
    		}
    
    		const ErrorMessage = {
    		  color: "white",
    		  fontSize: "13px"
    		}
    
    		const styles = {
    		  Header: Header,
    		  ErrorMessage: ErrorMessage
    		}
    	
    

    Method #2: CSS-in-JS Modules Such as Styled Components, Emotion, and Styled-jsx

    With Styled Components, we can write the actual CSS in our JavaScript file. This means that you can use all the features of the CSS — like media queries, pseudo-selectors, nesting, etc.—in JavaScript.

    Using styled-components, we can create reusable style components. It's pretty exciting to create and use. Explaining with an example here is going to do us a lot of good.

    First, we need to install it, so run the following in the directory of your React app:

    $ npm install --save styled-components

    	
    		import styled from 'styled-components';
    
    		const TodoComponent = styled.div`
    				background-color: #44014C;
    				width: 300px;`;
    
    		class Home extends Component {
    		  render() {
    		    return (
    		    	<TodoComponent>
    		    		<h2 style={Header}>ToDo</h2>
    		    	</TodoComponent>
    		    )
    		  }
    		}
    
    	
    

    In the code above, we used the styled component that we created — TodoComponent — on line 5 like any other HTML element. The only difference is that it comes with predefined styles of its own.

    Method #3: CSS Modules, Pre-processors Such as Sass, Stylus, and Less

    The CSS module is basically a.css file that is being compiled. When compiled, two outputs are generated. One is the CSS that is a modified version of the CSS input with a renamed class name. The other is a JavaScript object that maps the original name of the CSS with a renamed name.

    	
    		import styles from './styles.css';
    		class Message extends Component {
    		    render() {
    		        return (
    					I am an error message
    				) 
    			} 
    		}
    	
    

    If a performance issue such as slow rendering is found inside an app, the primary move is to use the Profiler tool provided with the Google Chrome and Mozilla Firefox React Developer Tools software plugin. The Profiler tool helps developers to find components which take longer than necessary for rendering or rendering.

    One of the most popular problems in React applications is the unnecessary render of components. React offers two methods that are useful in these situations:

    1. React.memo(): This prevents unnecessary re-rendering of function components
    2. PureComponent: This prevents unnecessary re-rendering of class components

    Both tools depend on a shallow comparison of the component props – if the props are not changed, the component will not return. The shallow comparison, although both tools are very useful, offers an additional performance burden so that they can have a negative impact if they are used incorrectly. The reaction profiler allows you to measure your performance before and after using these tools to ensure that your performance is actually improved by changing it.

    useState()

    	
    		const [count, setCounter] = useState(0);
    		const [moreStuff, setMoreStuff] = useState(...);
    
    		const setCount = () => {
    		    setCounter(count + 1);
    		    setMoreStuff(...);
    		};
    	
    

    UseState is one of the built-in reactive hooks. UseState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the state of the counter.

    We can use the setCounter method to update count status anywhere-in this case we use it within the setCount function where we can do more; the idea with hooks is that we can keep our code more functional and avoid class-based components if not desired / needed.

    useEffect()

    React useEffect is a function that is executed for three different React component lifecycles.These lifecycles are componentDidMount, componentDidUpdate, and componentWillUnmount lifecycles.

    	
    		import React, { useState, useEffect } from 'react';
    
    		const App = () => {
    		  const [message, setMessage] = useState('Hi there, how are you?');
    
    		  useEffect(() => {
    		    console.log('trigger use effect hook');
    
    		    setTimeout(() => {
    		      setMessage("I'm fine, thanks for asking.");
    		    }, 1000)
    		  }, [])
    		  return <h1>{message}</h1>
    		};
    		export default App;
    	
    

    UseEffect accepts a function as the first argument. This function handler will take care of any side effects you like when it's running. The function is a callback function after one of the lifecycle components has been triggered.

    Using Async and Await in React useEffect

    React.useEffect does NOT allow you to add async in the callback function

    	
    		// This will cause your React application to break!
    		React.useEffect(async() => {
    		  // ... stuff
    		}, []);
    	
    

    React is expecting a regular function and not a promise. But if you’d like to use async/await you can move your code into its own function, and invoke it inside React.useEffect().

    	
    		async function fetchData() {
    		  try {
    		    const response = await fetch('url/data/api');
    		    const { data } = await response.json();
    		    console.log(data) // [ { name: 'Mr. Whiskers' }, ...data ]
    		  } catch(e) {
    		    console.error(e);
    		  }
    		}
    
    		React.useEffect(() => {
    		  fetchData();
    		}, []);
    	
    

    Controlled Component

    The controlled component is bound to a value and its changes will be handled in code using event-based callbacks. Here, the input form element is handled by the response itself rather than by the DOM. In this case, the mutable state is kept in the state property and will be updated only with the setState() method.

    Controlled components have functions that govern the transmission of data to each event that occurs onChange. This data is then saved to state and updated using the setState) (method. It makes the component have better control over the elements of the form and the data.

    	
    		class NameForm extends React.Component {
    		  constructor(props) {
    		    super(props);
    		    this.state = {value: ''};
    
    		    this.handleChange = this.handleChange.bind(this);
    		    this.handleSubmit = this.handleSubmit.bind(this);
    		  }
    
    		  handleChange(event) {
    		    this.setState({value: event.target.value});
    		  }
    
    		  handleSubmit(event) {
    		    alert('A name was submitted: ' + this.state.value);
    		    event.preventDefault();
    		  }
    
    		  render() {
    		    return (
    		      <form onSubmit={this.handleSubmit}>
    		        <label>
    		          Name:
    		          <input type="text" value={this.state.value} onChange={this.handleChange} />
    		        </label>
    		        <input type="submit" value="Submit" />
    		      </form>
    		    );
    		  }
    		}
    	
    

    Uncontrolled Component

    It is similar to the traditional HTML form input. The form data is handled here by the DOM itself. It maintains its own state and will be updated as the input value changes. To write an uncontrolled component, you do not need to write an event handler for each state update, and you can use a ref to access the form value from the DOM.

    	
    		class NameForm extends Rea
  • TCS Possible Technical Interview Questions and Answers

    TCS Possible Technical interview Questions on new recruitment campus

    Campus Drive

    Usually, this interview takes 40 to 60 minutes and may have one or two interviewees. By posing behavioral questions, one interviewer will concentrate on your communication skills, self-management skills, and context. The other will focus on your technical skills.

    Telephonic interview

    If TCS will not come to your school this fall, so you will have submitted your resume online this fall. You look great on paper and they want a job discussion with the candidate. They will schedule your phone interview with a mutually acceptable date and time. By asking behavioral questions the interviewer will determine the communication abilities, self-management skills, and context. He/she may evaluate your technical ability, too. If the interview on the phone goes well, you'll be asked to join us for an interview in person.

    TCS Recruitment 2024

    TCS Questions for Technical Interview

    Please note: You should determine your Favorite programming language before the interview and be prepared based on that question.

    Here are some of the differences between Java and C language.

    CJava
    C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.
    C is a Procedural Programming Language.Java is Object-Oriented language.
    C is more procedure-oriented.Java is more data-oriented.
    C is a middle-level language because binding of the gaps takes place between machine level language and high-level languages.Java is a high-level language because translation of code takes place into machine language using compiler or interpreter.
    C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system.Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine).
    C generally breaks down to functions.Java breaks down to Objects.
    C programming language can be used for system programming as well as Application programming.This is not the case in Java.
    C does not contain the property called Inheritance because it does not support OOPS, which is very useful for code reusability. Thus C is not suited when one has to relate the things according to the real world.Java contains the property of Inheritance which is very useful in code reuseability.
    Memory allocation can be done by malloc in CMemory allocation can be done by a new keyword in Java.
    C is a low-level language. It has difficult interpretation for the user but it has a closer significance to the machine-level code.Java is a high-level language because translation of code takes place into machine language using compiler or interpreter.
    In C89 declaration of variables is at the beginning of the block but in the latest version of C that is C99 we can also declare variables anywhere.We can declare variables anywhere.
    free is used for freeing the memory in C. A compiler will free up the memory internally by calling the garbage collector.

    C does not supports Threading.Java supports the concept of threading.
    C supports pointers.Java does not supports pointers.
    It is not portable.It is portable.
    Call by value and call by reference is supported in C.It only supports a call by value.
    C is platform dependent.Java is a platform independent.
    It supports user-based memory management.It internally manages the memory.
    C is not robust that is strict type checking does not takes place while compile and run time.Java is robust.
    Exception handling cannot be directly achieved in C and thus it lacks the maintenance of normal flow of the program.Exception Handling is supported in Java.
    It follows a top-down approach.Java follows a bottom-up approach.
    Overloading functionality is not supported by C.Java supports method overloading which helps in code readability.
    C supports Preprocessors.Java does not support Preprocessors.
    C does not supports OOPS concept.Java supports OOPS concept.
    Union and structure datatypes are supported by C.Java does not supports union and structures.
    C supports the storage classes.Whereas Java does not suport the storage classes.
    It has 32 keywords.It has 50 keywords.
    Go-to statements are supported in C language.Java does not supports go-to statements.
    Virtual keywords are supported by C.Virtual keywords are not supported by Java.
    Overloading functionality is not supported by C.Java supports method overloading which helps in code readability.
    Default members of C are public.Default members of Java are private.
    Data hiding is done by using static in C.Data hiding is done by using private in Java.

    Functions inside the header file are declared. That is there are function prototypes in a header register, not function bodies. They are set in the library (lib).

    There are four types of classes of storage in C. They are local, auto-registration and static

    Static is a qualifier for access. If a variable within a function is declared static, the scope is restricted to the function, but it will exist for the program ‘s lifetime. Values between consecutive calls to a function will persist

    Macros are processor instructions that will be substituted at the time of compile. The downside with macros is that they actually substitute the code they do not function calls. Likewise, the advantage is that they can reduce the replacement time for the same values.

    Pass by value actually transfers the value from the caller to the calling function, so that the call function can not change the caller function values. But Pass by reference will pass the address instead of the value to the caller function if the call function requires modifying any value that it can directly modify.

    An object is an abstract type of data that adds polymorphism and heritage. Instead of structuring programs as code and data, an object-oriented system integrates the two using an “object” concept An object has state and actions (code) (data).

    A class is a user-defined blueprint or prototype which creates objects from. It represents the set of properties or methods that all objects of one form have in common. Class declarations may generally include certain components, in order to:

    Modifiers: A class can be public or has default access (For information see this).
    Class name: Initial letter (capitalized by convention) will start the name.
    Superclass(if any): extends the name of the parent (superclass) of the class, where any, followed by the keyword. A class can only apply to one parent (subclass).
    Interfaces(if any): A comma-separated list of class-implemented interfaces, if any, followed by keyword resources. More than one interface can be implemented by a class.
    Body: The body of the class surrounded by braces,}.

    Constructors are employed to create new objects. Fields are variables that provide the state of the class and its objects, and methods are used to enforce the class and its object’s behavior.

    Here you will learn about class and structure differences.

    A class and a structure, are user-defined data types and often it may be difficult to understand the difference between the two. The following table indicates strong differences between the two to understand this.

    ClassStructure
    It is a reference data type and uses the keyword “class”.It is a value data type and uses the keyword “struct”.
    Object for a class is created in the heap memory.Object for a structure is created in the stack memory.
    We can always inherit another class. i.e., the concept of inheritance is applied.Structures can never be inherited.
    Object is created using the “new” keyword.We may or may not use the keyword “new” while creating objects.
    It occupies more space.A structure occupies less space.
    Class allows both the parameterized and the non parameterized constructors.It only allows for the parameterized constructors, even the default constructors cannot be used.
    Example:
    class fruits {
    Fruit F1;
    F1.apple= “red”;
    F1.mango=”yellow”;
    }
    Example:
    public struct fruit {
    public string apple;
    public string mango;
    }

    POINTER is a variable where the address of another variable is stored. A pointer function can also be used to refer to another pointer. A pointer may be incremented/decremented, i.e. pointing to the next/previous location of the memory. The purpose of the pointer is to save memory space and attain faster execution time.

    How does Pointer Work?
    If we declare a form int variable v, then v will actually store a value.

    Int v = 0;
    V now equals zero.

    However, each variable has its address (or, simply put, where it is located in the memory, apart from the value). The address is retrievable by placing an ampersand (&) before the name of the element.

    If you print a variable ‘s address on the screen, it will look like a completely random number (which can also be different from running).

    Null pointer is a special attribute reserved for a reference. Every sort of pointer has the reserved value. Formally, each particular type of pointer (int *, char *, etc.) has its own dedicated null-pointer value. Conceptually it does not point anywhere when a pointer has that null value.

    Void pointer is a different type of pointer-void *-a pointer pointing to any storage location of data which has no particular form.

    Void pointer is a different type of pointer-void *-a pointer pointing to any storage location of data which has no particular form.

    Null pointer is a value, then again, while the void pointer is a sort. Such definitions are entirely different, and they are incomparable. That basically means your question isn’t exactly true, as mentioned. For example, it’s like asking: “What’s the difference between a triangle and a car?”

    Overloading function is a feature where two or more functions may have different parameters but the same name. Definitions of the polymorphism feature may be called function overloading.

              	#include <iostream> 
    				using namespace std; 
    
    				void print(int i) { 
    					cout << " Here is int " << i << endl; 
    				} 
    				void print(double f) { 
    					cout << " Here is float " << f << endl; 
    				} 
    				void print(char const *c) { 
    					cout << " Here is char* " << c << endl; 
    				} 
    
    				int main() { 
    					print(10); 
    					print(10.10); 
    					print("ten"); 
    					return 0; 
    				}
    			

    Function overloading : A feature in programming languages that allows multiple functions of the same name can be described with different parameter types or with different parameter numbers. This feature is called the Overloading method. The compiler can determine the correct function by evaluating the number of parameter types/arguments within the overloaded function. Function overloading eliminates the expenditure in different feature names and allows the use of more than one feature to perform similar functionality.

    Operator overloading : A feature in programming languages that permits operators to be redefined. This functionality works on objects identified by the user. All overloaded operators have equal syntactic sugar for function calls. Operator overloading offers a nice façade without contributing to / altering the underlying language changes.

    A class friend function is specified outside the boundaries of that class but it has the right of access to all private and protected class members. While the prototypes for friend functions appear in the concept of class, friends are not functions of students.

    A friend can be a function, function template, or member function, or a class or class template, in which case friends are the whole class and all its members. To announce a function as a class friend, precede the prototype function with keyword friend in the class description

    One important feature of C++ is the inline function. So let’s first understand why inline functions are being used, and what is the inline function purpose?

    Once the program executes the function call instruction the CPU will store the instruction’s memory address after the function call, copy the function arguments on the stack and finally pass power to the required function. The CPU then executes the function code, stores the return value of the function in a predefined location/register of the memory, and returns control to the calling function. This can become overhead if the task execution time from the caller task to call the function (callee) is less than the switch time. The overhead of the function call is generally negligible relative to the amount of time the function takes to run for functions that are large and/or perform complex tasks. However, for small, commonly used functions, the time required to make the call to the function is often much longer than the time required to actually execute the code for the function. With small functions, this overhead arises because small function execution time is less than the switching time.

    C++ provides inline functions for lowering overhead call functions. Inline function is a function which is expanded when it is called in line. When the inline function is called entire inline function code is added or substituted at the inline function call stage. The C++ compiler performs this substitution during compile time. Where low, inline feature will improve performance.

        	      	
        	      		inline return-type function-name(parameters) {
    			    		// function code
    					} 
    				
    			

    A class that is declared using the keyword “abstract” is known as abstract. It can have both abstract methods (methods without body) and concrete methods (regular body methods). Can not provide abstract methods in a typical class(non-abstract class). In this guide, we’ll learn what an abstract class is, why we use it and what are the rules that we need to follow when working in Java with it.

    You can not instantiate an abstract class, which means you are not allowed to create an object of it. Why? For what? We’ll explore that in this guide later.

    – An existing memory block which was allocated by subroutine malloc) (will be freed by subroutine free). When an invalid pointer parameter is transferred, there will be unpredictable effects. Unless the parameter is a null-pointer then there will be no intervention.

    – Since the subroutine realloc) (allows the developer to adjust the block size of the memory pointing to the pointer parameter, a given byte size is returned through the size parameter and a new pointer is returned to the block. The specified pointer parameter must have been created by using the subroutines malloc(), calloc) (or realloc) (and should not be dealt with by subroutines realloc) (or free). If the parameter of the pointer is a null pointer then there will be no action.

    All Arrays and Linked List can be used to store similar types of linear data, but they do have some advantages and disadvantages over each other.

    Key Differences Between List and Array

    1. An array is the data structure that contains a collection of similar data elements of the sort while the Linked list is considered a non-primitive data structure that contains a collection of unordered linked elements known as nodes.
    2. The variables belong to indexes in the sequence, i.e. if you wish to enter the fourth element, you must write the name of the variable with its index or position within the square bracket.
    3. However, you must start from the head in a linked list and work your way through until you get to the fourth element.
    4. It’s quick to access an element in an array, while Linked list takes linear time, so it’s a bit slower.
    5. Much time consumes operations such as insertion and deletion in arrays. On the other hand, these operations perform fast on Linked lists.
    6. Arrays are of fixed dimensions. Conversely, Linked lists are dynamic and flexible, and their size can be expanded and contract.
    7. At compile time, memory is allocated in an array, while it is allocated at execution or runtime in a Linked list.
    8. Elements are placed in arrays consecutively, while they are placed randomly in Linked Lists.
    9. The memory requirement is less because the actual data is stored in the array inside the index. As well, due to the storage of additional next and previous referencing items, there is a need for more memory in Linked Lists.
    10. Additionally, the use of memory in the array is inefficient. Conversely, the use of the memory in the linked list is efficient.

    Difference between Structure and Array

    ARRAYSTRUCTURE
    Array refers to a collection consisting of elements of the homogenous data type.Structure refers to a collection consisting of elements of the heterogenous data type.
    Array uses subscripts or “[ ]” (square bracket) for element accessStructure uses “.” (Dot operator) for element access
    Array is pointer as it points to the first element of the collection.Structure is not a pointer
    Instantiation of Array objects is not possible.Instantiation of Structure objects is possible.
    Array size is fixed and is basically the number of elements multiplied by the size of an element.Structure size is not fixed as each element of Structure can be of different type and size.
    Bit filed is not possible in an Array.Bit filed is possible in an Structure.
    Array declaration is done simply using [] and not any keyword.Structure declaration is done with the help of “struct” keyword.
    Arrays is a primitive datatypeStructure is a user-defined datatype.
    Array traversal and searching is easy and fast.Structure traversal and searching is complex and slow.
    data_type array_name[size];struct sruct_name{
    data_type1 ele1;
    data_type2 ele2;
    };
    Array elements are stored in continuous memory locations.Structure elements may or may not be stored in a continuous memory location.
    Array elements are accessed by their index number using subscripts.Structure elements are accessed by their names using dot operator.

    A data structure is a specific way to organize data in a computer so it can be used effectively.

    For example, using the array data structure, we can store a list of items having the same data-type.

    The data structure is important where data is involved in almost every aspect. Algorithms that require an efficient data structure are typically implemented in the following areas: numerical analysis, operating system, A.I., compiler design, database management, graphics, and statistical analysis, to name a few.

    Code Reusability and Readability are the key benefits of inheritance. When child class inherits parent class properties and features, we do not need to write the same code in child class again. This makes reuse of the code easier, makes us write less code, and the code becomes much more legible.

    What is Deadlock?
    There was a time when operating systems could only execute one process at a time, thereby giving full system resources and attention to that one process. Operating systems today can perform several tasks at once, but they often have to deal with a dilemma known as a stalemate. A deadlock occurs when there is at least one process that is waiting for another process to release resources in order to complete a task correctly.

    Prevention & Avoidance:
    A deadlock may occur if and only if all of the following conditions in a system are met at the same time. These terms are referred to as the Coffman conditions:

    1. Mutual exclusion states that each resource may only be allocated to one process at a time
    2. Circular waiting means that a process has a resource and needs some of the resources that other processes carry
    3. Keeping resources is where one or more processes will maintain and wait for other resources to be available for use
    4. No preemption means the resources which have already been granted access and which can not be removed at that time

    If you are aware of these four conditions, you will be able to follow them and hopefully avoid a complete deadlock. In a deadlock situation, there may also be a slight variation in which there are two or more processes in a constantly changing state known as livestock. The crucial difference here is that the processes at play did not necessarily cease at all but rather were just too busy to respond to each other.

    The limitations of singly-linked lists:
    The Single Linked List (SLL) is a linear data structure that consists of nodes chained in one direction. Each node contains a data member that holds useful information and a pointer to the following node.
    The problem with this structure is that it only allows us to traverse forward, i.e. when required, we can not iterate back to a previous node.

    This is where the Connected Double List (DLL) shines. DLLs are an extension of connected basic lists, with one exception only:

    A doubly connected list requires a pointer to the next node and to the previous node. This means you can navigate the list in both directions.

    The class of the doubly linked list:
    From the above definition we can see that there are three fundamental members to a DLL node:

    – The data
    – A pointer to the next node
    – A pointer to the previous node

    Despite the inclusion of a p (previous) pointer, a DLL costs more in terms of memory. The reward for this, though, is that iteration gets much more effective.

    Complexity in time
    The worst-case search, insertion, and deletion complexity is O(n). Can be added and removed at the head in O(1).

    Have you ever wondered how different views different users can have on the same website? A college website, for example, has a different view for the student , faculty and dean. A student can see his / her attendance information, homework, etc .. When a faculty can see its class time-table as well as all the details relevant to a faculty. We see only that much needed data and other data is hidden from us. So, what is the name for this phenomenon? Yeah, you were right. This phenomenon is termed abstraction of data. We’ll hear about data abstraction in this blog and we’ll see the three abstraction levels in DBMS, too. So let’s get going.

    Data Abstraction:
    Data Abstraction refers to the process whereby the user hides irrelevant information. So, what would irrelevant details mean? Let’s get this through with one case. Example: If we try to access some mail from our Gmail then we don’t know where that data is stored physically i.e. is the data present in India or USA or what data model was used to store that data? We are not preoccupied with these issues. Our email is just about us. So, information like this i.e. location of data and data models is irrelevant to us and we only do this in data abstraction. There are other variables that we don’t know about besides the position of data and data models.

    There are mainly three levels of data abstraction and to achieve data independence we divide it into three levels. Data independence ensures that users do not need to communicate directly with each other and data does not. The consumer should be at another level, and the data should be present at a different level. Data Independence can be accomplished by doing so. Now let’s see in-depth what these three abstract types of data are:

    1: View Level
    2: Conceptual Level
    3: Physical Level

    View Level or External Schema
    This level informs the application of how the user should be displaying the data. Example: If in a university system we have a login-id and password, then as a student we can see our marks, attendance, fee structure, etc .. Yet the University’s faculty will have a particular view. He would have choices such as pay, editing a student’s grades, joining the student’s attendance, etc. The student and the teachers, then, have a different view. In doing so, system protection also improves. The student can’t edit his marks in this example but the faculty that is authorized to edit the marks can edit the marks of the student.

    Conceptual Level or Logical Level
    This level says how actually the data is processed and organized. We have different data models from which we can store the data(from here you can learn more about the different data model types). Example: Take an example where the relational model is used to store the data. We must store a student ‘s data, the student table columns will be student name, age, mail id, roll no, etc. At this point, we have to describe all these when we are building the database. Although the data is stored in the database, the structure of the tables, such as the student table, teacher table, book table, etc., is described in the conceptual or logical level here.

    Physical Level or Internal Schema
    The physical level, as the name implies, informs us about where the data is actually stored, i.e. it informs the user ‘s actual location of the data. The Database Administrators(DBA) decide which data should be stored at which particular disk drive, how to fragment the data, where to store it, etc. They are deciding whether to centralize or disperse the data. While at view level we see the data in the form of tables, the data here is actually only stored in the form of files. It totally depends on the DBA, how physically he/she handles the database.

    An argument on the command line allows you to provide input from outside the system to your software. Nearly every programming language accepts arguments from the command line.

    Only one simple example:-

    Using command-line logic, let ‘s find the sum of two integer numbers:

              	#include <stdio.h>
    				int main(int argc, char *argv[])
    				{
    					int a,b;
    					if(argc!=3)
    						return -1;
    					a = atoi(argv[1]);
    					b = atoi(argv[2]);	
    					printf("%d\n",a+b);	
    					return 0;
    				}
    			
    		  

    What is a Storage Class:
    A storage class represents a variable ‘s visibility, and location. It says how much code we can access a variable from. The following things are described by a storage class:

    1. Scope variable.
    2. The position the variable is stored in.
    3. The value initialized in a variable.
    4. A variable lifespan.
    5. What can get into a variable?

    Therefore, the information about a variable is represented by a storage class. There are a total of four standard class storage types. The table below shows the types of capacity in ‘C’

    Storage classPurpose
    autoIt is a default storage class.
    externIt is a global variable.
    staticIt is a local variable which is capable of returning a value even when control is transferred to the function call.
    registerIt is a variable which is stored inside a Register.

    The alignment of the data structure is the way that data is organized and stored in computer memory. Data alignment and padding of the data structure are two separate things but are related to each other and known as Data Structure Alignment together.

    Data alignment: Data alignment involves placing the data at address in memory equal to certain word size multiples. This improves device efficiency because of the manner in which the CPU manages memory.

    Data Structure Padding: Now, to fit the data, some extra bytes which need to be added between the end of the last data structure and the start of the next data structure, because the data is stored in memory because multiples of fixed word size. This addition of extra memory bytes to match the data is called padding of the data structure.

    A new operator is a feature that allocates raw memory — conceptually at least, it’s not much different from malloc). Although it is very rare when you write anything in your own container, you can directly call a new operator, such as:

    char *x = static_cast(operator new(100));

    Overloading of the new operators is also possible either globally, or for a particular class. IIRC, is signed by:

    void *operator new(size_t);

    Of course, if you overload a new operator (whether global or for a class), you will also want/need to delete the matching operator too. For what it’s worth, there’s also a separate new operator] [that’s used to allocate memory to arrays — but you’re almost certainly better off totally ignoring that entire mess. The new operator is what you normally use to build a free-store object:

    my_class *x = new my_class(0);

    The difference between the two is that only raw memory is allocated by a new operator, nothing else. The new operator begins with the use of a new operator to assign memory, but then invokes the constructor for the proper form of entity, so the result is a real live object created in that memory. If that object contains any other objects (either embedded or as base classes) then those builders are also invoked.

    The delete and delete operators] [are used to remove the objects generated with new and new], [returning to the allocated memory left available to the compiler’s memory manager, respectively.

    Objects created with new must obviously be deleted and the arrays created with new] [should be removed].

    A) Recursive is a function that calls itself.
    B) Recursive program speed is slower because of overhead stacking.
    C) The recursive function must be subject to recursive conditions, terminating conditions, and recursive definitions.

    Stack the structure of data. It remembers its caller because of its LIFO (Last In First Out) property, so it knows who to return when the function has to return. Recursion allows the use of device stack to store function calls return addresses. Each recursive function has it’s corresponding iterative (non-recursive) function. Even when these equivalent iterative procedures are written, it is necessary to use the explicit stack.

    Compiler:
    This is a translator that takes input, i.e. high-level language, and generates low-level language output, i.e. machine language or assembly language.

    1. The compiler is smarter than assembler which checks all kinds of limitations, ranges, errors, etc.
    2. But it’s more system run time and takes a greater portion of memory. It is slow because a compiler runs through the whole program and then translates the whole program into machine codes.

    Interpreter:
    An interpreter is a program that converts the language of the programming into an understandable language. –

    1. This merely translates one program assertion at a time.
    2. Most often than not, the interpreters are smaller than compilers.

    Let’s see the difference between Compiler and Interpreter:

    S.No.CompilerInterpreter
    1.Compiler scans the whole program in one go.Translates program one statement at a time.
    2.As it scans the code in one go, the errors (if any) are shown at the end together.Considering it scans code one line at a time, errors are shown line by line.
    3.Main advantage of compilers is it’s execution time.Due to interpreters being slow in executing the object code, it is preferred less.
    4.It converts the the instructions into systematic code.It doesn’t convert the instructions instead it directly works on source language.
    Eg.C, C++, C# etc.Python, Ruby, Perl, SNOBOL, MATLAB etc.

    Applet is a java program that can be inserted into the HTML pages. Java applets running on the java allow Web browsers like Mozilla and internet explorer. The applet is designed to run on the client-server remotely, so some limitations apply. Applets can not access local computer resources from the system. Applets are used to make the Website more fun and interactive.

    Garbage Collector is a program that automatically manages memory, where Java performs the de-allocation of objects rather than the programmer. In the Java programming language, the new operator is used to achieve the dynamic allocation of objects. An object once created uses some memory, and the memory remains allocated until references are made for the object to be used.

    If there are no references to an object, it is assumed that it is no longer necessary and it is possible to reclaim the memory occupied by the object. There’s no explicit need to destroy an object because Java automatically handles the de-allocation.

    Garbage Collection is known as the technique that accomplishes this. If there is no memory left in the system to allocate, programs that do not de-allocate memory can eventually crash. Those programs are said to have leaks of memory.

    Garbage collection in Java occurs automatically during program lifetime, eliminating the need for memory de-allocation and thus avoiding memory leakage.

    In C language it is the duty of the programmer to de-allocate the dynamically allocated memory using the free) (function. This is where the administration of Java memory leads.

    In C language it is the duty of the programmer to de-allocate dynamically assigned memory using the free) (function. That is where control of the Java memory is going.

    In the presence of malicious third parties — known as adversaries, cryptography allows for secure communication. Encryption converts an input (i.e. plaintext) into an encrypted output ( i.e., ciphertext) using an algorithm and a key. If the same key is used, a given algorithm will always convert the same plaintext into the same ciphertext.

    Algorithms are considered safe if, given the ciphertext, an attacker is unable to determine any of the plaintext or key properties. Given a large number of plaintext/ciphertext combinations that used the key, an attacker should not be able to determine anything about a key.