Tuesday, July 31, 2018

Top 17 interview questions on Javascript


Source : https://aircto.com/interview-questions/javascript/

What is Scope?
In JavaScript there are two types of scope:
Local scope
Global scope
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.Variables defined inside a function are not accessible (visible) from outside the function.
Local JavaScript Variables:
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.
What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top.
In JavaScript, a variable can be declared after it has been used.
How ‘this’ works in JavaScript?
Whenever a function is contained in the global scope, the value of this inside of that function will be the window object.
Whenever a function is called by a preceding dot, the object before that dot is this.
Whenever a constructor function is used, this refers to the specific instance of the object that is created and returned by the constructor function.
What is call () and apply () & bind() in JavaScript?
Call invokes the function and allows you to pass in arguments one by one.
Apply invokes the function and allows you to pass in arguments as an array.
Bind returns a new function, allowing you to pass in this array and any number of arguments. Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.
How will you achieve inheritance in JavaScript?
Every JavaScript object has a prototype. A prototype is also an object.
All JavaScript objects inherit their properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
What is the significance of, and the reason for, wrapping the entire content of a JavaScript source file in a function block?
Strict Mode is a feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.
Strict mode helps out in a couple ways:
It catches some common coding bloopers, throwing exceptions.
It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
It disables features that are confusing or poorly thought out.
What is closure in JavaScript?
A closure is a 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.
To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
What is the difference between == and === ?
The == operator will compare for equality after doing any necessary type conversions. The ===operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.
What is promise in Javascript?
A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
What is the value of typeof undefined == typeof NULL?
The expression will be evaluated to true since NULL will be treated as any other undefined variable.
2.What is the most efficient way to deep clone an object in JavaScript?
.clone() method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
What is the difference between classical inheritance and prototypal inheritance?
Classical Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the new keyword. Class inheritance may or may not use the class keyword from ES6.
Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or Object.create(). Instances may be composed of many different objects, allowing for easy selective inheritance.
What is RESTful Web Service? How to call a REST web service API from Javascript button Handler?
REST stands for Representational State Transfer, an architectural style that has largely been adopted as a best practice for building web and mobile applications. RESTful services are designed to be lightweight, easy to maintain, and scalable. They are typically based on the HTTP protocol, make explicit use of HTTP methods (GET, POST, PUT, DELETE), are stateless, use intuitive URIs, and transfer XML/JSON data between the server and the client.
Javascript code
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "Your Rest URL Here", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
Button Action
How to check if an array includes an object in JavaScript?
function contains(a, obj) {
var i = a.length;
while (i--) {
   if (a[i] === obj) {
       return true;
   }
}
return false;
}
Extending Array prototype
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}
What will be the output of the code below?
var y = 1;
  if (function f(){}) {
    y += typeof f;
  }
  console.log(y);
The output would be undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing type of f returns undefined because the if statement code executes at runtime, and the statement inside the if the condition is evaluated during runtime.
Write the code for adding new elements dynamically?
 
 
 
firstP
How do I empty an array in Javascript?
Ways to clear an existing array B = [];
This code will set the variable B to a new empty array. This is perfect if you don't have references to the original array B anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable B.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Javascript array cheatsheet

A cheatsheet of array methods:
  • To add/remove elements:
    • push(...items) – adds items to the end,
    • pop() – extracts an item from the end,
    • shift() – extracts an item from the beginning,
    • unshift(...items) – adds items to the beginning.
    • splice(pos, deleteCount, ...items) – at index pos delete deleteCount elements and insert items.
    • slice(start, end) – creates a new array, copies elements from position start till end (not inclusive) into it.
    • concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of itemsis an array, then its elements are taken.
  • To search among elements:
    • indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
    • includes(value) – returns true if the array has value, otherwise false.
    • find/filter(func) – filter elements through the function, return first/all values that make it return true.
    • findIndex is like find, but returns the index instead of a value.
  • To transform the array:
    • map(func) – creates a new array from results of calling func for every element.
    • sort(func) – sorts the array in-place, then returns it.
    • reverse() – reverses the array in-place, then returns it.
    • split/join – convert a string to array and back.
    • reduce(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.
  • To iterate over elements:
    • forEach(func) – calls func for every element, does not return anything.
  • Additionally:
    • Array.isArray(arr) checks arr for being an array.
Please note that methods sortreverse and splice modify the array itself.

Sum of [1, [2,1], [3,9], 4, 5]



<script>
var arr = [1, [2,1], [3,9], 4, 5];
var  result = arr.reduce(function(sum, current){
if(Array.isArray(current)){
var x = current.reduce(function(xsum, xcurrent){
return xsum + xcurrent;
});
return sum + x;
}
else{
return sum + current
}
});
alert( result ); // 15
</script>

Find Duplicate in Two arrays


var x=[10,20,40,40,90]

var y=[11,10,20,90]

x.map(function(e){
if(y.indexOf(e)>-1){
console.log(e)
    }
});


primitive data types & non-primitive data types



 variable of a non-primitive type doesn't contain the value directly; instead, it is a reference (similar to a pointer) to an object. (It is not possible in Java to create user-defined value types). Java has eightprimitive types: byte , short , int , long , char , boolean , float and double 


Image result for primitive and non-primitive


Thursday, July 26, 2018

alternative for conditional statements in javascript



ref:https://blog.wax-o.com/2015/05/an-alternative-to-if-else-and-switch-in-javascript/



var result = ( ( {
    45: () => {
return 11;
    },
    11: () => {
return 45;
    },
} )[ 11 ])();

Compare two arrays and return duplicate values

var x = ['IdA', 'idB', 'IdC', 'IdD', 'IdE'];
var y = ['idB', 'IdE', 'IdF'];

var z = x.filter(function(val) {
  return y.indexOf(val) != -1;
});

o/p : ["idB", "IdE"]

Wednesday, July 25, 2018

call() , apply() and bind() in JavaScript


ref: https://www.codementor.io/niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp



How-to: call() , apply() and bind() in JavaScript
In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions with simple examples. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.

Uses

You can use call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.
To get a grasp of "this" in JavaScript, read Understanding "This" in JavaScript.

call() or Function.prototype.call()

Check the code sample below for call()
//Demo with javascript .call()

var obj = {name:"Niladri"};

var greeting = function(a,b,c){
    return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};

console.log(greeting.call(obj,"Newtown","KOLKATA","WB"));
// returns output as welcome Niladri to Newtown KOLKATA in WB
The first parameter in call() method sets the "this" value, which is the object, on which the function is invoked upon. In this case, it's the "obj" object above.
The rest of the parameters are the arguments to the actual function.

apply() or Function.prototype.apply()

Check the below code sample for apply()
//Demo with javascript .apply()

var obj = {name:"Niladri"};

var greeting = function(a,b,c){
    return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};

// array of arguments to the actual function
var args = ["Newtown","KOLKATA","WB"];  
console.log("Output using .apply() below ")
console.log(greeting.apply(obj,args));

/* The output will be 
  Output using .apply() below
 welcome Niladri to Newtown KOLKATA in WB */
Similarly to call() method the first parameter in apply() method sets the "this"value which is the object upon which the function is invoked. In this case it's the "obj" object above. The only difference of apply() with the call() method is that the second parameter of the apply() method accepts the arguments to the actual function as an array.

bind() or Function.prototype.bind()

Check the below code sample for bind()
//Use .bind() javascript

var obj = {name:"Niladri"};

var greeting = function(a,b,c){
    return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};

//creates a bound function that has same body and parameters 
var bound = greeting.bind(obj); 


console.dir(bound); ///returns a function

console.log("Output using .bind() below ");

console.log(bound("Newtown","KOLKATA","WB")); //call the bound function

/* the output will be 
Output using .bind() below
welcome Niladri to Newtown KOLKATA in WB */
In the above code sample for bind() we are returning a bound function with the context which will be invoked later. We can see the bound function in the console as below .
bound.jpg
The first parameter to the bind() method sets the value of "this" in the target function when the bound function is called. Please note that the value for first parameter is ignored if the bound function is constructed using the "new" operator.
The rest of the parameters following the first parameter in bind() method are passed as arguments which are prepended to the arguments provided to the bound function when invoking the target function.
That's all for now. Thank you for reading and I hope this post will be helpful for beginners who are facing issues regarding the apply(), call(), and bind()methods of JavaScript.

Wednesday, July 18, 2018

angular-2-sibling-component-communication


1. using Services : https://embed.plnkr.co/P8xCEwSKgcOg07pwDrlO/

2. another one is passing sibling reference as below

https://medium.com/@pandukamuditha/angular-5-share-data-between-sibling-components-using-eventemitter-8ebb49b64a0a

However I find the following solution much simpler, it allows to share data between 2 siblings.(I tested this only on Angular 5)
In you parent component template:
<!-- Assigns "AppSibling1Component" instance to variable "data" -->
<app-sibling1 #data></app-sibling1>
<!-- Passes the variable "data" to AppSibling2Component instance -->
<app-sibling2 [data]="data"></app-sibling2> 
app-sibling2.component.ts
import { AppSibling1Component } from '../app-sibling1/app-sibling1.component';
...

export class AppSibling2Component {
   ...
   @Input() data: AppSibling1Component;
   ...
}

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...