November 3, 2020

JavaScript Interview Questions with Answers Part 3

1. Rest parameters ...
There will be no error because of “excessive” arguments when calling the function.

function totalOf(...nums) { // nums is the name for the array
  let sum = 0;

  for (let num of nums) sum += num;

  return sum;
}

alert( totalOf(1) ); // 1
alert( totalOf(1, 2) ); // 3
alert( totalOf(1, 2, 3) ); // 6

The rest parameters must be at the end.

2. The “arguments” variable

There is also a special array-like object named arguments that contains all arguments by their index.

For instance:

function showName() {

  alert( arguments.length );
  alert( arguments[0] );
  alert( arguments[1] );
 
}

// shows: 2, John, Bob
showName("John", "Bob");

// shows: 1, Ilya, undefined (no second argument)
showName("Ilya");

3. How to get function name and number of parameters in JavaScript?
The “name” property:

function hello() {
  alert("Hi");
}
alert(hello.name); // hello

The “length” property:
There is another built-in property “length” that returns the number of function parameters.

function f1(a) {}
function f2(a, b) {}
function many(a, b, ...more) {}

alert(f1.length); // 1
alert(f2.length); // 2
alert(many.length); // 2. The Rest Parameters is not considered

Custom properties
We can also add properties of our own.

4. setTimeout vs. setInterval in JavaScript
setTimeout allows us to run a function once after the interval of time.
Syntax:
setTimeout(func|code, [delay], [arg1], [arg2], ...)

Canceling with clearTimeout
A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution.
The syntax to cancel:
let timerId = setTimeout(...);
clearTimeout(timerId);

setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Syntax:
setInterval(func|code, [delay], [arg1], [arg2], ...)

5. [[Prototype]]
In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either null or references another object. That object is called “a prototype.

__proto__ is a historical getter/setter for [[Prototype]].

Example:
let athlete = {
  eats: true,
  run() {
    alert("athlete run");
  }
};

let highjumper = {
  jumps: true,
  __proto__: athlete
};


// run is taken from the prototype
highjumper.run(); // athlete run

// Object.keys only returns own keys
alert(Object.keys( highjumper )); // jumps

// for..in loops over both own and inherited keys
for(let prop in highjumper ) alert(prop); // jumps, then eats

6. What is async-await?

Async and Await are extensions of promises.

Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.
async function firstAsync() {
  return 1;
}
firstAsync().then(alert); // 1

Running the above code gives the alert output as 1, it means that a promise was returned, otherwise the .then() method simply would not be possible.

The await operator is used to wait for a Promise. It can be used inside an Async block only.

7. The "new Function"

Syntax:

let func = new Function ([arg1, arg2, ...argN], functionBody);


Example:

let sum = new Function( 'x', 'y', 'return x + y' );


When a function is created using a new Function, its [[Environment]] is set to reference not the current Lexical Environment, but the global one.


So, such a function doesn’t have access to outer variables, only to the global ones.


var p = 9;

function temp() {

  

  var p = 5;

  alert( p );

  let func = new Function( 'return p;' );

  alert( func() );

  

}


temp();//Alerts 5 then 9 since new Function reference global


8. function myAdder( arr ) {
    arr[ 1 ] ++;
    arr = arr + arr;
  return arr;
}
a = new Array( 1, 3, 2, 5 );
var b = myAdder( a );


console.log( b );

1. 1, 4, 2, 5, 1, 4, 2, 5
2. 1, 4, 2, 51, 4, 2, 5
3. undefined
4. error

Answer: 2

The addition operator either performs string concatenation or numeric addition.
So, '1, 4, 2, 5' + '1, 4, 2, 5' is '1, 4, 2, 51, 4, 2, 5'

9. Output of it 1" - - "1" is?

1. 2
2. 0
3. 1
4. Error

Answer: 2

The statement evaluates to 1-(-1) which is 2.

Output of it 1" -- "1" is?

1. 2
2. 0
3. 1
4. Error

Answer: 4

Postfix cannot be put in between two numbers.

10. Instanceof String
let str = "this is string";
console.log( str instanceof String );//string literal is not an object. So, false.
str = new String( "this is string" );
console.log( str instanceof String );//true

11. What's the difference between putting script in head and body? 
When scripts are included in the head they load or run before the content of the page. When you include them in the body they load or run after the preceding html. It oss usually a good practice to put scripts as close to the end of the body as possible.

12. What is setTimeout doing when set to 0 milliseconds?
JavaScript is single-threaded. Asynchronous callbacks are assigned to a message placed in a message queue.

A new message is added to the queue immediately, and will be processed when the currently executing code is finished and any previously-added messages have been processed.

13. typeof
The typeof operator returns a string indicating the type of the unevaluated operand.
console.log( typeof 'str' );
console.log( typeof 123 );
console.log( typeof undefined );
console.log( typeof typeof undefined );
console.log( typeof new Array() );
console.log( typeof new String() );

> "string"
> "number"
> "undefined"
> "string"
> "object"
> "object"

14. padStart() and padEnd()
The padStart() amd padEnd() methods pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.
let str = 'ab';
console.log( str.padStart( '3', 'i' ) );
console.log( str.padEnd( '3', 'i' ) );

Output:
iab
abi

15. Array reduce() Method
The reduce() method reduces the array to a single value.
The reduce() method executes a provided function for each value of the array (from left-to-right).
The return value of the function is stored in an accumulator (result/total).

Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

function subVal(total, num) {
  return total - num;
}

var numbers = [175, 50, 25];

console.log( numbers.reduce( subVal ) );//100 since 175 is initial value. So, 175 - 50 - 25
console.log( numbers.reduce( subVal, 300 ) );//50 since 300 is initial value. So, 300 - 175 - 50 - 25

No comments:

Post a Comment