JS - General Knowledge

Questions/Answers based on the teachings at https://medium.freecodecamp.org/the-definitive-javascript-handbook-for-a-developer-interview-44ffc6aeb54e

55 flashcards · Programming Languages · by zeckdude

  1. How many built-in data types are there and what are they?

    null undefined boolean number string object symbol (added in ES6)

  2. What is undefined?

    undefined is the absence of a definition. It is used as the default value for uninitialized variables, function arguments that were not provided and missing properties of objects. Functions return undefined when nothing has been explicitly returned.

  3. Is Javascript a loosely or strongly typed language? What does that mean?

    JavaScript is a loosely typed language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types.

  4. What does pass by value mean? What can be passed by value?

    Passing by value When a primitive value is passed as an argument to a function When this occurs, the JS engine makes a copy of the value of the variable, stored in memory, to be used inside the function Any changes to the variable inside the function will not affect the variable outside of the function Example: var george = 'george'; function changeName(name) { name = 'john'; } changeName(george); console.log(george); // prints "george" Copy by value The same concept applies, so when you make a…

  5. What does pass by reference mean? What can be passed by reference?

    Passing by reference When an object or array is passed as an argument to a function When this occurs, the JS engine makes a new reference for the variable in the function to point to the same object in memory This means you could accidentally mutate an object or function by assigning it to another object or passing it as a parameter to a function. Example: let callToActionBtn = { text: 'Click' }; function changeButtonText(button) { button.text = 'Push'; } changeButtonText(callToActionBtn); cons…

  6. Why are functions considered to be first-class functions and what does that mean? Provide 5 characteristics that make functions first-class-functions.

    This means that javascript functions are just a special type of object that can do all the things that regular objects can do. In JS, functions have the following properties: Is an instance of the Object type function sayHello() { console.log('hi there'); } sayHello instanceof Object // returns true Can have properties and has a link back to its constructor method Can store the function in a variable const sayHello = () => console.log('hi there'); Can be passed as a parameter to another functio…

  7. What are higher order functions?

    Higher order functions are functions that take at least one function as a parameter or return a function.

  8. What is null?

    null is the absence of a value. It is an assignment value that can be assigned to a variable as a representation of no value.

  9. What is a falsy value? What are the six falsy values?

    Falsy values are values that will be coerced to false when forced a boolean coercion on it. They are: "" 0 null undefined NaN false

  10. What is NaN?

    NaN property Represents "Not-a-Number" value Indicates that a value is not a legal number.

  11. What is a truthy value? Provide six varying examples of truthy values.

    Truthy values are values that will be coerced to true when forced a boolean coercion on it. Anything not explicitly on the falsy list is truthy. Examples include: '0' ' ' [] function() {} 1 true

  12. What is implicit coercion? What is 1 situation when a primitive value is implicitly coerced to a boolean? What is 1 situation when a primitive value is implicitly coerced to a string? What are 3 situations when a primitive value is implicitly coerced to a number?

    Implicit coercion is when a variable is automatically type cast to another data type. Implicit coercion to boolean When using the logical operators || and && Implicit coercion to string When using the binary + operator (and one of the operands is a string) Implicit coercion to number When using comparison operators (<, <=, >, >=) When using arithmetic operators (+, -, /, %, *), except for + when one operand is a string When using the unary + operator When using the loose equality operator (==)

  13. What is the difference between == and ===?

    The common belief is that == is to check for equality and === is to check for equality and type. That is actually wrong and and == actually checks for equality with coercion (loose equality) while === checks for equality without coercion (strict equality). Loose equality compares two values for equality, after converting both values to a common type. What happens is that it will first check if both values are boolean. If both are not boolean, it will cast the boolean value to a number. If the s…

  14. How do you shallow clone (copy by value) an array?

    var array = [1,2,3]; var shallowCopy = array.slice(); var array = [1,2,3]; var shallowCopy = [...array];

  15. How do you deep clone (copy by value) an array?

    var array = [1,2,['one']]; var deepCopy = JSON.parse(JSON.stringify(array));

  16. What is scope?

    Scope defines the accessibility of variables and functions in the code.

  17. What is global scope?

    Global Scope is the outermost scope. Variables declared outside a function are in the global scope and can be accessed in any other scope. In a browser, the window object is the global scope.

  18. What is local scope?

    Local Scope is a scope nested inside another function scope. Variables declared in a local scope are accessible within this scope as well as in any inner scopes.

  19. What are the different variable declaration identifiers? How do they differ?

    var Variable declaration gets hoisted Has function scope Can be redeclared Can be overwritten let Used to identify a variable that will be re-assigned Variable declaration does not get hoisted Has block scope Can not be redeclared Can be overwritten const Used to identify a variable that will remain constant and can not be re-assigned or redeclared One thing to be aware of is that its object properties or array elements can be changed Variable declaration does not get hoisted Has block scope

  20. What is hoisting? Describe the subtle variations in hoisting behavior as they relate to function declarations, function expressions, var declarations, const declarations, and let declarations.

    Hoisting is the behavior of moving var and function declarations to the top of their respective scopes. Function declarations Declarations are completely hoisted A declared function can be called before and after it is defined Function expressions Declarations are hoisted but not its assignments It is created when the execution reaches it and is usable from then on — the assignment is not hoisted var declarations Declarations are hoisted but not its assignments let declarations Declarations are…

  21. What is closure? Provide use cases as to why it is useful.

    A closure is a function that makes use of variables defined in outer functions that have previously returned. To use a closure, simply define a function inside another function and return it. The inner function will have access to the variables in the outer function scope, even after the outer function has returned. Use Cases: Allows you to create private variables and methods that cannot be changed from outside the function declaration Example: function createRunningTotal() { let counter = 0;…

  22. What is the module pattern? Provide an example.

    The Module Pattern is: Is a design pattern which uses closure to provide access to private variables and methods to a returned inner function. One of the most common design patterns Encapsulates the code within the module with closures. One of the most common variations is the revealing module pattern Example: var Module = (function () { var _privateMethod = function () {...}; // Methods on the returned object have access to private variables and methods from the outer function via closure retu…

  23. What is the revealing module pattern? Why is it useful? Provide an example.

    The revealing module pattern: Is a variation on the module pattern Reveals public pointers to methods inside the module's scope. This makes it easier to follow which methods are being made public. Example: var Module = (function () { var privateMethod = function () { // private }; var someMethod = function () { // public }; var anotherMethod = function () { // public }; return { someMethod: someMethod, anotherMethod: anotherMethod }; })();

  24. What is an IIFE? Why is it useful? Provide an example.

    An IIFE is an Immediately Invoked Function Expression. It is: Called immediately after you define it. Useful to keep variables and methods, that are defined within, scoped to the function and thereby not polluting the global namespace Surrounded with parentheses so it is not treated as a function declaration Followed by parentheses so it executes right away Example: (function() { var name = 'Chris'; console.log('Private variable inside IIFE:', name); })();

  25. What is context?

    Context refers to the object within which a function is executed. When you use the JavaScript keyword this, that word refers to the object that the function is executing in.

  26. What does the call() method do? Provide an example.

    call() sets the context and invokes the function immediately. The arguments to run on the called function are provided as separate arguments to call(). Example: var obj = { runFunc: function() { console.log('The context is', this); console.log('The arguments are', arguments); } } obj.runFunc.call(window, 'string', 5);

  27. What does the apply() method do? Provide an example.

    apply() sets the context and invokes the function immediately. The arguments to run on the applied function are provided as an array of arguments to apply(). Example: var obj = { runFunc: function() { console.log('The context is', this); console.log('The arguments are', arguments); } } obj.runFunc.apply(window, ['string', 5]);

  28. What does the bind() method do? Provide an example.

    bind() sets the context and returns the bound to be used later. The arguments to run on the bound function are provided as separate arguments to bind(). Example: var obj = { runFunc: function() { console.log('The context is', this); console.log('The arguments are', arguments); } } var boundFunc = obj.runFunc.bind(window, 'string', 5); boundFunc();

  29. What is this? How is its value determined?

    The value of this is usually determined by a functions execution context. The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used. In order to determine the value of this, the following rules apply (stop at the first one that applies): new binding - When using the new keyword to call a function, this is the newly constructed object Explicit binding - When call() or apply() are used to call a function, this is the object that…

  30. What is strict mode? Why is it useful?

    Strict mode is a way to introduce better error-checking into your code. It is enabled by adding "use strict" in the scope where it should be applied. It is useful because it will make the browser throw an error when common errors occur such as: When declaring a global variable

  31. What is a constructor function? Provide an example.

    A constructor function is a blueprint for creating multiple objects that share properties and methods. It is considered good practice to name constructor functions with an upper-case first letter. A constructor function is: A function that assigns properties and methods to this (which is the object that is created when the function is invoked) Traditionally named with an upper-case first letter Invoked using the new keyword Examples: function Person(name) { this.sayName = function() { console.l…

  32. What is the new keyword? What happens when it is used?

    The new keyword is used to invoke a constructor function. When it is used: It creates a new object that contains the properties and methods as defined on the constructor function Sets the new object’s prototype to be the prototype of the constructor function Sets this in the newly created object to be itself

  33. What does Object.create() do? When is it useful? Provide an example.

    The Object.create() method creates a new object with the specified object as its prototype. Example: // Object var person = { sayName: function() { console.log('Hello, my name is', this.name); }, nose: 1, arms: 2 } // Inherit from the `person` object and add to it var webDeveloper = Object.create(person, { nerd: { value: true } }); // Inherit from the `webDeveloper` object and add to it var chris = Object.create(webDeveloper, { name: { value: 'Christopher' } }); // Check if `chris` is inheritin…

  34. How do you throw an error? Provide an example.

    throw 'This is my error'

  35. How do you handle exceptions? What happens in each step? Provide an example.

    If an exception is thrown, the try...catch statement catches it. The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. try block: Contains one or more statements to perform catch block: Contains statements that specify what to do if an exception is thrown in the try block If no exception is thrown in the try block, the catch block is skipped finally block: Contains statements to execute after the try and catch blocks exe…

  36. Which method do you use to inherit properties and methods from an existing object to another existing object? Provide an example.

    You use Object.setPrototypeOf(). Note: Object.setPrototypeOf has performance considerations. Try to avoid using it and create a new object with the desired prototype using Object.create(). Example: let toyota = { drive() { return 'driving toyota' } } let camry = { drive() { return `${super.drive()} camry`; } wifi() { return 'using wifi' } } // camry inherits properties and methods from toyota Object.setPrototypeOf(camry, toyota);

  37. How do you shallow copy an object? Provide an example.

    let toyota = { drive() { return 'driving toyota' }, steer() { return 'steering toyota'; } } let camry = { drive() { return 'driving camry'; }, closeDoor() { return 'close door on camry'; } } Use Object.assign(): var newObject = Object.assign({}, toyota, camry); Use spread operator: var newObject = {...toyota, camry};

  38. What are three ways to implement OOP in JS?

    Factory function Constructor function w/ new keyword Object.create()

  39. What are loosely/tightly coupled objects?

    Tightly coupled objects Objects that rely so heavily on each other that removing or changing one will mean that you have to completely change another one Loosely coupled objects Objects that can stand alone as much as possible

  40. What is a promise? What are the methods associated with it? Provide an example.

    A promise is object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value. Methods: then(): Take two arguments: 1 success callback function and 1 failure callback function The callback functions receive the result of the AJAX operation catch(): This is the same as providing the second argument callback function on the then() Example: new Promise((resolve, reject) => { resolve('woohoo'); // reject('Something isnt set up correctly'); }) .then(func…

  41. What is prototypal inheritance? Provide an example that demonstrates it.

    Prototypal inheritance is the process that describes how objects inherit from other objects. Each object has a prototype (__proto__) property which contains the properties and methods from the parent object, which are accessible by the child object. Example: let Car = function(model) { this.model = model; } Car.prototype.getModel = function() { return this.model; } var nissan = new Car('Nissan');

  42. What is a constructor property? Why is it useful?

    A constructor property can be found on any objects that are created with a constructor function. Each of the new objects are given a constructor property which references the constructor function. This is useful to: Compare the constructor properties of two objects to check if they are from the same parent object Example var a = new String("abc"); var b = new String("def"); a.constructor === b.constructor Create a new object that share is based on the same constructor as another object Example:…

  43. What is the difference between a function declaration and function expression?

    Function Declarations are: Completely hoisted to the top of the function scope Therefore, a declared function can be called before and after it is defined Written with the following syntax Example: function sayHello() { console.log('hello'); } Function expressions are: Written with the following syntax Example: const sayHello = function() { console.log('hello'); } Not hoisted Therefore, a function expression is created when the execution reaches it and is usable from then on

  44. What is the difference between the __proto__ and prototype property? What method is used on the instance to access the prototype of the constructor function?

    __proto__: The object that shows all the properties and methods of the constructor function that it makes available to its instances prototype: The object in memory that __proto__ refers to each time you create an object with new It is only available on the constructor function and not on the instance that is created with new You can add properties and methods to the constructor function's prototype and they will be accessible to the instances that have been created via their __proto__ property…

  45. Explain pure functions?

    A pure function is a function which: Given the same inputs, always returns the same output Has no side-effects (doesn't change anything else in the app or do any other unrelated actions)

  46. What is functional programming? Why is it beneficial?

    Functional programming is a paradigm that follows these ideas: Use pure functions Avoid shared state Immutable data No side-effects Is declarative It is beneficial because: It is more concise It is more predictable Easier to test

  47. What does the term composition over inheritance mean? Why is it beneficial?

    Composition over inheritance refers to the belief that functional programming is better for code maintenance than an inheritance model. The belief is due to several areas that make OOP difficult to maintain over time. The negative points relating to OOP are: Objects are designed in relation to what they are, which forces the programmer to make predictions for the future as to what the class tree should look like It is a strict pattern as inherited objects rely on properties and methods from the…

  48. What is the prototype chain?

    The prototype chain is: A series of links between objects that reference one another When looking for a property on an object, the JavaScript engine follows these steps: Try to access the property on the object itself Look for the property on the object it inherited its properties from — the object’s prototype Traverse up the chain looking for the property and return the first one it finds The last object in the chain is the built-in Object.prototype, which has null as its prototype. Once the e…

  49. What is the difference between an object's own properties and its inherited properties? How can you check if a property is an own property on the instance?

    An own property is: Defined on the object An inherited property is: Inherited through the prototype chain and can be found on the object's __proto__ property A property can be determined to be an object's own property or inherited via the prototype chain by using the hasOwnProperty() method Example: const Chair = function() {} Chair.prototype.legs = 4; const sofa = new Chair(); sofa.material = 'leather'; sofa.hasOwnProperty('material'); // returns true sofa.hasOwnProperty('legs'); // returns fa…

  50. If an object property is mutated on the prototype, what happens to the corresponding properties on it's inherited objects? If an object's prototype is replaced, what happens to the corresponding properties on it's inherited objects?

    If an object’s property is mutated on the prototype, objects which inherited that property will share the same mutation. Example: const chair = { price: 20 }; const sofa = Object.create(chair); chair.price = 99999999; console.log(sofa.price); // returns 99999999 If the property is replaced, the change will not be shared. Example: let chair = { price: 20 }; const sofa = Object.create(chair); chair = { price: 9999999 }; console.log(sofa.price); // returns 20

  51. What is the difference between classical inheritance and prototypal inheritance?

    Classical Inheritance Uses a class which is a blueprint for creating multiple objects that share properties and methods Those objects can further be used to create subclasses Instances are created with the constructor function and new keyword Can also be created with an ES6 class, but behind the scenes it is just using a constructor function Uses the prototype chain to wire the child to the parent Prototypal Inheritance Uses a prototype which is an internal object from which other objects inher…

  52. Define what a programming paradigm is. Name two programming paradigms important for JavaScript app developers.

    A programming paradigm is a way of thinking about software construction based on some fundamental, defining principles. Prototypal inheritance Functional programming

  53. What are the three kinds of prototypal inheritance?

    Prototype delegation A delegate prototype is an object which is used as a model for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype and its properties This process is usually accomplished by using Object.create() Concatenative inheritance The process of inheriting properties from one object to another by copying the object’s prototype properties, without retaining a reference between them This process is usually accomplished by using…

  54. What makes a function in JS a first-class function? Why is it useful?

    Function are considered first-class functions when functions in that language are treated like any other variable. They have these characteristics: Can be passed as an argument to other functions Can be returned by another function Can be assigned as a value to a variable Can be assigned as object properties It is useful because first-class functions: Allow for functional programming to work in JS Make it possible to run callback functions

  55. What is recursion? What are steps to follow when using recursion? Provide an example.

    Recursion is when, instead of using a loop, a function will change a value and call itself again with the new value, and then it repeats the process until a condition is satisfied. Steps: Function must take an argument A condition must be set that will stop the function from running if it has been met Perform its action Call itself with the argument having changed (usually incremented or decremented) Example: function printNumber(n) { if (n === 0) { return; } console.log(n); return printNumber(…