Interview Questions


1) What is ECMAScript ?
This is the official name given to the language standard that Netscape originally submitted to ECMA for standardization.
Despite the official name this language is more commonly referred to as JavaScript.


2) Is JavaScript a Strongly Typed programming language ?
No. Type conversions can be implicit. This has nothing to do with Strict Mode.
JavaScript is dynamically typed. Data types are detected at run-time not during compilation.
You can reuse and reassign variables to lots of different types.

var myVar = '100';  
myVar = 20 * myVar;
console.log( typeof(myVar) ); // "number"

3) What is Strict Mode ?
This is an option that can be used to force you to explicitly declare a variable before it can be used.
This allows you to place an entire file/script or just an individual function in a "strict" operating context.
Modules (ES 2015) are automatically placed in strict mode.

'use strict'

function fun_One() {
'use strict'
};

4) What is displayed in the Console ?
This expression is shorthand for "b = 3; var a = b;"

( function() { 
   var a = b = 3;
}) ();

// when strict mode is turned off
console.log( typeof(a) ); // "undefined" - because "a" defaults to local scope
console.log( typeof(b) ); // "number" - because "b" defaults to global scope

// when strict mode is turned on
console.log( typeof(a) ); // Run-time Error: variable undefined in strict mode

5) Can you give some examples of other actions that are prevented when using strict mode ?
*) The strings 'eval' and 'arguments' cannot be used as variable names.
*) Writing to a read-only property is not allowed.
*) The 'with' statement is not allowed.


6) What are 'undeclared' and 'undefined' variables ?
Undeclared variables - are those that do not exist and have not be declared. Reading the value from an undeclared variable will generate a runtime error.
Undefined variables - are those that have been declared but have not been given a value. Reading the value from an undefined variable will give you undefined.
If you declare a variable and do not assign a value to it, its value will be undefined.

var myUndefined; 
console.log( myUndefined ); // "undefined"
console.log( myUndeclared ); // Run-time Error: "myUndeclared" is not defined

7) Can you describe the difference between 'undefined' and 'null' ?
undefined - a variable that has not been given a value. It has not been initialised.
null - a variable that has been explicitly set to have no value.

var myVar1; 
myVar1 = null;
console.log( myVar1 );

If you compare undefined and null using either of the following lines, they will be equal.

if (null == undefined)        // return true 
if (null === undefined) // return true

null is also considered an object.

let myLet1 = null; 
console.log( typeof myLet1 === 'object' ) // true
let myLet2 = [];
console.log( toString.call(myLet2) === '[object Array]' ); // true
console.log( myLet2.constructor === Object );

8) Can you describe the different variable scopes ?
There are three scopes, global, function and block.
global scope - can be accessed from anywhere in the program
function scope - can be accessed only from within the function where it is declared
block scope - can be accessed only from within the block


9) How do you declare a variable ?
If you do not use the var keyword then it will be given global scope.
You can use the 'var' keyword to give your variable function scope.

myGlobal1 = 5;                    // variables are case sensitive 
var myVarGlobal2 = 10;
function fun_One() {
   myGlobal3 = 10 * 2;
   var myVarFunction1 = 10 * 2; // has function scope
};

10) Can you describe Variable Hoisting ?
JavaScript will automatically move all variable declarations to the top of their corresponding scope.
The initialisation will not be hoisted, only the declaration.

var myVar = 'Monday'  
function fun_One() {
   if (myVar === undefined) {
      var myVar = 'Tuesday'
   }
   console.log( myVar );
};
fun_One(); // Tuesday

The (var myVar) part of the (var myVar = 'Tuesday') is automatically moved above the if statement.
This creates a new variable "myVar" that has function scope declared inside the "fun_One" function.
This has the same name as the variable at the global scope and therefore takes precedence.


11) What is the 'typeof' operator ?
This is a unary operator that takes a single operand and returns a 'string' description of the data type.

console.log typeof ( 'Hello World' );  // 'string'  
console.log typeof ( 19.5 ); // 'number'
console.log typeof ( true ); // 'boolean'

var myFunction = function(x, y) {
    return x + y;
};
console.log typeof ( myFunction ) // 'function'

12) Can you give some examples of Value data types ?
Also known as primitive data types.

number          // integer and floating point 
string
boolean
symbol // added in ES 2015
null // represents an empty
undefined

13) Can you give some examples of Reference data types ?

Function 
Array
Object
Object - Number
Object - String
Object - Boolean

14) How can you check if a variable has a value ?
You can use the if keyword to check if a variable has a value.

if (myVar) { 
   // 0, NaN, "", null, undefined
}
else {
  // everything else
}

15) Can you describe the 'boolean' data type ?
This can contain the values true or false.

equals (==) 
not equals (!=)
null == undefined // true
false == 0; // true
 == 0; // true - type coerced
123' == 123 // true
boolean + number = addition

16) Can you explain the difference between the Boolean() function and the Boolean constructor ?
The Boolean() function can be used with primitive/literal values or with objects.
When used with literal values this function can be used to convert literal values to a 'boolean' data type.
When used with the 'new' keyword this function can be used as a constructor to create a Boolean object.

let bool1 = Boolean(false);           // typeof = boolean 
let bool2 = new Boolean(false); // typeof = object

17) Can you convert a 'boolean' data type to a 'string' data type ?

let myLetBool = false; 
let myLetStr;
myLetStr = myLetBool.toString();
myLetStr = false.toString();
myLetStr = String('false');

18) Can you convert a 'boolean' data type to a 'number' data type ?



19) Can you describe the logical operators ?

&& - and 
|| - or
! - not

JavaScript uses short-circuit evaluation


20) Can you describe the 'Symbol' data type ?
Added in ES 2015.
A symbol represents a unique identifier.
Using symbols guarantees uniqueness. The description is just a label.
Symbol conversion has to be explicit.

let myLetID1 = Symbol("id"); 
let myLetID2 = Symbol("id");
console.log( myLetID1 === myLetID2); // 'false'

Unlike Number, String and Boolean it is not possible to create an explicit Symbol object using the new keyword.


21) Is there a way of checking for equality ?
Yes. You can use the operators (==) and (!=).
The '==' operator checks for implicit type conversion.

null == undefined;   // true 
false == 0; // true
' == 0; // true
'123' == 123; // true
206 != 207; // false

22) Can you explain the following results ?

let myLet1 = [1,2,3]; 
let myLet2 = [1,2,3];
let myLet3 = "1,2,3";
myLet1 == myLet3; // true
myLet2 == myLet3; // true
myLet1 == myLet2; // false

23) Is there a way of checking for equality AND data type ?
Yes. You can use the operators (===) and (!==).
The '===' operator checks for explicit type conversion.

null === undefined            // false 
false === 0; // false
'' === 0; // false
123' === 123 // false

let myLetNum1 = 10;
let myLetNum2 = 10;
console.log( myLetNum1 == myLetNum2 ); // true
console.log( myLetNum1 === myLetNum2 ); // true

let myLetNum3 = new Number(10);
let myLetNum4 = new Number(10);
console.log( myLetNum3 == myLetNum4 ); // false
console.log( myLetNum3 === myLetNum4 ); // false

24) Can you describe the 'alert', 'prompt' and 'confirm' functions ?
This displays a message to the user in a modal window.

window.alert('this is a useful message'); 

This displays a textbox asking the user for input in a modal window.
The textbox can have a default value.

var promptResult = window.prompt('This is a prompt for information', 'default value'); 

This displays a question to the user asking them to choose either OK or Cancel.

var confirmResult = window.confirm('Do you confirm?'); 

25) Write a While loop ?
A while loop can execute zero or many times

var x = 10; 
while (x > 0) {
   x--;
   console.log('The value of x is ' + x);
};

26) Write a Do loop ?
A do loop executes at least once.
A do loop contains the keyword while.

var x = 0; 
do {
   x++;
   console.log('The value of x is ' + x);
} while (x > 4);

27) Can you describe the 'break' keyword ?
This provides a way to exit the current loop.
If you are in a nested loop this will only exit one level.

var text = ''";  
for (i = 0; i < 10; i++) {
  if (i === 3) {
      break;
   }
  text += "The number is " + i + "<br>";
};

28) Can you describe the 'continue' keyword ?
This continues with the next statement of the loop.

var text = '';  
for ( I = 0; I < 5; i++) {
   if (I === 3) {
      continue;
   }
   text += 'The number is ' + i + "<br>";
}

29) What is the 'delete' operator ?
The delete operator can be used to delete properties from an object.


30) Can you describe a Function ?
A function is a block of code designed to perform a specific task.
A function is a callable object
A function that is a member of an object is called a method
A function is executed when it is called (or invoked).
A function always returns a value.

function func1() { 
   return 10;
};
console.log( func1() ); // 10

31) Can you describe the 'return' statement ?
If a function contains a 'return' statement the function will stop executing.
If no specific value is returned by this statement then 'undefined' is returned.

function func1() { 
};
function func2() {
   return;
};
console.log( func1() ); // undefined
console.log( func2() ); // undefined

32) How many different ways can you create a function ?
*) Function declaration
*) Function expression
*) Function constructor
*) Arrow function


33) What is the difference between a Function Declaration and a Function Expression ?
Function declarations are hoisted to the top but function expressions are not.
You should always include a semicolon after a function declaraction and a function expression.

// function declaration always starts with the function keyword 
function myfunc1(one, two) {
   return one + two;
};

// function expression with assignment ?
let myfunc2 = function(one, two) {
   return one + two;
};
console.log ( myFunc1(10,5) ); // 15
console.log ( myFunc2(10,5) ); // 15

34) Can you describe the 'Function Constructor' ?
Functions can be defined using the 'function' keyword
Functions can also be defined using a built-in constructor called 'Function'.

var myFunc3 = new Function("one", "two", "return one + two"); 
console.log ( myFunc3(10,5) ); // 15

35) What is a Self-Executing Function ?
This is an anonymous function that is executed immediately and does not pollute the global namespace.
Also called an Immediately Invocable Function Expression ((IIFE).

(function() { 
}) ();

This could be written using the arrow function.

( () => { 
}) ();

The first pair of parentheses converts the function declaration into a function expression.
The second pair of parentheses executes the function.
There is alternative syntax that can be used.

(function() { 
}() ); // douglas crockford

Another alternative is to prefix the function expression with any unary operator


36) Can you explain the difference between 'Assigning' an anonymous function and 'Executing' an anonymous function.

// assigning 
let myfun1 = function() {
}();
// executing
let myfun1 = ( function() {
}() );

37) Can you have Optional Arguments ?
Yes. All arguments are optional by default. If you do not pass in an argument, its parameter will be undefined.
Also if you pass in too many arguments, they will just be ignored.
This has benefits as well as drawbacks.


38) Can you describe the 'arguments' object ?
This is an array-like object that is accessible from inside functions that contains the values of the arguments passed to that function.

function func1 (a, b) { 
   console.log( arguments[0] ); // output: 1
   console.log( arguments[1] ); // output: 2
}
func1(1,2);

39) What is displayed in the Console ?

console.log( mul(2)(3)(4) ); 
function mul (x) {
   return function (y) { // anonymous function
      return function (z) { // anonymous function
         return x + y + z;
      };
   };
};

40) What is displayed in the Console ?

var myObject = { 
   foo: "one";
   func: function(){
      var self = this;
      console.log( this.foo );
      console.log( self.foo );
      ( function() {
         console.log( this.foo ); // this is undefined
         console.log( self.foo );
      }() );
   }
};
myObject.func();

41) Can you describe a Nested Function ?
It is possible to nest function declarations inside function declarations.
Nested functions are private to the function in which they are defined

function multiplySomeNumbers(arg1, arg2) { 
   return doubleThis(arg1) / arg2;
   function doubleThis(arg3) {
      var result = arg3 * 2;
      return result;
   };
};

42) Can you give some examples of built-in Objects ?

global 
Function
Object
Array
Math
Date
RegExp
JSON
Error

43) How many different ways are there to create Objects ?
*) Object Literal
*) Object.create
*) Function constructor
*) ES 2015 class keyword

var ob2 = {};    // preferred 
var obj1 = new Object();

44) Write code to create an Object Prototype ?
Javascript (ES 2009) used functions as classes

function Person(name, age) { 
  this.name = name;
  this.age = age;
};
var you = new Person('You', 24);

45) What are Object Prototypes ?
All JavaScript objects inherit properties and methods from a prototype.
The prototype property allows you to add new properties and methods to existing objects.

function Person( firstname, lastname ) { 
   this.firstname = firstname;
   this.lastname = lastname;
};

// adds a property
Person.prototype.age = 32;

// adds a method
Person.prototype.name = function() {
   return this.firstname + ' ' + this.lastname;
}

46) What is the syntax for accessing object properties ?

obj.name = 'Russell';  
var name = obj.name;
obj['name'] = 'Russell';
var name = obj['name'];

47) What is the 'this' keyword used for ?
The 'this' keyword refers to the object from where it is called.

var obj = { 
   val: 'hello',
   myFunction: function() {
      console.log( this.val );
   }
};
var obj1 = new obj();
obj.myFunction();

The 'this' keyword provides a way of referring back to the object that is associated with it.
The 'this' keyword is used as a mechanism to reach into the containing object for the properties on that object.
How the function is executed determines what the 'this' keyword refers to.

var obj = { 
   var _this = this;
   _this.val: 'hello',
   _this.myFunction: function() {
      console.log( _this.val );
   }
};
var obj2 = new obj();
obj.myFunction();

48) What is a 'closure' ?
A closer is an inner scope which has access to all the variables defined outside of its block.
An inner object does have access to the local variables of its parent function.


49) Can you think of any disadvantages to creating private methods ?
Private methods are very memory inefficient because a new copy of the method is created for every instance.

var = myClass function(text) { 
   this.name = text;

   // private method
   var myPrivate = function() {
      this.name = this.name.UpperCase();
   };

   // public method
   this.myPublic = function() {
   };
};

50) Write code to add methods to classes ?
It is possible to attach functions to objects

function makePerson(first, last) { 
  return {
    this.first = first,
    this.last = last,

    this.fullName = function() {
      return this.first + ' ' + this.last;
    },

    this.fullNameReversed = function() {
      return this.last + ', ' + this.first;
    }
  };
}
s = makePerson('Russell', 'Smith');
s.fullName(); // "Russell Smith"
s.fullNameReversed(); // "Smith, Russell"

51) How would you create a module using an Immediately Invoked Function Expression ?
This is called "Revealing Module Pattern".
This encapsulates private variables and methods in a closure scope.

var Module = ( function() { 
   var _fullname = "Russell Proctor";
   function setMyPrivateFullName(newValue) {
      _fullName = newValue;
   }
   function getMyPrivateFullName() {
      return _fullname;
   }

   return {
      setFullName : setMyPrivateFullName,
      getFullName : getMyPrivateFullName
   };
}) ();
console.log( Module.getFullName() );
Module.setFullName("Another Name");
console.log( Module.getFullName() );

52) How would you create a module using the CommonJS approach ?
(require and module.exports)
This is the approach used by Node.js

const { a, b} = require('module-name');  
exports.method = str => str.toUpperCase();

53) How would you create a module using the Asynchronous Module Definition (AMD) ?
define and require


54) How would you create a module using ES 2015 ?
The variables and functions in a module are not available anywhere else unless the module explicitly exports them.


55) What is a Promise Object ?
The promise object (or deferred object) is a way of scheduling work to be done on a value that might not yet be obtained.
This lets you write non-blocking logic that executes asynchronously without having to write any plumbing code.
The promise object allows you to chain operations together.
The promise object is implemented in WinJS and JQuery.
The promise object can be in one of three states:
pending -
resolved -
rejected -


56) Write code to create a promise object using JQuery ?
You can create a promise object by using the $.Deferred method.
There are a number of methods available on this Deferred object

resolve - 
resolvewith - passes data to the promises object subscribers
notify -
notifywith - passes data to the promises object subscribers
reject -
rejectwith - passes data to the promises object subscribers
promise -

There are a number of methods available on the Promise object

done - 
fail -
always -
pipe -
progress -
state -
then -

function timeoutAsync(milliseconds) { 
    var deferred = $.Deferred();
    setTimeout(function () { deferred.resolve(); }, milliseconds); // run this code when the time has expired
    return deferred.promise(); // changes the state of the promise object to resolved
};
function abcAsync() {
    var promise = timeoutAsync(2000);
    promise.done(function () { alert('done!') });
    return promise; // you should always return a promise
};

57) Write code that executes if the promise object fails ?
You can use the fail method to execute code when the asynchronous call fails.

function abcAsync() { 
    var promise = timeoutAsync(2000);
    promise.fail(function () { alert('failed!') });
    return promise;
};

58) Write code that executes regardless of success or failure ?

function abcAsync() { 
    var promise = timeoutAsync(2000);
    promise.always(function () { alert('this always runs!') });
    return promise;
};

59) Write code that executes chaining using nesting ?
When you want to chain several asynchronous calls together you can nest them

function abcAsync() { 
    var firstPromise = timeoutAsync(2000);
    firstPromise.done(function () {
        var secondPromise = timeoutAsync(3000);
        secondPromise.done(function () {
            var thirdPromise = timeoutAsync(4000);
            thirdPromise.done( function () { alert('done!') } );
            });
        });
    });
    return firstPromise;
};

60) Write code that executes chaining using the pipe method ?

function abcAsync() { 
    var firstPromise = timeoutAsync(2000);
    var secondPromise = firstPromise.pipe(function () {
        return timeoutAsync(3000);
    });
    var thirdPromise = secondPromise.pipe(function () {
        return timeoutAsync(4000);
    });
    thirdPromise.done(function () { alert('done!') });
    return thirdPromise;
};

61) Can you give some examples of JQuery AJAX functions ?
$.get() - load data from the server using a HTTP GET request
$.post() - load data from the server using a HTTP POST request
$.ajax() - perform an asynchronous HTTP (Ajax) request
All these functions and methods use XMLHttpRequest under the hood.


62) Write code to make an asynchronous AJAX call using XMLHttpRequest ?

function fetchAjaxAsync(url, callback, errorCallback) { 
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        processResult();
      }
      else {
        errorCallback(new Error(xhr.statusText));
      }
   }
  }
  xhr.open(url, "GET", true);
  xhr.send();
}

63) Write code to make an asynchronous AJAX call using the Fetch API ?
This API provides a global fetch method (window.fetch)
The Fetch API uses promises so you can chain multiple calls together instead of nesting them.

fetch(url). 
   then( function (response) {
      return response.json()
   })
   .then( function (myJSON) {
      console.log( JSON.stringify(myJSON) )
   })

64) What is Namespacing and how is it used ?
?


65) When should you use the setTimeout, setInterval and clearInterval functions ?
?


66) What are the disadvantages to using innerHTML ?
) content is replaced everywhere
) unable to append to the existing content
) does not provide validation so it is possible to insert invalid HTML


67) Can you explain the 'window.onload' and 'onDocumentReady' events ?
window.onload - this is only run once all the information on the page has been loaded.
onDocumentReady - loads the code after the DOM has loaded.


68) What are some of the new features available in ES 2015 ?
Support for constants
block scope support for constants and functions
classes
promises
arrow functions
enhanced object properties
extended literals
template literals
modules (import /export)
destructuring assignment


69) What is the 'Spread' operator in ES 2015 ?
The spread operator '...' can take either an array or an object and expand it into its set of Items.
For arrays this operator lets you drop an array inside another array and get its values.
In the array context, this operator is also called the 'spread element'.

const array1 = [1,2]; 
const array2 = [...array1, 3, 4];
// array2 = [1, 2, 3, 4]

For objects this operator is the equivalent of Object.assign, copying the values of one object into a new object.

const object1 = { a:1, b:2}; 
const object2 = { c:3, ...Object1 };
// object2 = { a:1, b:2, c:3 }

70) Can you explain the difference between Java and JavaScript ?
Java - is a complete and comprehensive programming language
JavaScript - is a client-side scripting language


71) What is JQuery ?
JQuery is a JavaScript library that works across all browsers.
It makes things like HTML document traversal and manipulation, event handling and AJAX much easier.
The library takes common tasks and wraps them into small reusable methods.


72) What is Node.js ?
This platform is built on the Google Chrome JavaScript runtime and lets you write code that executes on the back-end server.
nodejs.org , npmjs.com/package


73) What is NPM ?
Alternatives: Yarn, Bower
This is an abbreviation for Node Package Manager.
NPM is a repository of JavaScript packages (or modules) which can be easily reused by other developers using a command-line tool.


74) What is NPX ?
This is a package runner for Node Package Manager.
NPX was added in NPM 5.2
This is a replacement for installing global packages.
It encourages you to install them locally but still be able to run them as if they were global.


75) What is Webpack ?
Alternative: Browserify
Web Pack is a module bundler for JavaScript applications.
webpack.js.org/concepts
If you need a configuration file when working with webpack you can create a webpack.config.js file in the root folder.
If the file is found webpack will automatically use it.


76) What is Babel ?
Babel is a JavaScript compiler that lets you use JavaScript ES 2015 (ES6) features and transpiles the code to standard ES 2009 (ES5) code.
This lets you use the latest features without worrying about older browsers that do not support ES 2015.

babel-loader 
babel-core

77) What is Gulp ?
Alternative: Grunt
Gulp is a JavaScript task runner that can be used to automate repetitive tasks such as minification, unit testing and compilation.


78) What is Transpiling ?
This term means taking source code written in one language and transforming it into another language that has the same (or similar) level of abstraction.
The best example is compiling TypeScript to JavaScript.


79) What is Vue ?
Vue is a JavaScript framework which is being developed and maintained by the open source community.
In the context of MVC (Model View Controller), Vue is just the View.


80) What is Angular ?
Angular is a JavaScript framework being developed by Google.
It lets you extend the HTML syntax to include your components and data binding.
In the context of MVC (Model View Controller), Angular is all three.
Angular1 = Angular JS
The latest version of Angular is called Angular 4.


81) What is Yeoman ?
This is a command-line scaffolding tool that lets you quickly assemble a web project that has all the required components and dependencies.

npm install generator-office 
yo office

82) What is JSON ?
JavaScript Object Notation is a lightweight data-interchange format and is easy for code to parse and generate.
JSON is built on two structures. A collection of name/value pairs and an ordered list of values.


83) What is YAML ?
YAML is a superset of JSON and is a human friendly data serialisation standard.
This is similar to XML.


84) What is AJAX ?
AJAX is the acronym for Asynchronous JavaScript and Xml
This refers to a set of techniques used on the client side to create asynchronous web applications.



© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrev