Js Interview Questions

Advanced concepts in modern Javascript. Closures, event handling, primitive VS reference data types, ES6&ES7, V8 engine. Related courses: keyword this: memcode.com/courses/85 prototypal inheritance: memcode.com/courses/68 promises: memcode.com/courses/122 streams and buffers: memcode.com/courses/215 Links: great site with tasks

47 flashcards · Programming Languages · by lakesare

  1. What is a potential pitfall with using typeof bar === "object" to determine if bar is an object?

    typeof null === "object" too.

  2. Why wrap entire content of a JavaScript source file in a function block?

    Namespace. (function() { const x = 2; })(); Now others don't see x. It was needed in ES5, but now, with introduction on modules, we don't usually need it as they are automatically encapsulated in their own scope.

  3. Give an example of closure keeping its context.

    const createAdd = () => { let counter = 0; return () => { console.log(counter) counter = counter + 1 } } add = createAdd(); add(); //=> 0 add(); //=> 1 add(); //=> 2 After createAdd() executed, normally we would expect that the entirety of the inner scope of createAdd() would go away, because we know that the V8 engine employs a Garbage Collector that comes along and frees up memory once it's no longer in use. Since inner scope of createAdd is no longer in use, it would seem natural that counte…

  4. Why === instead of ==?

    === doesn't implicitly convert its operands

  5. f.call vs f.bind vs f.apply What is the difference?

    call and apply invoke the function immediately . bind returns a new function with this preset. call - comma (takes in comma-separated arguments), apply - array (takes in array of arguments), bind - a bit different (returns a new function instead. comma-separated arguments). call(self, a, b) apply(self, [a, b])

  6. Why use server-rendering?

    1. performance on the first page load. 2. google crawling of ajax is unpredictable 3. if you care about users on lame phones

  7. 1. console.log('a'); 2. setTimeout(() => console.log('b'), 0); 3. console.log('c'); What will be displayed? What happens here?

    'a', 'c', 'b' 1 is pushed to the stack, executed, and popped from the stack. browser sees asynchronous code 2, and pushes it to the web api. Web api decides when async code is ready, and adds it to the event queue. 3 is pushed to the stack, executed and popped from the stack. event loop sees there is nothing in the stack anymore, and pushes 2 from the event queue onto the stack. 1 -> call stack, executes. 2 -> call stack, web api 3 -> call stack, executes 2 -> event queue, call stack, executes…

  8. Javascript is single-threaded.

  9. What is event bubbling?

    section > div > a We click on a: event fires for a, then for div, then for section and up. event.target will still be a in all the event handlers. Events bubble from the inner element up like a bubble in the water.

  10. What does event.stopPropagation() do?

    If called in the capture state - stops event from capturing, if called in the bubble state - stops event from bubbling.

  11. What are 3 stages of event handling in Js?

    1. event capturing 2. event has arrived at event.target 3. event bubbling

  12. Is Js call-by-value or call-by-reference?

    This terminology is extremely confusing, and differs among different language language (Java people call call-by-sharing a call-by-value), don't rely on it! Js is call-by-value, because: reassigning a passed variable in function never changes the outside variable. BUT if we pass an object, the object reference is copied, AND WE CAN CHANGE THAT OBJECT This situation is sometimes referred to as call-by-sharing. Other languages that support this system are Ruby and Java.

  13. In Js a variable may store two types of data: primitive and reference. What are they?

    primitive: boolean, null, undefined, number, string, Symbol. reference: only objects (which includes functions and arrays).

  14. What is the difference between primitive and reference data types?

    Primitive data types store a value. Their values are copied over: let a = 3; let b = a; // copy a += 1; // a is 4, b is still 3 Reference data types store a reference to an object.

  15. How to access static method from an instance method?

    this.constructor.staticMethod class Hello { static hi = 'hi'; sayHi = () => { console.log(this.constructor.hi); } }

  16. [].sort((a, b) => compareFunction) What can compareFunction return?

    If compareFunction returns: => -1: a comes first. => 1: b comes first. => 0: leave a and b unchanged in respect to each other.

  17. What new primitive data types do we have in ES6?

    Symbol.

  18. What is a deep copy VS shallow object copy?

    A shallow copy will clone the top-level object, but nested object are shared between the original and the clone. That's it: an object reference is copied, not cloned. So if the original object contains nested object, then the clone will not be a distinct entity. A deep copy will recursively clone every objects it encounters. The clone and the original object will not share anything, so the clone will be a fully distinct entity.

  19. const object = { a: 1, b: 2 }; const copy = object; object.a = 3; What happens here?

    Both object and copy are { a: 3, b: 2 } now. copy was assigned a reference to the object object. When it comes to object, a Javascript variable behaves more like a kind of automatic pointer.

  20. Name 2 ways to create a shallow copy of an object in Js.

    Object.assign({}, aa) { ...aa }

  21. How to create a deep copy of an object in Js?

    Js doesn't offer any native mechanisms for this. You can either: use a library, inefficient JSON.parse(JSON.stringify(aa)) Links: Js implementation of deep clone, with good explanation

  22. Name and explain 4 entities of Js Runtime model (aka in what order functions will be called).

    stack - a place where functions push, execute and pop from web api - if function was async, it goes here event queue - where function goes after web api decides it's ready to be executed. event loop - waits when stack get empty and pushes something from event queue to it.

  23. What's a V8 Engine?

    V8 Engine is a piece of code that compiles JavaScript directly to native machine code (011101001). It's used in Chrome and Node.js.

  24. Write a function that will console.log({ a, b, c }) with default values, unless options are passed: hi(); hi({ a: 'rrr' });

    const hi = ({ a=1, b=2, c=3 } = {}) => { console.log({ a, b, c }); };

  25. When may hasOwnProperty be useful?

    When we want to know if our object defined the property (vs if it was just inherited). const person = { name: 'Default', surname: 'Default' }; const jane = { name: 'Jane' }; jane.__proto__ = person; console.log(jane.hasOwnProperty('name')); console.log(jane.hasOwnProperty('surname'));

  26. In ES5 there is an array-like object 'arguments' accessible within functions. What can be used in arrow functions instead?

    const hi = (a, b, ...args) { args //=> an array } Links: rest parameters

  27. "Jane".length What happened here?

    Js primitives are not objects, they don't have any methods or properties defined on them. But sometimes Js understands that we want to use this string as new String("Jane"), wraps our primitive into object, and lets us use its methods. [However it doesn't convert, eg, numbers to objects]

  28. Is Js a compiled or interpreted language?

    Js can be either, it's not mentioned in languages specification. It depends on Js engine used to execute it. Before the browser war Js engines were simply interpreters, but nowadays, eg V8, is a JIT compiler. The emergence of JIT compilers for script languages has blurred the line between compilation and interpretation. Links: Js engine

  29. Is V8 engine compiler or interpreter?

    V8 consists of two compilers. runs quickly but generates inefficient code, optimizing compiler.

  30. What algorithm does Js use to sort arrays?

    EcmaScript standard doesn't define this, it depends on engine used to execute it. V8 and SpiderMonkey use different ones.

  31. What does 'use strict' do in Js?

    'use strict' is a directive/pragma for compilers to interpret code in the strict mode. Strict mode throws errors when it's sensible. In function call, this was window. It is now undefined. Using delete on a variable name delete myVariable throws. These errors are good, because they reveal plain errors or bad practices.

  32. What is an execution context?

    Functions have an execution context. Basically how function was called, and what this is within function body.

  33. How can we supersede IIFEs since ES6? (function(){ var name = "Better JQuery"; window.betterJquery = { name }; }())

    Using curly braces and const/let: { const name = "Better JQuery"; window.betterJquery = { name }; }

  34. How to use .slice method?

    Defined on: String.prototype.slice(), Array.prototype.slice() Returns: Doesn't modify the string/array, for arrays returns a new shallow copy. Signature: slice(indexStart, indexBeforeEnd)

  35. In what cases does the fetch method reject?

    fetch.catch happens only on network failure or if anything prevented the request from completing. Usual statuses (404, 500) will be treated as fetch.then.

  36. event.preventDefault() VS event.stopPropagation()?

    preventDefault will e.g. stop the form from submitting, stopPropagation will prevent an event from continuing to capture/bubble (depending on time when it's called). preventDefault doesn't stopPropagation.

  37. ES6 introduced tail call optimization. What does it mean for your coding habits?

    Now we can create deeply recursive calls without fearing stack overflow, provided we use recursive call as a tail call.

  38. Name exception handling syntax.

    try{ } catch (error) { } finally { // executes no matter what. literally no matter what. }

  39. What will happen? try { setTimeout(function() { noSuchVariable; // script will die here }, 1000); } catch (e) { alert("exception!"); }

    If an exception happens in a "scheduled" code, like in setTimeout, then try..catch won’t catch it: try { setTimeout(function() { noSuchVariable; // script will die here }, 1000); } catch (e) { alert( "won't work" ); } That’s because try..catch actually wraps the setTimeout call that schedules the function. But the function itself is executed later, when the engine has already have left the try..catch construct. To catch an exception inside a scheduled function, try..catch must be inside that fu…

  40. Name 2 cases when finally is useful. (Cases when simple statement after the try-catch block won't get executed)

    1. When try block returns function f() { try { alert('start'); return "result"; } catch (e) { } finally { alert('cleanup!'); } } f(); // start! cleanup! => result 2. When we throw in the catch block function f() { try { alert('start'); throw new Error("an error"); } catch (e) { // ... if("can't handle the error") { throw e; } } finally { alert('cleanup!') } } f(); // cleanup! Links: proof

  41. What's the result? function f() { try { alert('start'); return "result"; } catch (e) { } finally { alert('cleanup!'); } } f(); //-?

    alert(start!) alert(cleanup!) => result finally executes even if try returns from the function.

  42. Why do we need break statements after each case in switch?

    If we don't break after a valid case, any next case will be considered valid and will be executed, until we meet next break. switch (0) { case -1: console.log('negative 1'); break; case 0: console.log(0); case 1: // no break statement in 'case 0:' so this case will run as well console.log(1); break; // it encounters this break so will not continue into 'case 2:' case 2: console.log(2); break; default: console.log('default'); //=> 0 1

  43. What are the possible values for Math.random()?

    [0, 1) Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

  44. What is the difference between const p1 = {} and const p2 = Object.create(null); ?

    p1.__proto__ => Object.prototype p2.__proto__ => {} A javascript object inherits from Object by default, unless you explicitly create it with null as its prototype. {} is instead equivalent to Object.create(Object.prototype).

  45. What is the difference between debounce and throttle?

    Debounce - execute this function only if 100ms have passed without it being called (Makes a function not be called again until a certain amount of time has passed without it being called) Throttle - execute this function at most once every 100ms (Enforces a maximum number of times a function can be called over time)

  46. What's the difference between for..in and for..of loops? let list = [4, 5, 6]; for (let i in list) { console.log(i); } for (let i of list) { console.log(i); }

    for..in - iterates over the indexes for..of - iterates over the values let list = [4, 5, 6]; for (let i in list) { console.log(i); // "0", "1", "2", } for (let i of list) { console.log(i); // "4", "5", "6" } These are useful when you want to use break e.g.

  47. What loop would you use to iterate over the properties of an object? let oldCar = { make: 'Toyota', model: 'Tercel', year: '1996' }; // Alternative to Object.keys? Object.keys(oldCar).forEach((key) => { console.log(`${key} --> ${oldCar[key]}`); })

    for..in: for (ley key in oldCar) let oldCar = { make: 'Toyota', model: 'Tercel', year: '1996' }; for (let key in oldCar) { console.log(`${key} --> ${oldCar[key]}`); }