August 24, 2020

JavaScript Interview Questions with Answers Part 1

1. Object value settings or Initialisation in JavaScript

1. Dot Operator
var objPerson = new Object();
objPerson.FirstName = 'John';
objPerson.LastName = 'Brad';
objPerson.Age = 1969;

2. Object Initialiser - comma-delimited
var objPerson = {
    FirstName: 'John',
    LastName: 'Brad',
    Age: 1969
};

3. Constructor Function
function Person(FirstName, LastName, Age) {
  this.FirstName = FirstName;
  this.LastName = LastName;
  this.Age = Age;
}

4. Object.create()
// Animal properties and method encapsulation
var Animal = {
  type: 'Invertebrates', // Default value of properties
  displayType: function() {  // Method which will display type of Animal
    console.log(this.type);
  }
};

// Create new animal type called animal1 
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates

// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType(); // Output:Fishes

5. Square Bracket Notation
objPerson['FirstName'] = 'John';
objPerson['LastName'] = 'Brad';
objPerson['Age'] = 1969;

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

2. Functions in JavaScript
Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

function myFunc(theObject) {
  theObject.Firstname = 'John';
}

var mycar = {Firstname: 'Smith', Lastname: 'Bob', Age: 55};
var x, y;

x = mycar.Firstname; // x gets the value "John"

myFunc(mycar);
y = mycar.Firstname; // y gets the value "John"
                // (the Firstname property was changed by the function)
                
function hoisting only works with function declarations—not with function expressions:
Below code will work.
console.log( cube( 5 ) );
/* ... */
function square(n) { return n * n *n }

Below code will fail:
console.log(square)    // square is hoisted with an initial value undefined.
console.log(square(5)) // Uncaught TypeError: square is not a function
const square = function(n) {
  return n * n;
}

Recursive Function:
If a function calls itself, then it is Recursive Function.
In fact, recursion itself uses a stack: the function stack. The stack-like behaviour can be seen in the following example:

function foo(i) {
  if (i < 0)
    return;
  console.log('begin: ' + i);
  foo(i - 1);
  console.log('end: ' + i);
}
foo(3);

// Output:

// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3

arguments
The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

arguments[i]

The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

3. The finally block 
The finally block contains statements to be executed after the try and catch blocks execute. Additionally, the finally block executes before the code that follows the try…catch…finally statement. It is also important to note that the finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.
If the finally block returns a value, this value becomes the return value of the entire try…catch…finally production, regardless of any return statements in the try and catch blocks.

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

function f() {
  try {
    throw 'bogus';
  } catch(e) {
    console.log('caught inner "bogus"');
    throw e; // this throw statement is suspended until 
             // finally block has completed
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  console.log(f());
} catch(e) {
  // this is never reached! 
  // while f() executes, the `finally` block returns false, 
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}

Output:
// caught inner "bogus"
// false

4. Difference between a for...of loop and a for...in loop. 
While for...in iterates over property names, for...of iterates over property values:

Example:
const arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs 3, 5, 7
}

5. Composition
Promise.resolve() and Promise.reject() are shortcuts to manually create an already resolved or rejected promise respectively.
Promise.all() and Promise.race() are two composition tools for running asynchronous operations in parallel.

6. Weakmap
The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

7. Weakset
WeakSet objects are collections of objects. Just as with Sets, each object in a WeakSet may occur only once; all objects in a WeakSet's collection are unique.

The main differences to the Set object are:

WeakSets are collections of objects only.  They cannot contain arbitrary values of any type, as Sets can.
The WeakSet is weak, meaning references to objects in a WeakSet are held weakly. If no other references to an object stored in the WeakSet exist, those objects can be garbage collected.

8. HTML, CSS and JavaScript

HTML is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.

CSS is a language of style rules that we use to apply styling to our HTML content, for example setting background colours and fonts, and laying out our content in multiple columns.

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. 
JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved. 

9. What is the advantage of having separate JavaScript Files? 
The benefit of a separate file is that the browser will download it and store it in its cache. Other pages that reference the same script will take it from the cache instead of downloading it, so the file is actually downloaded only once. That reduces traffic and makes pages faster.

10. Same Origin Policy
Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other if they come from different sites (from a different domain, protocol or port).

This is called the “Same Origin Policy”. To work around that, both pages must agree for data exchange and contain a special JavaScript code that handles it. We’ll cover that in the tutorial.

This limitation is, again, for the user’s safety. A page from http://anysite.com which a user has opened must not be able to access another browser tab with the URL http://gmail.com and steal information from there.

11. Automatic semicolon insertion
A semicolon may be omitted in most cases when a line break exists.

This would also work:
alert('Hello')
alert('World')

Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon insertion.
 
There are cases when a newline does not mean a semicolon. For example:

alert(3 +
1
+ 2);
 
 JavaScript does not assume a semicolon before square brackets [...].

12. use strict
The "use strict" directive was new in ECMAScript version 5.
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
With strict mode, you can not, for example, use undeclared variables.

13. Variable naming
There are two limitations on variable names in JavaScript:

    The name must contain only letters, digits, or the symbols $ and _.
    The first character must not be a digit.

Examples of valid names:

let userName;
let test123;

14. Object.assign()

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

Syntax
Object.assign(target, ...sources)

Sample Code:
const target = { a : 1, b : 2 };
const source = { b : 3, c : 4 };
const returnedTarget = Object.assign( target, source );
console.log( 'After Assgin - Target ' + JSON.stringify( target ) );
console.log( 'After Assign - Source ' + JSON.stringify( returnedTarget ) );

Output:
"After Assgin - Target {"a":1,"b":3,"c":4}"
"After Assign - Source {"a":1,"b":3,"c":4}"

Cloning:
const obj = { a : 1 };
const copy = Object.assign( {}, obj );
console.log( 'Obj is ' + JSON.stringify( obj ) );
console.log( 'Copy is ' + JSON.stringify( copy ) );

Output:
"Obj is {"a":1}"
"Copy is {"a":1}"

15. The “undefined” value
The special value undefined also stands apart. It makes a type of its own, just like null.
The meaning of undefined is “value is not assigned”.
If a variable is declared, but not assigned, then its value is undefined:
let age;
alert(age); // shows "undefined"

No comments:

Post a Comment