JS
What will the code below output to the console and why ? console.log(1 + "2" + "2"); console.log(1 + +"2" + "2"); console.log(1 + -"1" + "2"); console.log(+"1" + "1" + "2"); console.log( "A" - "B" + "2"); console.log( "A" - "B" + 2);
"122" string "32" numeric + string "02" numeric + string "112" string "NaN2" the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN NaN: any operator applied to NaN with any other numeric operand will still yield NaN The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed.
What will the code below output to the console and why? var arr1 = "john".split(''); var arr2 = arr1.reverse(); var arr3 = "jones".split(''); arr2.push(arr3); console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1)); console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
"array 1: length=5 last=j,o,n,e,s" "array 2: length=5 last=j,o,n,e,s" arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e','s'] ]) after the above code is executed for the following reasons: 1. Calling an array object's reverse() method doesn't only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1). 2. The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.
Consider the following code snippet: for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); }); document.body.appendChild(btn); } (a) What gets logged to the console when the user clicks on "Button 4" and why? (b) Provide one or more alternate implementations that will work as expected.
(a) No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point that the onclick method is invoked (for any of the buttons), the for loop has already completed and the variable i already has a value of 5. (Bonus points for the interviewee if they know enough to talk about how execution contexts, variable objects, activation objects, and the internal "scope" property contribute to the closure behavior.) (b) The key to making this work is to capture the value of i at each pass through the for loop by passing it into a newly created function object. for (let i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); }); document.body.appendChild(btn); }
What would the following lines of code output to the console? console.log("0 || 1 = "+(0 || 1)); console.log("1 || 2 = "+(1 || 2)); console.log("0 && 1 = "+(0 && 1)); console.log("1 && 2 = "+(1 && 2));
0 || 1 = 1 (true) 1 || 2 = 1 (true) 0 && 1 = 0 (false) 1 && 2 = 2 (true; when an expression is evaluated as "true", then the expression itself is returned (reason it isn't '1')
Consider the following code. What will the output be, and why? (function () { try { throw new Error(); } catch (x) { var x = 1, y = 2; console.log(x); } console.log(x); console.log(y); })();
1 undefined 2 var statements are hoisted (without their value initialization) to the top of the global or function scope it belongs to, even when it's inside a with or catch block. However, the error's identifier is only visible inside the catch block.
What is the result of the following code? Explain your answer. function printing() { console.log(1); setTimeout(function() { console.log(2); }, 1000); setTimeout(function() { console.log(3); }, 0); console.log(4); } printing();
1 4 3 2 UI events (such as click, scroll, and so on), Ajax callbacks, and callback provided to setTimeout() and setInterval() are all processed one at a time by the event loop. Therefore, when calling the setTimeout() function the callback provided is queued, even if the delay specified is zero. The callback stays in the queue until the time specified has elapsed and the engine is ready to perform the action (i.e. if it isn't performing another action at the moment). So, although a callback passed to setTimeout() is delayed by zero milliseconds, it'll be queued and executed after other non-delayed statements declared in the same function.
Write an isPrime() function that returns true if a number is prime and false otherwise.
1. you can't trust the data type passed 2. negative numbers aren't prime. Same goes for 1 and 0. 3. the only even number that is prime is 2. 4. if a number isn't divisible by 2, it isn't divisible by 4, 6, 8, and so on. Therefore your loop must skip those numbers 5. you don't need to test numbers greater than the square root of the input number function isPrime(number) { if (typeof number !== 'number' || !Number.isInteger(number)) { return false; } if (number < 2) { return false; } if (number === 2) { return true; } else if (number % 2 === 0) { return false; } var squareRoot = Math.sqrt(number); for(var i = 3; i <= squareRoot; i += 2) { if (number % i === 0) { return false; } } return true; }
Testing your this knowledge in JavaScript: What is the output of the following code? var length = 10; function fn() { console.log(this.length); } var obj = { length: 5, method: function(fn) { fn(); arguments[0](); } }; obj.method(fn, 1);
10 2 Why isn't it 10 and 5? As fn is passed as a parameter to the function method, the scope (this) of the function fn is window. var length = 10; is declared at the window level. method is bound to Object obj, and obj.method is called with parameters fn and 1. Though method is accepting only one parameter, while invoking it has passed two parameters; the first is a function callback and other is just a number. When fn() is called inside method, which was passed the function as a parameter at the global level, this.length will have access to var length = 10 (declared globally) not length = 5 as defined in Object obj. arguments[0]() is nothing but calling fn(). Inside fn now, the scope of this function becomes the arguments array, and logging the length of arguments[] will return 2.
(function() { var a = b = 5; })(); console.log(b); What will be printed on the console?
5 the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope.
What is a "closure" in JavaScript?
A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope. The closure has access to variables in three scopes: - Variables declared in their own scope - Variables declared in a parent function scope - Variables declared in the global namespace
What is a "closure" in JavaScript?
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. var globalVar = "xyz"; (function outerFunc(outerArg) { var outerVar = 'a'; (function innerFunc(innerArg) { var innerVar = 'b'; console.log( "outerArg = " + outerArg + "\n" + "innerArg = " + innerArg + "\n" + "outerVar = " + outerVar + "\n" + "innerVar = " + innerVar + "\n" + "globalVar = " + globalVar); })(456); })(123); In the above example, variables from innerFunc, outerFunc, and the global namespace are all in scope in the innerFunc. The above code will therefore produce the following output: outerArg = 123 innerArg = 456 outerVar = a innerVar = b globalVar = xyz
What is the difference between a method and a function in javascript?
A function is a piece of code that is called by name and it is not associated with any object, nor defined inside an object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value). E.g.: /* Function definition*/ function myFunc() { /* Do some stuff; */ } myFunc();/* Calling the function */ A method is a piece of code that is called by name and is defined inside an object. It is almost identical to a function except that it is always associated with an object and operating only on data inside it. var methodObject = { attribute: "xyz", display: function () { /* Method*/ console.log(this.attribute); } }methodObject.display(); /* Calling the method */
9. What are the pros and cons of monolithic vs microservice architectures?
A monolithic architecture means that your app is written as one cohesive unit of code whose components are designed to work together, sharing the same memory space and resources. A microservice architecture means that your app is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other across potentially many separate machines.
What is JavaScript self-invoking anonymous function?
A self-invoking anonymous function runs immediately when we define it and doesn't have a name. E.g. (function() { console.log("this will print automatically"); })();
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." 0.30000000000000004 false
How do you check if an object is an array or not?
Array.isArray(arrayList);
How does Array() differ from [] while creating a JavaScript array?
Both the Array() and [] work almost the same in JavaScript. If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Even if we pass a string or a list of strings as arguments, the result will be similar. However, they differ when the input argument is of integer type. In that case, the statement will create an uninitialized array of size n. Whereas, the [n] statement will create an array of size 1 and assign n as the value of the first element.
Explain the difference between class inheritance and prototypal inheritance.
Class Inheritance: A constructor function instantiates an instance via the "new" keyword. This new instance inherits properties from a parent class. Prototypal Inheritance: An instance is created by cloning an existing object that serves as a prototype. Instances are typically instantiated via factory functions, object literals, or Object.create(). Instances may be composed from many different source objects, allowing for easy selective inheritance.
Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function. The arguments to the function should be: a DOM element a callback function (that takes a DOM element as its argument)
Depth-first-search algo function Traverse(p_element,p_callback) { p_callback(p_element); var list = p_element.children; for (var i = 0; i < list.length; i++) { Traverse(list[i],p_callback); // recursive call } }
What is event bubbling?
Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM); that is, all child node events are automatically passed to its parent nodes. The benefit of this method is speed, because the code only needs to traverse the DOM tree once. This is useful when you want to place more than one event listener on a DOM element since you can put just one listener on all of the elements, thus code simplicity and reduction. One application of this is the creation of one event listener on a page's body element to respond to any click event that occurs within the page's body.
What is prototype property in JavaScript?
Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function's prototype so that it becomes available to instances of that function.
How are errors gracefully handled in JavaScript?
Exceptions that occur at runtime can be handled via try/catch/finally blocks; this allows you to avoid those unfriendly error messages. The finally block is optional, as the bare minimum to use is try/catch. Basically, you try to run code (in the try block between the braces), and execution is transferred to the catch block of code when/if runtime errors occur. When the try/catch block is finally done, code execution transfers to the finally code block. try { // do something } catch (e) { // do something with the exception } finally { // This code block always executes whether there is an exception or not. }
pros and cons of functional programming
FP Pros: Using the functional paradigm, programmers avoid any shared state or side-effects, which eliminates bugs caused by multiple functions competing for the same resources. FP Cons: FP has a much steeper learning curve than OOP because the broad popularity of OOP has allowed the language and learning materials of OOP to become more conversational, whereas the language of FP tends to be much more academic and formal.
2. What is functional programming?
Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data. Good to hear: - Pure functions / function purity. - Avoid side-effects. - Simple function composition. - Examples of functional languages: Lisp, ML, Haskell, Erlang, Clojure, Elm, F Sharp, OCaml, etc... - Mention of features that support FP: first-class functions, higher order functions, functions as arguments/values.
What are global variables?
Global variables are available throughout your code: that is, the variables have no scope. Local variables scope, on the other hand, is restricted to where it is declared (like within a function). The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable. Most JavaScript developers avoid globals. One reason why is they're averse to naming conflicts between local and globals, Also, code that depends on globals can be difficult to maintain and test.
What is the instanceof operator in JavaScript? What would be the output of the code below? function foo(){ return foo; } new foo() instanceof foo;
Here, instanceof operator checks the current object and returns true if the object is of the specified type. For Example: var dog = new Animal(); dog instanceof Animal // Output : true Here dog instanceof Animal is true since dog inherits from Animal.prototype.
What is the difference between undefined and not defined in JavaScript?
In JavaScript, if you try to use a variable that has not been declared, then JavaScript will throw an error var x is not defined and the script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined. Additionally, doing console.log(x), when x has been declared, but not defined (doesn't have a value yet), will also print undefined.
What is function hoisting in JavaScript? Function Expression var foo = function foo(){ return 12; };
In JavaScript, variable and functions are hoisted. Let's take function hoisting first. Basically, the JavaScript interpreter looks ahead to find all variable declarations and then hoists them to the top of the function where they're declared. Behind the scene of the code above looks like this: var foo = undefined; foo(); // Here foo is undefined foo = function foo(){ / Some code stuff } var foo = undefined; foo = function foo(){ / Some code stuff } foo(); // Now foo is defined here
7. What does "favor object composition over class inheritance" mean?
It means that code reuse should be achieved by assembling smaller units of functionality into new objects instead of inheriting from classes and creating object taxonomies. Pros: - Make code more flexible. - Avoid class hierarchies. - Avoid tight coupling.
for (let i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); } What will this code print?
It will print 0 1 2 3 4, because we use let instead of var here. The variable i is only seen in the for loop's block scope.
What is JavaScript's this keyword?
JavaScript's this keyword normally refers to the object that owns the method, but it depends on how a function is called. Basically, it points to the currently in scope object that owns where you are in the code. When working within a Web page, this usually refers to the Window object. If you are in an object created with the new keyword, the this keyword refers to the object being created. When working with event handlers, JavaScript's this keyword will point to the object that generated the event.
Microservice pros/cons
Microservice pros: Microservice architectures are typically better organized, since each microservice has a very specific job, and is not concerned with the jobs of other components. Decoupled services are also easier to recompose and reconfigure to serve the purposes of different apps (for example, serving both the web clients and public API). Microservice cons: As you're building a new microservice architecture, you're likely to discover lots of cross-cutting concerns that you did not anticipate at design time. A monolithic app could establish shared magic helpers or middleware to handle such cross-cutting concerns without much effort. In a microservice architecture, you'll either need to incur the overhead of separate modules for each cross-cutting concern, or encapsulate cross-cutting concerns in another service layer that all traffic gets routed through.
Monolithic pros/cons
Monolithic Pros: The major advantage of the monolithic architecture is that most apps typically have a large number of cross-cutting concerns, such as logging, rate limiting, and security features such audit trails and DOS protection. When everything is running through the same app, it's easy to hook up components to those cross-cutting concerns. There can also be performance advantages, since shared-memory access is faster than inter-process communication (IPC). Monolithic cons: Monolithic app services tend to get tightly coupled and entangled as the application evolves, making it difficult to isolate services for purposes such as independent scaling or code maintainability. Monolithic architectures are also much harder to understand, because there may be dependencies, side-effects, and magic which are not obvious when you're looking at a particular service or controller.
object-oriented programming pros and cons
OOP Pros: It's easy to understand the basic concept of objects and easy to interpret the meaning of method calls. OOP tends to use an imperative style rather than a declarative style, which reads like a straight-forward set of instructions for the computer to follow. OOP Cons: OOP Typically depends on shared state. Objects and behaviors are typically tacked together on the same entity, which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions.
What is the drawback of creating true private methods in JavaScript?
One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance.
1. Can you name two programming paradigms (a way to classify programming languages based on their features) important for JavaScript app developers?
Prototypal inheritance (also: prototypes, OLOO). Functional programming (also: closures, first class functions, lambdas).
5. When is classical inheritance an appropriate choice?
Rarely, almost never, or never. A single level is sometimes OK, from a framework base-class such as React.Component. "Favor object composition over class inheritance."
Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example: console.log('hello'.repeatify(3)); Should print hellohellohello.
String.prototype.repeatify = //how to not override possible already defined functions String.prototype.repeatify || function(times) { var str = ''; for (var i = 0; i < times; i++) { str += this; } return str; };
Consider the two functions below. Will they both return the same thing? function foo1() { return { bar: "hello" }; } function foo2() { return { bar: "hello" }; }
Surprisingly, no. JavaScript is very fogiving of missed semi-colons, so when you write a statement in new line without ending it with a ;, it is automatically inserted by the engine. That will result in foo2 returning undefined, while foo1 an object.
10. What is asynchronous programming, and why is it important in JavaScript?
Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O. Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations. User interfaces are asynchronous by nature, and spend most of their time waiting for user input to interrupt the event loop and trigger event handlers.
What is the difference between == and ===?
The == operator checks equality only, whereas === checks equality and data type i.e. the values must be of the same type.
What will be the output of the following code? var Employee = { company: 'Acme' } var employee1 = Object.create(Employee); delete employee1.company console.log(employee1.company);
The above code will output Acme. For the object employee1, company is a prototype property that can't be deleted using the delete operator.
What will be the output of the following code? var z = 1, y = z = typeof y; console.log(y);
The above code will output undefined. The order of execution with the = operator is right to left, which means typeof y will execute first and will return undefined, which will then pass to z and y. Thus, console.log(y); will print undefined.
What is the result of the following code? Explain your answer. var fullname = 'John Doe'; var obj = { fullname: 'Colin Ihrig', prop: { fullname: 'Aurelio De Rosa', getFullname: function() { return this.fullname; } } }; console.log(obj.prop.getFullname()); var test = obj.prop.getFullname; console.log(test());
The code prints Aurelio De Rosa and John Doe In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.
Consider the following code: var nodes = document.getElementsByTagName('button'); for (var i = 0; i < nodes.length; i++) { nodes[i].addEventListener('click', function() { console.log('You clicked element #' + i); }); } What will be printed on the console if a user clicks the first and the fourth button in the list? Why?
The code prints two times You clicked element #NODES_LENGTH where NODES_LENGTH is the number of the nodes retrieved. The reason is that after the for loop is completed, the variable i assumes a value equal to the length of the nodes list. In addition, because i was in scope at the time the code attached the handler, the variable belongs to handler's closure. As you'll recall, the value of the variables in closures isn't static, hence the value of i isn't the value at the time the handler was added (0 for the first button in the list, 1 for the second, and so on). At the time the handler will be executed, on the console will be printed the current value of the variable i, that is equal to the length of the nodes list.
What will be the output of the following code: for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); } Explain your answer. How could the use of closures help here?
The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5. The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5. Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows: for (var i = 0; i < 5; i++) { (function(x) { setTimeout(function() { console.log(x); }, x * 1000 ); })(i); } OR: for (let i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }
What will be the output of the code below? var bar = true; console.log(bar + 0); console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false);
The code will output 1, "truexyz", 2, 1. Here's a general guideline for addition operators: Number + Number -> Addition Boolean + Number -> Addition Boolean + Number -> Addition Number + String -> Concatenation String + Boolean -> Concatenation String + String -> Concatenation
What will the following code output to the console: console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10)); Explain your answer.
The code will output the value of 10 factorial (i.e., 10!, or 3,628,800). The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1. Here, therefore, is what this does: f(1): returns n, which is 1 f(2): returns 2 * f(1), which is 2 f(3): returns 3 * f(2), which is 6 f(4): returns 4 * f(3), which is 24 f(5): returns 5 * f(4), which is 120 [...]
What is the value of typeof undefined == typeof NULL?
The expression will be evaluated to true, since NULL will be treated as any other undefined variable. Note: JavaScript is case-sensitive and here we are using NULL instead of null.
What do the following lines output, and why? console.log(1 < 2 < 3); console.log(3 > 2 > 1);
The first statement returns true which is as expected. The second returns false because of how the engine works regarding operator associativity for < and >. It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1. true has value 1, so it then compares 1 > 1, which is false.
What does the isNaN() function do?
The isNan() function returns true if the variable value is not a number.
Fix the previous question's issue so that the last console.log() prints Aurelio De Rosa.
The issue can be fixed by forcing the context of the function using either the call() or the apply() function. In the code below I'll use call() but in this case apply() would produce the same result: console.log(test.call(obj.prop));
What is the difference between declaring a function in the two formats below? var foo = function() { /* Some code */ }; function bar() { /* Some code */ };
The main difference is that foo is defined at run-time whereas bar is defined at parse time. E.g. /* Run-Time function declaration*/ foo(); /* Calling foo here will throw an error */ var foo = function() { console.log("Hi I am inside Foo"); }; /* Parse-Time function declaration * /bar(); /* Call bar function here, It will not give an Error */ function bar() {console.log("Hi I am inside Foo"); };
What is the difference between the function declarations below? var foo = function(){ // Some code }; function bar(){ // Some code };
The main difference is the function foo is defined at run-time whereas function bar is defined at parse time. An advantage of this first-one way of declaration is that you can declare functions based on certain conditions.
What is the output out of the following code? Explain your answer. var a={}, b={key:'b'}, c={key:'c'}; a[b]=123; a[c]=456; console.log(a[b]);
The output of this code will be 456 (not 123). The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]". As a result, a[b] anda[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].
Consider the code snippet below. What will the console output be and why? (function(x) { return (function(y) { console.log(x); })(2) })(1);
The output will be 1, even though the value of x is never set in the inner function. a closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an "inner function"; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function's variables. Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x, which is found to have a value of 1.
What will be the output of the following code? var output = (function(x){ delete x; return x; })(0); console.log(output);
The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don't affect local variables.
What will be the output of the following code? var x = 1; var output = (function(){ delete x; return x; })(); console.log(output);
The output would be 1. The delete operator is used to delete the property of an object. Here x is not an object, but rather it's the global variable of type number.
What will be the output of the code below? var y = 1; if (function f(){}) { y += typeof f; } console.log(y);
The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.
What will be the output of the code below? var trees = ["pine","apple","oak","maple","cherry"]; delete trees[3]; console.log(trees.length);
The output would be 5. When we use the delete operator to delete an array element it doesn't unset the element in that position of the array, but sets it to undefined instead. So, the array length is not affected by the delete operation. This holds true even if you deleted all elements of an array using the delete operator.
What will be the output of the code below? var trees = ["xyz","xxxx","test","ryan","apple"]; delete trees[3]; console.log(trees.length);
The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even if you deleted all elements of an array using the delete operator.
What will be the output of the code below? // NFE (Named Function Expression var foo = function bar(){ return 12; }; typeof bar();
The output would be Reference Error. A function definition can have only one reference variable as its function name To make the code above work, you can re-write it as follows: var bar = function(){ return 12; }; typeof bar(); or function bar(){ return 12; }; typeof bar();
What will be the output of code below? var salary = "1000$"; (function () { console.log("Original salary was " + salary); var salary = "5000$"; console.log("My New Salary " + salary); })();
The output would be undefined, 5000$. Newbies often get tricked by JavaScript's hoisting concept. In the code above, you might be expecting salary to retain its value from the outer scope until the point that salary gets re-declared in the inner scope. However, due to hoisting, the salary value was undefined instead. var salary = "1000$"; (function () { var salary = undefined; console.log("Original salary was " + salary); salary = "5000$"; console.log("My New Salary " + salary); })(); salary variable is hoisted and declared at the top in the function's scope. The console.log inside returns undefined. After the console.log, salary is redeclared and assigned 5000$.
What will be the output of the code below? var z = 1, y = z = typeof y; console.log(y);
The output would be undefined. According to the associativity rule, operators with the same precedence are processed based on the associativity property of the operator. Here, the associativity of the assignment operator is Right to Left, so typeof y will evaluate first , which is undefined. It will be assigned to z, and then y would be assigned the value of z and then z would be assigned the value 1.
What will be the output of the code below? var x = { foo : 1}; var output = (function(){ delete x.foo; return x.foo; })(); console.log(output);
The output would be undefined. The delete operator is used to delete the property of an object. Here, x is an object which has the property foo, and as it is a self-invoking function, we will delete the foo property from object x. After doing so, when we try to reference a deleted property foo, the result isundefined.
What will be the output of the code below? var Employee = { company: 'xyz' } var emp1 = Object.create(Employee); delete emp1.company console.log(emp1.company);
The output would be xyz. Here, emp1 object has company as its prototype property. The delete operator doesn't delete prototype property. Note: However, we can delete the company property directly from theEmployee object using delete Employee.company
What is the result of "10"+20+30 in JavaScript?
The result is 102030 because when using the + operator with a string, it acts as a string concatenation operator (not binary +). To make it work as expected, you should parse the "10" to integer before doing the +.
What's the result of executing this code and why. function test() { console.log(a); console.log(foo()); var a = 1; function foo() { return 2; } } test();
The result of this code is undefined and 2. The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don't retain any assigned value. So, at the time the variable a is printed, it exists in the function (it's declared) but it's still undefined. Stated in other words, the code above is equivalent to the following: function test() { var a; function foo() { return 2; } console.log(a); console.log(foo()); a = 1; } test();
What is Scope in JavaScript?
The scope determines the accessibility of variables, objects, and functions in particular part of your code. In JavaScript, the scope can be of two types. 1. Global Scope 2. Local Scope
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. - Prevents accidental globals - Eliminates this coercion (in strict mode, referencing a a this value of null or undefined throws an error.) - Disallows duplicate parameter values
Assuming d is an "empty" object in scope, say: var d = {}; ...what is accomplished using the following code? [ 'zebra', 'horse' ].forEach(function(k) { d[k] = undefined; });
The snippet of code shown above sets two properties on the object d. Ideally, any lookup performed on a JavaScript object with an unset key evaluates to undefined. But running this code marks those properties as "own properties" of the object. This is a useful strategy for ensuring that an object has a given set of properties. Passing this object to Object.keys will return an array with those set keys as well (even if their values are undefined).
What is the difference between undefined and null?
The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null.Null means empty or non-existent value which is used by programmers to indicate "no value"
If we have a JavaScript associative array var counterArray = { A : 3, B : 4 }; counterArray["C"] = 1; How can we calculate the length of the above associative array's counterArray?
There are no in-built functions and properties available to calculate the length of associative array object here. However, there are other ways by which we can calculate the length of an associative array object. We can calculate the length of an object by iterating through an object and by counting the object's own property: function getSize(object){ var count = 0; for(key in object){ // hasOwnProperty method check own property of object if(object.hasOwnProperty(key)) count++; } return count; }
What is the reason for wrapping the entire content of a JavaScript source file in a function block?
This is a common practice used in many popular JavaScript libraries (jQuery, Node.js, etc.). It creates a closure around the entire contents of the file which makes a private namespace and thereby avoids potential name clashes between different JavaScript modules and libraries.
What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
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.
How do JavaScript timers work? What is a drawback of JavaScript timers?
Timers allow you to execute code at a set time or repeatedly using an interval. This is accomplished with the setTimeout, setInterval, and clearInterval functions. The setTimeout(function, delay) function initiates a timer that calls a specific function after the delay; it returns an id value that can be used to access it later. The setInterval(function, delay) function is similar to the setTimeout function except that it executes repeatedly on the delay and only stops when cancelled. The clearInterval(id) function is used to stop a timer. Timers can be tricky to use since they operate within a single thread, thus events queue up waiting to execute.
8. What are two-way data binding and one-way data flow, and how are they different?
Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa. One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or "store" in React). Only the model has the access to change the app's state. The effect is that data always flows in a single direction, which makes it easier to understand. Note: React is one-way
How to call other class methods?
Using call() and apply() method we can use methods from different context to the current context. It is really helpful for code reusability and context binding. call(): is used to call a function with a given this value and arguments provided individually. apply(): is used to call a function with a given this value and arguments provided as an array.
Why would you use use strict at the beginning of a JavaScript source file?
Using strict is a way to enforce strict parsing and error handling of the JavaScript code at runtime. This means that code errors that would have otherwise been ignored or would have failed silently, will now generate errors or throw exceptions. Some benefits are: easier debugging; preventing accidental globals, eliminates misuse of `this` etc.
What will the code below output? var a = [1, 2, 3]; a[10] = 99; console.log(a[6]);
When doing a[10] = 99; the JavaScript engine will set the array slots from 3 to 9 to an empty value. That would equal a declared, but not defined variable. Accordingly, doing console.log(a[6]); will print undefined.
6. When is prototypal inheritance an appropriate choice?
When you need to compose objects from multiple sources. Any time you need inheritance. Each type of prototypal inheritance (delegation, concatenative, functional) has its own set of use-cases, but all of them are equally useful in their ability to enable composition, which creates has-a or uses-a or can-do relationships as opposed to the is-a relationship created with class inheritance.
Imagine you have this code: var a = [1, 2, 3]; a) Will this result in a crash? a[10] = 99; b) What will this output? console.log(a[6]);
a) It will not crash. The JavaScript engine will make array slots 3 through 9 be "empty slots." b) Here, a[6] will output undefined, but the slot still remains empty rather than filled with undefined. This may be an important nuance in some cases. For example, when using map(), empty slots will remain empty in map()'s output, but undefined slots will be remapped using the function passed to it: var b = [undefined]; b[2] = 1; console.log(b); // (3) [undefined, empty × 1, 1] console.log(b.map(e => 7)); // (3) [7, empty × 1, 7]
How to empty an array in JavaScript? For instance, var arrayList = ['a','b','c','d','e','f'];
arrayList = [] arrayList.length = 0; arrayList.splice(0, arrayList.length);
function.call vs function.apply
both methods expect a thisArg as the first argument. This is the argument that gives the function a context; it determines the value of the JavaScript keyword this inside the function that is called or applied. The single difference is that the call method requires that arguments are specified separately; the apply method takes them as an array. It's clearer if you see the syntax: function.call(thisArg[, argument1[, argument2[, ...]]]); function.apply(thisArg[, argumentArray]);
Fix the previous question's issue so that the handler prints 0 for the first button in the list, 1 for the second, and so on.
create another closure so that the value of i will be the one expected. The code implementing this approach is the following: var nodes = document.getElementsByTagName('button'); for (var i = 0; i < nodes.length; i++) { nodes[i].addEventListener('click', (function(i) { return function() { console.log('You clicked element #' + i); } })(i)); } Or move the function outside of the loop: function handlerWrapper(i) { return function() { console.log('You clicked element #' + i); } } var nodes = document.getElementsByTagName('button'); for (var i = 0; i < nodes.length; i++) { nodes[i].addEventListener('click', handlerWrapper(i)); }
Consider the two functions below. Will they both return the same thing? Why or why not? function foo1() { return { bar: "hello" }; } function foo2() { return { bar: "hello" }; } console.log("foo1 returns:"); console.log(foo1()); console.log("foo2 returns:"); console.log(foo2());
foo1 returns: Object {bar: "hello"} foo2 returns: undefined The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.
Write a simple function (less than 160 characters) that returns a boolean indicating whether or not a string is a palindrome.
function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return (str == str.split('').reverse().join('')); }
Write a mul function which will produce the following outputs when invoked: console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48
function mul (x) { return function (y) { // anonymous function return function (z) { // anonymous function return x * y * z; }; }; } Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed.
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
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 a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?
null is also considered an object! Fix: console.log((bar !== null) && (typeof bar === "object")); // logs false
Consider the following code: console.log(typeof null); console.log(typeof {}); console.log(typeof []); console.log(typeof undefined); What's the output?
object object object (note: NOT an array) undefined
What will the code below output to the console and why? var myObject = { foo: "bar", func: function() { var self = this; console.log("outer func: this.foo = " + this.foo); console.log("outer func: self.foo = " + self.foo); (function() { console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }()); } }; myObject.func();
outer func: this.foo = bar outer func: self.foo = bar inner func: this.foo = undefined inner func: self.foo = bar In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo. In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.
What would following code return? console.log(typeof typeof 1);
string typeof 1 will return "number" and typeof "number" will return string.
What will be the output when the following code is executed? Explain. console.log(false == '0') console.log(false === '0')
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 will be the output of this code? var x = 21; var girl = function () { console.log(x); var x = 20; }; girl ();
undefined It's because JavaScript initialization is not hoisted. (Why doesn't it show the global value of 21? The reason is that when the function is executed, it checks that there's a local x variable present but doesn't yet declare it, so it won't look for global one.)
What will the following code output to the console and why: var hero = { _name: 'John Doe', getSecretIdentity: function (){ return this._name; } }; var stoleSecretIdentity = hero.getSecretIdentity; console.log(stoleSecretIdentity()); console.log(hero.getSecretIdentity()); What is the issue with this code and how can it be fixed.
undefined John Doe The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist. One way to fix the stoleSecretIdentity() function is as follows: var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);
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'));
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 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.
The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern? var list = readHugeList(); var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... nextListItem(); } };
var list = readHugeList(); var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... setTimeout( nextListItem, 0); } }; The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function (nextListItem) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.
How do you add an element at the begining of an array? How do you add one at the end?
var myArray = ['a', 'b', 'c', 'd']; myArray.push('end'); myArray.unshift('start'); console.log(myArray); // ["start", "a", "b", "c", "d", "end"] OR: myArray = ['start', ...myArray, 'end'];
What is undefined x 1 in JavaScript?
way of displaying an array's uninitialised index in Chrome. e.g. var trees = ["redwood","bay","cedar","oak","maple"]; delete trees[3]; Output: ["redwood", "bay", "cedar", undefined × 1, "maple"]