ECMAScript 6



21. What is Promises?  

Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
function timeout(duration = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, duration);
    })
}

var p = timeout(1000).then(() => {
    return timeout(2000);
}).then(() => {
    throw new Error("hmm");
}).catch(err => {
    return Promise.all([timeout(100), timeout(200)]);
})


22. What is Reflect API?  

Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.



23. What is Tail Calls?  

Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
function factorial(n, acc = 1) {
    'use strict';
    if (n <= 1) return acc;
    return factorial(n - 1, n * acc);
}

// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES6
factorial(100000)


24. What is Variable?  

The humble var keyword has been with us since the very beginning of JavaScript. With ECMAScript 6, we’re gaining new ways to declare variables and even constants. Now that browser support is starting to improve, I’d like to take the opportunity to run through what we have now, what is coming up on the horizon.

If you have any experience with JavaScript, you probably know at least something about variables and scope. You’ll know that to define a variable you use the var keyword:
var aNewVariable = null;

You’ll probably also know that a variable is in the global scope if declared outside of a function, and the local scope if declared inside a function:
var globalVariable = "Global";

function aFunction() {
	var localVariable = "Local";
}

What may confuse you at first, if you come from a background in C-like languages–such as Java–is that local variables in JavaScript have function scope, rather than block scope. That is, variables behave as if they are hoisted up to the top of the function. Variables defined in a block, such as the body of an if statement, can be accessed from the enclosing function. They can even be accessed before the variable is declared:
function aFunction() {
   // sets the variable defined in the do/while block
   blockVariable = "Not global";
    
    do {
        var blockVariable = 1;
    } while (false);
    
    // 1 as can access variable inside block;
    console.log(blockVariable); 
}

While this slightly confusing behaviour can be useful, block level scope also has its place. Previously, there was no way to achieve this in JavaScript, except applying “hacks” such as including the code you want to be block level inside a self executing function. With ECMAScript 6 (ES6 for short), that will change, with the introduction of the let keyword.



25. What is Constant?  

As well as variables, many languages have the concept of constants. That is, variables where you can not change the value once it has been initialised. JavaScript lacks this ability, although if you have an object, you can freeze it using Object.freeze in ES5.

With ES6, we will get this ability directly with the new const keyword. As you would expect, once you have declared a const, the value can’t be changed:
(function () {
	const CONSTANT_VARIABLE = "Foo";

	/* should print "foo" to console */
	printValue(CONSTANT_VARIABLE);
	
	/* Try to change value. Should fail */
	CONSTANT_VARIABLE = "Bar";
	
	/* should still print "Foo" to console, not "Bar" */
	printValue(CONSTANT_VARIABLE);

	function printValue(val) {
    		console.log("Value of CONSTANT_VARIABLE is " + val);
	}
})();
You’ll notice I’ve made the identifier all uppercase in the example above. I prefer to name constants this way, as it is consistent with how constants are named in host and native objects.

One thing to be aware of with const in ES6 is that they share the same block level scoping as let. This is different from how they were originally defined in JavaScript 1.7, and implemented in Firefox, where they have function scope, the same as var. IE11 uses block level scoping, as does Chrome, but only when you use strict mode and enable the experimental flag. Unfortunately, Opera, Safari, and Chrome without the flag only support const if you don’t use strict, so support is mutually exclusive here.

The other thing you should be aware of is that Presto-based Opera and Safari 6 both support const but treats it exactly like var. That is, it isn’t a constant at all; you can change the value. I’ve not managed to test Safari 7, but the latest WebKit nightlies work as in the ES6 spec.


26. How to use Block level scope with let?  

Variables declared with the let keyword work in a similar way to those declared with var, except they use block level scoping instead of function level. If we adapt the previous example to declare blockVariable with let, and run it in browser that supports the keyword (more on that below), you’ll see that two different variables will exist: one inside the do/while block, which has block level scope, and a global property (it isn’t exactly a variable) outside of the block.
function aFunction() {
   // creates new property on the global object
   blockVariable = "property of the Global object";
    
    do {
        let blockVariable = 1;
    } while (false);
    
    // "property of the Global object" as can’t access variable inside block;
    console.log(blockVariable); 
}

One place where let seems immediately useful is when initialising a for loop. Due to variable hoisting, it is often recommended to define your initialiser (often called i) at the top of the function. However, this divorces the variable from the loop somewhat, and it personally feels a bit strange. Using let will give you the best of both worlds:
for (let i = 0; i & 10; i++) {
	//do stuff
}

As with anything ES6, browser support is where things fall a bit flat at the moment. IE11 has just implemented it by default. Firefox has had let for a long time, but you have to enable JavaScript 1.7 mode (let was formally Firefox specific) using type="application/javascript;version=1.7". With it becoming more common practice to remove the type attribute when using HTML5, this feels a little odd now, but I’m sure this requirement will change as ES6 matures.

For Chrome, things are a little more tricky. First you need to enable experimental JavaScript features in ”chrome://flags/”. Then it seems to only work if you are using strict mode: "use strict"; as the first statement of the script or function. It is not supported in Safari or Opera (technically, it would be supported in Opera 15 if you enable the experimental flag, but there is currently no way to do this).


27. what is Block-Scoped Variables?  

const is a signal that the variable won't be reassigned. let is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.



28. What is Block-Scoped Functions?  

JavaScript comes with a function-level scope for variables and functions. This quirk often trips beginners who are already familiar with other curly braces language. With ECMAScript 6, the situation will change with the availability of the well-understood block scope.

Function-level scope leads to a situation called hoisting. For example, for this code:
function f() {
  doSomething();
  var a = 1;
}

what really happens is something like:
function f() {
  var a;
  doSomething();
  a = 1;
}


29. What is Expression Bodies?  

An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

Basic Syntax:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: (param1, param2, …, paramN) => { return expression; }

// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }
singleParam => { statements }

// A function with no parameters requires parentheses:
() => { statements }
() => expression // equivalent to: () => { return expression; }


Advanced Syntax:
// Parenthesize the body to return an object literal expression:
params => ({foo: bar})

// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }

// Destructuring within the parameter list is also supported
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6


30. What is Lexical this?  

ES6 arrow functions, syntax and lexical scoping. ... If you're competent with the way JavaScript scope works, and have a great understanding of lexical scope, the this keyword and Prototype methods such as .call() , .apply() and .bind() , then you're in good hands to continue reading.

You might notice that arrow function is equivalent to (function(){...}).bind(this). The arrow function is bound to the current context. This is the real difference between arrow function and normal function expression. However, it does not matter if we are not using this in the function body.

To understand lexical this, we need to understand lexical scope first. Todd Motto has written an excellent article on JavaScript scopes. I highly recommends everyone to have a read. In short, a lexical scope (or closure) is a scope that has access to the variables in its parent scope.
var foo = 'bar';
function parent() {
  // `foo` is available here
  console.log('Inside parent: ' + foo);
 
  function child() {
    // `foo` is available here too
    console.log('Inside child: ' + foo);
  }
  child();
}
 
parent(); // prints 'Inside parent: bar' and 'Inside child: bar'

Lexical this extends this idea to the this keyword.
function User() {
  var _this = this;
  setTimeout(() => {
    console.log(_this === this);
  }, 0);
}
var user = new User(); // prints `true`
 
function User2() {
  var _this = this;
  setTimeout(function() {
    console.log(_this === this);
  }, 0);
}
var user2 = new User2(); // prints `false`

Lexical this is easier to work with as it is defined by where the function is written, instead of the context it is being called.

One thing to note that arrow functions ignore any effort to change this binding. Therefore, call, apply, bind and even the rules in strict mode cannot change the value of this.


31. What is Default Parameter Values?  

Let's freshen up our knowledge quickly and take a look at the syntax again. Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined ; this means null is a valid value.A default parameter can be anything from a number to another function.

 // Basic syntax
function multiply (a, b = 2) {
  return a * b;
}
multiply(5); // 10

// Default parameters are also available to later default parameters
function foo (num = 1, multi = multiply(num)) {
  return [num, multi];
}
foo(); // [1, 2]
foo(6); // [6, 12]
 


32. What is Rest Parameter?  

Handling a function with a variable number of arguments is always tricky in JavaScript. At least, we still have this arguments object which can be used to retrieve all arguments used to invoke a function. With the upcoming ECMAScript 6, no such hack is necessary anymore since we can start using its rest parameter feature.

To see how a rest parameter works, consider the following scenario. You drive a truck which delivers some supplies to a grocery store. As you unload the supplies, you add them to the store:
store.add('fruit', 'apple');
store.add('dairy', 'milk', 'cheese', 'yoghurt');
store.add('pastries', 'donuts', 'croissants');

whereby add is implemented as something like:
store.add = function(category) {
  var items = [].slice.call(arguments, 1);
  items.forEach(function (item) {
    store.aisle[category].push(item);
  });
};


33. What is Spread Operator?  

Operator to copy enumerable properties from one object to another in a more succinct way. The object spread operator is conceptually similar to the ES6 array spread operator. ... The advantage of using the object spread syntax becomes more apparent when you're composing complex objects.

While rest parameters use the rest operator to combine zero or more parameters into a single array parameter, the spread operator does just the opposite. It separates an array into zero or more parameters.
we can use the spread operator (along with a rest parameter!):
function merge(...objects) {
    let masterObj = {};
 
    // iterate over `objects` merging each
    // into `masterObj` to generate flattened
    // object
    for (let i = 0; i < objects.length; i++) {
        let obj = objects[i];;
        for (let key in obj)
            masterObj[key] = obj[key];
    }
 
    return masterObj;
}
 
let objectsList = [
    {
        count: 5,
        delay: 2000,
        early: true,
        message: 'Hello'
    },
    {
        early: false
    }
];
let merged = merge(...objectsList);
 
// output:
// {count:5, delay:2000, early:false, message:'Hello'}
console.log(merged);

The spread operator looks exactly like the rest operator. It is the same three dots (...). The only difference is that it is used in function calls and array literals instead of function parameter declarations. The spread operator should be able to replace the majority, if not all, uses of apply.

At first, using the spread operator may not seem like much of an improvement over apply, besides no longer having to specify undefined. However, the spread operator can be used anywhere in a function call and may be used more than once as well. Take a look at this example:
let merged = merge(
    {count: 10},
    ...objectsList,
    {delay: 1500}
);
 
// output:
// {count:5, delay:1500, early:false, message:'Hello'}
console.log(merged);

Now we’re specifying individual objects as well as the array. If we were going to still try to use apply we would first have to build a new array including the individual objects. Spread operator to the rescue!


34. What is Template Literals?  

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.

Syntax

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

Description

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting. To escape a back-tick in a template literal, put a backslash \ before the back-tick.
`\`` === "`" // --> true

Multi-line strings

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:
console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"

To get the same effect with multi-line strings, you can now write:
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"


35. What is Extended Object Literals?  

Extended Object Literals simplify object creation and composition by reducing the required amount of typing with some syntactic sugar.

With this, object literals are now syntactically similar to ES6’s new class syntax and have less duplication in common use-cases like constructor function.
es5: {"a":"somestring","b":5,"c":{"key":"value"}}
es6: {"a":"somestring","b":5,"c":{"key":"value"}}
me: {"name":"Alex","age":26}
If you add1() to 5 you get 6


36. What is Binary and Octal Literal?  

You can now specify integers in binary and octal notation: > 0xFF // ES5: hexadecimal 255 > 0b11 // ES6: binary 3 > 0o10 // ES6: octal 8. The global object Number gained a few new properties. Among others: Number.EPSILON for comparing floating point numbers with a tolerance for rounding errors.

Here’s a nice and easy one to start our week; you can now represent binary and octal numbers with literals:
console.log(parseInt("101011", 2)); // 43
console.log(0b101011); // 43

console.log(parseInt("0543", 8)); // 355
console.log(0o543); // 355


37. What is object literal property value shorthand?  

Constructing an object using the literal syntax is something that is very familiar to every JavaScript developer, quite likely because this reminds everyone of JSON. While every object property needs to be either a key-value pair or getter/setter, this may change in the near future. Another syntactic sugar in the upcoming ECMAScript 6 is the object literal property value shorthand.

Consider the following ECMAScript 5 fragment:
function createMonster(name, power) {
  return { type: 'Monster', name: name, power: power };
}
function createWitch(name) {
  return { type: 'Witch', name: name };
}

With the new shorthand form, this can be rewritten as the following code:
function createMonster(name, power) {
  return { type: 'Monster', name, power };
}
function createWitch(name) {
  return { type: 'Witch', name };
}

As you can see, this works because the property value has the same name as the property identifier. This a new addition to the syntax of Object Initialiser in the latest ECMAScript 6 draft Rev 13. Of course, just like the limitations set from ECMAScript 3, you can’t use a reserved word as your property name.


38. What is Computed Property?  

The ECMAScript 6 compatibility table shows that neither Node nor io.js currently have support for computed properties. The data is under object literal extensions > computed properties.



39. What is Destructuring Assignment?  

In a programming language, destructuring assignment denotes the use of patterns to extract parts of an object. If we refer to Common LISP, destructuring assignment binds a set of variables to a corresponding set of values, where normally bind a value to a single variable. For the next-generation ECMAScript 6, destructuring feature is slated to be an important addition to the assignment expression.

Python developers might be already familiar with the concept of sequence unpacking. CoffeeScript also already has the syntax for destructuring. SpiderMonkey, the JavaScript engine in Firefox, has been supporting destructuring assignment for a while. The latest ECMAScript 6 defines the grammar for destructuring assignment in Section 11.13.1.

There are two different forms:
(i)array pattern and
(ii) object pattern.


40. What is Array Pattern?  

Variables can be initialized in one go. The following two lines have the same effect, the first one is employing an array pattern.
var [m, d, y] = [3, 14, 1977];
var m = 3, d = 14, y = 1977;

Swapping two variables is rather trivial, this one works just as expected. Internally, it does the sequence as if there is a temporary variable temp and the usual value exchange.
x = 3; y = 4; [x, y] = [y, x]
temp = [y, x]; x = temp[]; y = temp[1];
Another typical use of array restructuring is for a function which has multiple return values. We don’t need to wrap it in an object anymore. Also, there is no need to accept all elements in the array.

function now() { return [2, 6, 2013, 8, ]; }
var [m, d] = now(); // m = 2, d = 6
var [,,year] = now(); // year = 2013


.Net Interview Question

PHP Interview Question

Java Interview Question

AngularJS Interview Questions