JS Interview Questions
What is a "closure" in JavaScript? Provide an example.
A closure is an inner function that has access to the variables in the outer (enclosing) function's scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function's scope, and (3) global variables.
Whats the difference between a library and framework? examples?
A library is a reusable piece of code which you use as it comes i.e provided methods A framework is a piece of code which dictates the architecture your project will follow. Once you choose a framework to work with, you have to follow the framework's code and design methodologies Library: jQuery Framework: React
What's a promise?
A promise represents the eventual result (value) of an asynchronous operation. It is a placeholder into which the resolved result value or rejected value (failure)
What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?
Although typeof bar === "object" is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object! Therefore, the following code will, to the surprise of most developers, log true (not false) to the console: var bar = null; console.log(typeof bar === "object"); // logs true! As long as one is aware of this, the problem can easily be avoided by also checking if bar is null: console.log((bar !== null) && (typeof bar === "object")); // logs false To be entirely thorough in our answer, there are two other things worth noting: First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be: console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); Second, the above solution will return true if bar is an array (e.g., if var bar = [];). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be: console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); However, there's one other alternative that returns false for nulls, arrays, and functions, but true for objects: console.log((bar !== null) && (bar.constructor === Object)); Or, if you're using jQuery: console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar))); ES5 makes the array case quite simple, including its own null check: console.log(Array.isArray(bar));
What will the code below output? Explain your answer. console.log(0.1 + 0.2); console.log(0.1 + 0.2 == 0.3);
An educated answer to this question would simply be: "You can't be sure. it might print out 0.3 and true, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results." The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out: 0.30000000000000004 false A typical solution is to compare the absolute difference between two numbers with the special constant Number.EPSILON: function areTheNumbersAlmostEqual(num1, num2) { return Math.abs( num1 - num2 ) < Number.EPSILON; } console.log(areTheNumbersAlmostEqual(0.1 + 0.2, 0.3));
ES5 vs ES6
ES6: template literals arrow functions var, let, const modules require import/export class declaration and inheritance
Explain Node's event loop
Node.js is an event-based platform. This means that everything that happens in Node is the reaction to an event. A transaction passing through Node traverses a cascade of callbacks. This provides a mechanism called an event loop.
Why Node JS?
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.
What will the code below output to the console and why? (function(){ var a = b = 3; })(); console.log("a defined? " + (typeof a !== 'undefined')); console.log("b defined? " + (typeof b !== 'undefined'));
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example. However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for: var b = 3; var a = b; But in fact, var a = b = 3; is actually shorthand for: b = 3; var a = b; As a result (if you are not using strict mode), the output of the code snippet would be: a defined? false b defined? true But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function. Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)
What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
The NaN property represents a value that is "not a number". This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4), or because the result of the operation is non-numeric. While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them. For one thing, although NaN means "not a number", its type is, believe it or not, Number: console.log(typeof NaN === "number"); // logs "true" Additionally, NaN compared to anything - even itself! - is false: console.log(NaN === NaN); // logs "false" A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(), but even using isNaN() is an imperfect solution. A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.
What will be the output when the following code is executed? Explain. console.log(false == '0') console.log(false === '0')
The code will output: true false In JavaScript, there are two sets of equality operators. The triple-equal operator === behaves like any traditional equality operator would: evaluates to true if the two expressions on either of its sides have the same type and the same value. The double-equal operator, however, tries to coerce the values before comparing them. It is therefore generally good practice to use the === rather than ==. The same holds true for !== vs !=.
What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?
The short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice. Some of the key benefits of strict mode include: Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source. Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error. Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error. Disallows duplicate parameter values. Strict mode throws an error when it detects a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down. Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g. var object = {foo: "bar", foo: "baz"};) but as of ECMAScript 2015 this is no longer the case. Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems). Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.
Write a sum method which will work properly when invoked using either syntax below. console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5
There are (at least) two ways to do this: METHOD 1 function sum(x) { if (arguments.length == 2) { return arguments[0] + arguments[1]; } else { return function(y) { return x + y; }; } } In JavaScript, functions provide access to an arguments object which provides access to the actual arguments passed to a function. This enables us to use the length property to determine at runtime the number of arguments passed to the function. If two arguments are passed, we simply add them together and return. Otherwise, we assume it was called in the form sum(2)(3), so we return an anonymous function that adds together the argument passed to sum() (in this case 2) and the argument passed to the anonymous function (in this case 3). METHOD 2 function sum(x, y) { if (y !== undefined) { return x + y; } else { return function(y) { return x + y; }; } } When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored. On the other hand, if the number of arguments passed is less than the number of arguments in the function definition, the missing arguments will have a value of undefined when referenced within the function. So, in the above example, by simply checking if the 2nd argument is undefined, we can determine which way the function was invoked and proceed accordingly.
What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries. Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows: (function($) { /* jQuery plugin code referencing $ */ } )(jQuery);
Discuss possible ways to write a function isInteger(x) that determines if x is an integer.
This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger() method is provided. The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values. With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following use of the bitwise XOR operator: function isInteger(x) { return (x ^ 0) === x; } The following solution would also work, although not as elegant as the one above: function isInteger(x) { return Math.round(x) === x; } Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation. Or alternatively: function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); } One fairly common incorrect solution is the following: function isInteger(x) { return parseInt(x, 10) === x; } While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe: > String(1000000000000000000000) '1e+21' > parseInt(1000000000000000000000, 10) 1 > parseInt(1000000000000000000000, 10) === 1000000000000000000000 false
what is webpack?
a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser Webpack takes modules with dependencies and generates static assets representing those modules
what is express?
a web application framework, written in javascript and hosted within the node.js runtime environment. helps serve applications
application vs viewstate
application- stored in memory on the server. applies to all users and sessions (doesn't go away after login) view- saves information from the user in hidden fields on the browser. page level only. state of information is stored in the client only (eg hidden form field)
difference between a class and a constructor
class declarations are not hoisted.
imperative vs declarative programming
imperative = oop declarative = logical
What is Node Js?
its a javascript runtime environment (server) that executes javascript code outside the browser.
What is state?
single source of truth for app. tells you everything thats going on in your page. a program is described as stateful if it is designed to remember preceding events or user interactions, the remembered information is called the state of the system.
how does the internet work?
works on the web request response cycle. request: -made of methods, headers (content-type, user-agent etc), and body (actual request being sent to server). response: -status code, headers (content-length etc), body