Top 26 JavaScript Interview Questions and Answers in 2018

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Explain what a callback function is and provide a simple example.

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed. function modifyArray(arr, callback) { // do something to arr here arr.push(100); // then execute the callback function that was passed callback(); } var arr = [1, 2, 3, 4, 5]; modifyArray(arr, function() { console.log("array has been modified", arr); });

How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1. function isInt(num) { return num % 1 === 0; } console.log(isInt(4)); // true console.log(isInt(12.2)); // false console.log(isInt(0.3)); // false

Explain event bubbling and how one may prevent it

Event bubbling is the concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. As a result, when clicking on a child element one may exhibit the handler of the parent activating. One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

What is IIFEs (Immediately Invoked Function Expressions)?

It's an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it's created: (function IIFE(){ console.log( "Hello!" ); })(); // "Hello!" This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

Explain Null and Undefined in JavaScript

JavaScript (and by extension TypeScript) has two bottom types: null and undefined. They are intended to mean different things: Something hasn't been initialized : undefined. Something is currently unavailable: null.

What does "use strict" do?

The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error: function doSomething(val) { "use strict"; x = val + 10; }` It will throw an error because x was not defined and it is being set to some value in the global scope, which isn't allowed with use strict The small change below fixes the error being thrown: function doSomething(val) { "use strict"; var x = val + 10; }

Write a function that would allow you to do this.

var addSix = createBase(6); addSix(10); // returns 16 addSix(21); // returns 27 Answer: You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber. function createBase(baseNumber) { return function(N) { // we are referencing baseNumber here even though it was declared // outside of this function. Closures allow us to do this in JavaScript return baseNumber + N; } } var addSix = createBase(6); addSix(10); addSix(21);

How would you add your own method to the Array object so the following code would work?

var arr = [1, 2, 3, 4, 5]; var avg = arr.average(); console.log(avg); Answer: JavaScript is not class based, but it is a prototype-based language. This means that each object is linked to another object, its prototype, and it inherits its methods. You can follow the prototype chain for each object up until you reach the null object which has no prototype. We need to add a method to the global Array object, and we will do this by modifying the Array prototype. Array.prototype.average = function() { // calculate sum var sum = this.reduce(function(prev, cur) { return prev + cur; }); // return sum divided by number of elements return sum / this.length; } var arr = [1, 2, 3, 4, 5]; var avg = arr.average(); console.log(avg); // => 3

What will the following code output?

0.1 + 0.2 === 0.3 Answer: This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

What is "closure" in javascript? Provide an example?

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope. The closure has access to variable in three scopes: Variable declared in his own scope Variable declared in parent function scope Variable declared in global namespace var globalVar = "abc"; // Parent self invoking function (function outerFunction (outerArg) { // begin of scope outerFunction // Variable declared in outerFunction function scope var outerFuncVar = 'x'; // Closure self-invoking function (function innerFunction (innerArg) { // begin of scope innerFunction // variable declared in innerFunction function scope var innerFuncVar = "y"; console.log( "outerArg = " + outerArg + "\n" + "outerFuncVar = " + outerFuncVar + "\n" + "innerArg = " + innerArg + "\n" + "innerFuncVar = " + innerFuncVar + "\n" + "globalVar = " + globalVar); // end of scope innerFunction })(5); // Pass 5 as parameter // end of scope outerFunction })(7); // Pass 7 as parameter innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace. Output of above code would be: outerArg = 7 outerFuncVar = x innerArg = 5 innerFuncVar = y globalVar = abc

Describe the Revealing Module Pattern design pattern

A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this: var Exposer = (function() { var privateVariable = 10; var privateMethod = function() { console.log('Inside a private method!'); privateVariable++; } var methodToExpose = function() { console.log('This is a method I want to expose!'); } var otherMethodIWantToExpose = function() { privateMethod(); } return { first: methodToExpose, second: otherMethodIWantToExpose }; })(); Exposer.first(); // Output: This is a method I want to expose! Exposer.second(); // Output: Inside a private method! Exposer.methodToExpose; // undefined An obvious disadvantage of it is unable to reference the private methods

What is the difference between anonymous and named functions?

Consider: var foo = function() { // anonymous function assigned to variable foo // .. }; var x = function bar(){ // named function (bar) assigned to variable x // .. }; foo(); // actual function execution x();

Could you explain the difference between ES5 and ES6

ECMAScript 5 (ES5): The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015): The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers. Here are some key differences between ES5 and ES6: Arrow functions & string interpolation: Consider: const greetings = (name) => { return `hello ${name}`; } and even: const greetings = name => `hello ${name}`; Const. Const works like a constant in other languages in many ways but there are some caveats. Const stands for 'constant reference' to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can't change the reference itself. const NAMES = []; NAMES.push("Jim"); console.log(NAMES.length === 1); // true NAMES = ["Steve", "John"]; // error Block-scoped variables. The new ES6 keyword let allows developers to scope variables at the block level. Let doesn't hoist in the same way var does. Default parameter values Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. // Basic syntax function multiply (a, b = 2) { return a * b; } multiply(5); // 10 Class Definition and Inheritance ES6 introduces language support for classes (class keyword), constructors (constructor keyword), and the extend keyword for inheritance. for-of operator The for...of statement creates a loop iterating over iterable objects. Spread Operator For objects merging const obj1 = { a: 1, b: 2 } const obj2 = { a: 2, c: 3, d: 4} const obj3 = {...obj1, ...obj2} Promises Promises provide a mechanism to handle the result

Check if a given string is a isomorphic

For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of string A to every char of string B. paper and title would return true. egg and sad would return false. dgg and add would return true. isIsomorphic("egg", 'add'); // true isIsomorphic("paper", 'title'); // true isIsomorphic("kick", 'side'); // false function isIsomorphic(firstString, secondString) { // Check if the same lenght. If not, they cannot be isomorphic if (firstString.length !== secondString.length) return false var letterMap = {}; for (var i = 0; i < firstString.length; i++) { var letterA = firstString[i], letterB = secondString[i]; // If the letter does not exist, create a map and map it to the value // of the second letter if (letterMap[letterA] === undefined) { letterMap[letterA] = letterB; } else if (letterMap[letterA] !== letterB) { // Eles if letterA already exists in the map, but it does not map to // letterB, that means that A is mapping to more than one letter. return false; } } // If after iterating through and conditions are satisfied, return true. // They are isomorphic return true; }

What is Hoisting in JavaScript?

Hoisting is the JavaScript interpreter's action of moving all variable and function declarations to the top of the current scope. There are two types of hoisting: variable hoisting - rare function hoisting - more common Wherever a var (or function declaration) appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout. var a = 2; foo(); // works because `foo()` // declaration is "hoisted" function foo() { a = 3; console.log( a ); // 3 var a; // declaration is "hoisted" // to the top of `foo()` } console.log( a ); // 2

What is Coercion in JavaScript?

In JavaScript conversion between different two build-in types called coercion. Coercion comes in two forms in JavaScript: explicit and implicit. Here's an example of explicit coercion: var a = "42"; var b = Number( a ); a; // "42" b; // 42 -- the number! And here's an example of implicit coercion: var a = "42"; var b = a * 1; // "42" implicitly coerced to 42 here a; // "42" b; // 42 -- the number!

Explain the difference between "undefined" and "not defined" in JavaScript

In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop execute thereafter. But If you use typeof undeclared_variable then it will return undefined. Before starting further discussion let's understand the difference between declaration and definition. var x is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need of memory allocation. var x; // declaring x console.log(x); //output: undefined var x = 1 is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which it's declared then assignment happen in order this term is called hoisting. A variable that is declared but not define and when we try to access it, It will result undefined. var x; // Declaration if(typeof x === 'undefined') // Will return true A variable that neither declared nor defined when we try to reference such variable then It result not defined. console.log(y); // Output: ReferenceError: y is not defined

How does the "this" keyword work? Provide some code examples.

In JavaScript this always refers to the "owner" of the function we're executing, or rather, to the object that a function is a method of. Consider: function foo() { console.log( this.bar ); } var bar = "global"; var obj1 = { bar: "obj1", foo: foo }; var obj2 = { bar: "obj2" }; foo(); // "global" obj1.foo(); // "obj1" foo.call( obj2 ); // "obj2" new foo(); // undefined

What is Scope in JavaScript?

In JavaScript, each function gets its own scope. Scope is basically a collection of variables as well as the rules for how those variables are accessed by name. Only code inside that function can access that function's scoped variables. A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

What is let keyword in JavaScript?

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

Explain equality in JavaScript

JavaScript has both strict and type-converting comparisons: Strict comparison (e.g., ===) checks for value equality without allowing coercion Abstract comparison (e.g. ==) checks for value equality with coercion allowed var a = "42"; var b = 42; a == b; // true a === b; // false Some simple equalityrules: If either value (aka side) in a comparison could be the true or false value, avoid == and use ===. If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===. In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

Explain Values and Types in JavaScript

JavaScript has typed values, not typed variables. The following built-in types are available: string number boolean null and undefined object symbol (new to ES6)

Explain the Prototype Design Pattern

The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype - or sample - object. The Prototype pattern is also referred to as the Properties pattern. An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object. Classical languages rarely use the Prototype pattern, but JavaScript being a prototypal language uses this pattern in the construction of new objects and their prototypes.

What does the term "Transpiling" stand for?

There's no way to polyfill new syntax that has been added to the language. So the better option is to use a tool that converts your newer code into older code equivalents. This process is commonly called transpiling, a term for transforming + compiling. Typically you insert the transpiler into your build process, similar to your code linter or your minifier. There are quite a few great transpilers for you to choose from: Babel: Transpiles ES6+ into ES5 Traceur: Transpiles ES6, ES7, and beyond into ES5

How would you create a private variable in JavaScript?

To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example: function func() { var priv = "secret code"; } console.log(priv); // throws error To access the variable, a helper function would need to be created that returns the private variable. function func() { var priv = "secret code"; return function() { return priv; } } var getPriv = func(); console.log(getPriv()); // => secret code

How to compare two objects in JavaScript?

Two non-primitive values, like objects (including function and array) held by reference, so both == and === comparisons will simply check whether the references match, not anything about the underlying values. For example, arrays are by default coerced to strings by simply joining all the values with commas (,) in between. So two arrays with the same contents would not be == equal: var a = [1,2,3]; var b = [1,2,3]; var c = "1,2,3"; a == c; // true b == c; // true a == b; // false For deep object comparison use external libs like deep-equal or implement your own recursive equality algorithm.


Set pelajaran terkait

Sherpath- Legal Implication Quiz

View Set

Cell biology 1.3 Membrane structure

View Set

(EXAM 1) Biomechanics of Elbow/Forearm

View Set

History of The Calendar - Origins - Systems - Uses

View Set