JavaScript 01-50

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

33. What will be the output of the following code?

var person = { age: 20 }; var output = (function() { delete person.age; return person.age; })(); console.log(output); Code will output undefined. delete operator is used to delete a property from an object. person is an object which has age as a property and from self-invoking function we are deleting age property of object person and after deletion we are trying to reference deleted property age which result undefined.

32. What will be the output of the following code?

var total = 100; var output = (function() { delete total; return total; })(); console.log(output); Code will output 100. delete operator is used to delete property from an object. total is not an object; it's global variable of type number.

7. Explain values and types in JavaScript?

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

3. What is typeof operator?

JavaScript provides a typeof operator that can examine a value and tell you what type it is. var value; typeof value; ==> "undefined" value = "Hello World!"; typeof value; ==> "string" value = 45; typeof value; ==> "number" value = true; typeof value; ==> "boolean" value = null; typeof value; ==> "object" value = undefined; typeof value; ==> "undefined" value = { property: "propertyValue" }; typeof value; ==> "object"

40. Explain the differences on the usage of func between these? function func() {} andvar func = function() {}

The former is a function declaration while the latter is a function expression. The key difference is that the bodies of function declarations are hoisted but the bodies of function expressions are not hoisted although they have the same hoisting behavior as variables. We will get an Uncaught TypeError when we invoke a function expression before it is defined. func(); ==> 'Function' function func() { console.log('Function'); } ==> Function declaration func(); ==> Uncaught TypeError func is not a function var func = function() { console.log('Function'); }; ==> Function expression

34. What is the difference between using let and var to declare a variable in ES6?

- The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block which can be smaller than a function block. Both are global when they are outside any block. - Variables declared with let are not accessible before they are declared in their enclosing block. This will throw a ReferenceError exception.

23. What is Coercion in JavaScript?

In JavaScript conversion between different two build-in types called coercion. Coercion comes in two forms in JavaScript explicit and implicit. Explicit coercion var first = "40"; var second = Number(a); ==> 40 Implicit coercion var first = "40"; var second = first * 1; ==> 40

8. What is let keyword in JavaScript?

In addition to declaring variables at the function level; ES6 lets developers declare variables which belong to individual blocks (pairs of { ... }) using the let keyword.

20. Is there anyway to force using strict mode in Node.js?

It's better to run command node --use_strict if anyone wants the whole app to run in strict (including external modules).

9. What is strict mode?

Strict mode is a feature that allows us to place a program or a function in a strict operating context. This strict context prevents certain actions being taken and throws more exceptions. // non-strict code (function(){ "use strict"; ... })(); // non-strict code

17. Why would you use something like the load event? Do you know any alternatives and why would you use those?

The load event fires at the end of the document loading process which all of the objects in the document are in the DOM and all the images, scripts, links, and sub-frames have finished loading at this point. The DOM event DOMContentLoaded fires after the DOM has been constructed but do not wait for other resources to finish loading. This is preferred in certain cases when we don't need the full page to be loaded before initializing.

12. What does use strict do?

The use strict literal is entered at the top of a JavaScript program or a function and it helps us write safer JavaScript code by throwing an error when a global variable is created by mistake. function do(value) { "use strict"; newValue = value + 10; } It will throw an error because newValue was not defined and it is being set in global scope which is not allowed with "use strict". The small change fixes the error being thrown. function do(value) { "use strict"; var newValue = value + 10; }

41. What are the advantages and disadvantages of using use strict?

use strict is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt in to a restricted variant of JavaScript. Advantages - Makes it impossible to accidentally create global variables. - Makes assignments that would silently fail to throw an exception. - Makes attempts to delete undeletable properties throw exceptions. - Requires that function parameter names be unique. - this is undefined in the global context. - It catches some common coding bloopers and throws exceptions. - It disables features that are confusing or poorly thought out. Disadvantages - No more access to function.caller and function.arguments. - Many missing features that some developers might be used to. - Concatenation of scripts written in different strict modes might cause issues. The benefits outweigh the disadvantages and I never had to rely on the features that strict mode blocks. I would recommend using strict mode.

16. Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

- Every script has access to the global scope and if everyone uses the global namespace to define their variables, collisions will likely occur. - It's better to use the module pattern (IIFEs) to encapsulate our variables within a local namespace.

49. What is a Closure and why would we use one?

- Closures are functions that have access to the outer (enclosing) function's variables—scope chain even after the outer function has returned. - A closure is the combination of a function and the lexical environment within that function was declared. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Why would we use one? - Data privacy/emulating private methods which are commonly used in the module pattern. - Partial applications or currying.

29. Difference between ES5 and ES6?

- ECMAScript 5 (ES5) - The 5th edition of ECMAScript was standardized in 2009. This standard has been implemented fairly completely in all modern browsers. - ECMAScript 6/ECMAScript 2015 (ES6/ES2015) - The 6th edition of ECMAScript was standardized in 2015. This standard has been partially implemented in most modern browsers. Here are some key differences between ES5 and ES6. 1. arrow functions and string interpolation const greetings = (name) => { return `hello ${name}`; } const greetings = name => `hello ${name}`; 2. const works like a constant in other languages in many ways but there are some caveats. const stands for constant reference to a value. So we can actually mutate the properties of an object being referenced by the variable. We just can not change the reference itself. const NAMES = []; NAMES.push("Jim"); console.log(NAMES.length === 1); ==> true NAMES = ["Steve", "John"]; ==> Error will be thrown. 3. block-scoped variables The new ES6 keyword let allows developers to scope variables at the block level. let does not hoist in the same way var does. 4. Default parameters allow us to initialize functions with default values. Default is used when an argument is either omitted or undefined — meaning null is a valid value. function multiply (a, b = 2) { return a * b; } multiply(5); ==> 10 5. class definition and inheritance ES6 introduces language support for classes (class keyword), constructors (constructor keyword) and the extend keyword for inheritance. 6. for ... of operator The for ... of statement creates a loop iterating over iterable objects. 7. spread operator for objects merging. const first = { a: 1, b: 2 }; const second = { a: 2, c: 3, d: 4}; const third = { ...first, ...second } 8. Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks but promises provide improved readability via method chaining and succinct error handling. const isGreater = (a, b) => { return new Promise ((resolve, reject) => { if (a > b) { resolve(true); } else { reject(false); } }); } isGreater(1, 2) .then(result => { console.log('greater'); }) .catch(result => { console.log('smaller'); }); 9. modules exporting and importing const Coordinate = { x: 1, y: () => { ... } }; export default Coordinate; import coordinate from './Coordinate'; ==> Importing coordinate module.

22. What's the difference between Host objects and Native objects?

- Native objects are objects which are part of JavaScript language defined by ECMAScript specification such as String, Math, RegExp, Object, Function and so on. - Host objects are provided by a runtime environment (Browser or Node) such as window, XMLHTTPRequest and so on.

44. What is the difference between document load event and document DOMContentLoaded event?

- The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed without waiting for stylesheets, images, and subframes to finish loading. - load event of window is only fired after the DOM and all dependent resources and assets have loaded.

48. What's a typical use case for anonymous functions?

- They can be used in IIFEs to encapsulate some code within a local scope so that variables do not leak to the global scope. (function() { ... })(); - As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them rather than having to search elsewhere to find the function body. setTimeout(function() { console.log('Hello world!'); }, 1000); - Arguments to functional programming constructs or lodash (similar to callbacks). const array = [1, 2, 3]; const double = array.map(function(e) { return e * 2; }); console.log(double); ==> [2, 4, 6]

35. When should I use Arrow Functions in ES6?

- Use function in the global scope and for Object.prototype properties. - Use class for object constructors. - Use => (arrow function) everywhere else. Why use arrow functions almost everywhere? - Scope safety => When arrow functions are used consistently; everything is guaranteed to use the same this as the root. If even a single standard function callback is mixed in with a bunch of arrow functions there is a chance the scope will become messed up. - Compactness => Arrow functions are easier to read and write. - Clarity => When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what this object is.

39. What are the differences between ES6 class and ES5 function constructors?

// ES5 function constructor function Person(name) { this.name = name; } // ES6 class class Person { constructor(name) { this.name = name; } } They look pretty similar but the main difference in the constructor comes when using inheritance. When we create a Student class that subclasses Person and add a studentId field. // ES5 function constructor function Student(name, studentId) { // Call constructor of superclass to initialize superclass-derived members. Person.call(this, name); // Initialize subclass's own members. this.studentId = studentId; } Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; // ES6 class class Student extends Person { constructor(name, studentId) { super(name); this.studentId = studentId; } } It's much more verbose to use inheritance in ES5 but the ES6 version is easier to understand and remember.

25. What is the difference between anonymous and named functions?

// anonymous function assigned to variable first var first = function() { ... }; // named function (bar) assigned to variable second var second = function bar() { ... }; // actual function execution first(); second();

13. What constructions can we use for iterating over object properties?

1. for in loops - for (var prop in item) { ... } It will iterate through its inherited properties and we can use item.hasOwnProperty(prop) check before using it. 2. Object.keys() - Object.keys(item).forEach() It is a static method that will list all enumerable properties of an object. 3. Object.getOwnPropertyNames() - Object.getOwnPropertyNames(item).forEach() It is a static method that will list all enumerable and non-enumerable properties of an object.

14. What constructions can we use for iterating over array items?

1. for loops for (var i = 0; i < array.length; i++) The common pitfall is that var is in the function scope and most of the time we need a block-scoped iterator variable. ES2015 introduces let which has block-scoped and it is recommended to use that instead. So this becomes for (let i = 0; i < array.length; i++) 2. forEach array.forEach(function (element, index) { ... }) It can be more convenient at times because we don't have to use index if all we need is the array elements. There are also every and some methods which will allow us to terminate the iteration early. I would prefer .forEach method but it really depends on what we are trying to do. for loops allow more flexibility such as prematurely terminating the loop using break or incrementing the iterator more than once per loop.

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

== is the abstract equality operator while === is the strict equality operator. The == will compare for equality after doing any necessary type conversions. The === does not do coercion so if two values are not the same type, it will simply return false. When using == funky things can happen such as 1 == '1'; ==> true 1 == [1]; ==> true 1 == true; ==> true 0 == ''; ==> true 0 == '0'; ==> true 0 == false; ==> true It's better never to use the == except when comparing against null/undefined for convenience. var value = null; console.log(value == null); ==> true console.log(value == undefined); ==> true

38. What is the definition of a Higher-Order Function?

A Higher-Order Function is any function that takes one or more functions as arguments which it uses to operate on some data and/or returns a function as a result. Higher-Order Functions are meant to abstract some operation that is performed repeatedly. The classic example is map which takes an array and a function as an argument which uses the function to transform each item in the array and return a new array with the transformed data. Other popular examples in JavaScript are forEach, filter and reduce. A Higher-Order Function does not just need to be manipulating arrays as there are many use cases for returning a function from another function. Function.prototype.bind is one such example in JavaScript. Let say we have an array of names which we need to transform each string to uppercase. const names = ['irish', 'daisy', 'anna']; The imperative way will be as such const transformNamesToUppercase = function(names) { const results = []; for (let i = 0; i < names.length; i++) { results.push(names[i].toUpperCase()); } return results; }; transformNamesToUppercase(names); ==> ['IRISH', 'DAISY', 'ANNA'] Use .map(transformerFn) makes the code shorter and more declarative. const transformNamesToUppercase = function(names) { return names.map(name => name.toUpperCase()); }; transformNamesToUppercase(names); ==> ['IRISH', 'DAISY', 'ANNA']

28. What is the difference between a shim and a polyfill?

A shim is a piece of code used to correct the behavior of code that already exists usually by adding a new API that works around the problem. This differs from a polyfill which implements a new API that is not supported by the stock browser as shipped. - A shim is a piece of code that performs interception of an API call and provides a layer of abstraction and shim is a library that brings a new API to an older environment using only the means of that environment. It is not necessarily restricted to a web application. - A polyfill is a type of shim that retrofits legacy browsers with modern HTML5/CSS3 features usually using JavaScript.

5. Explain arrays in JavaScript?

An array is an object that holds values (of any type) not particularly in named properties/keys but rather in numerically indexed positions. var array = [ "Hello World!", 40 ]; array[0]; ==> "Hello World!" array.length; ==> 2 typeof array; ==> "object"

50. What do you think of AMD vs CommonJS?

Both are ways to implement a module system that was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is obviously asynchronous. CommonJS is designed with server-side development in mind while AMD with its support for asynchronous loading of modules is more intended for browsers. I find AMD syntax to be quite verbose and CommonJS is closer to the style we would write import statements in other languages. Most of the time, I find AMD unnecessary because if we served all our JavaScript into one concatenated bundle file, we would not benefit from the async loading properties. CommonJS syntax is closer to the Node style of writing modules and there is less context-switching overhead when switching between client-side and server-side JavaScript development. I'm glad that with ES2015 modules that have support for both synchronous and asynchronous loading, we can finally just stick to one approach. Although it has not been fully rolled out in browsers and in Node, we can always use transpilers to convert our code.

47. What's the difference between call and apply?

Both call and apply are used to invoke functions and the first parameter will be used as the value of this within the function. - call takes in comma-separated arguments as the next argument. - apply takes in an array of arguments as the next argument. function add(a, b) { return a + b; } console.log(add.call(null, 1, 2)); ==> 3 console.log(add.apply(null, [1, 2])); ==> 3

2. What is Scope in JavaScript?

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

37. What is Currying?

Currying is when we break down a function that takes multiple arguments into a series of functions that take part of the arguments. This function takes two arguments, first and second and returns their sum. function add (first, second) { return first + second; } function add (first) { ==> curried function return function (second) { return first + second; } } In an algebra of functions dealing with functions that take multiple arguments or equivalent one argument that is a Tuple is somewhat inelegant, say, f(x,y).

11. Explain event bubbling and how someone may prevent it?

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

45. Why is extending built-in JavaScript objects not a good idea?

Extending a built-in/native JavaScript object means adding properties/functions to its prototype. It may seem like a good idea at first but it is dangerous in practice. Imagine our code uses a few libraries that both extend the Array.prototype by adding the same contains method. The implementations will overwrite each other and our code will break when the behavior of two methods is not the same. The only time we may want to extend a native object is when we want to create a polyfill essentially providing our own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it is an older browser.

26. What is IIFEs?

It's an Immediately-Invoked Function Expression (IIFE for short). It executes immediately after it is created and often used to avoid polluting the global namespace because all variables inside an IIFE (like any normal functions) are not visible outside its scope. (function IIFE() { console.log( "Hello!" ); })(); ==> "Hello!"

6. Explain null and undefined in JavaScript?

JavaScript (and by extension TypeScript) has two bottom types null and undefined. They are intended to mean different things - Something has been uninitialized undefined. - Something is currently unavailable null.

1. Explain equality in JavaScript?

JavaScript has both strict and type-converting comparisons. Strict comparison (===) checks for value equality without allowing coercion. Abstract comparison (==) checks for value equality with coercion allowed. var first = "45"; var second = 45; first == second; ==> true first === second; ==> false Some simple equality rules - If either value in comparison could be true/false or these specific values (0, empty string, empty array) avoid == and use === but in all other cases, we are safe to use == and in many cases it simplifies the code in a way that improves readability.

24. How to compare two objects in JavaScript?

Non-primitive values like objects (including function and array) are being compared by reference so both == and === comparisons will simply check whether the references match. For example arrays are by default coerced to string by simply joining all the values with commas in between. So two arrays with the same contents would not be equal var first = [1,2,3]; var second = [1,2,3]; var third = "1,2,3"; first == third; ==> true second == third; ==> true first == second; ==> false For deep object comparison use external libraries like deep-equal or implement your own recursive equality algorithm.

31. What is the drawback of creating true private method in JavaScript?

One of the drawback of creating a true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. var Employee = function (company, salary) { this.company = company || ''; this.salary = salary || 5000; var increaseSalary = function () { this.salary = this.salary + 1000; }; ==> private this.dispalyIncreasedSalary = function() { ==> public increaseSalary(); console.log(this.salary); }; }; var first = new Employee("Pluto", 3000); var second = new Employee("Pluto", 2000);

10. What is a Polyfill?

Polyfill is essentially a specific code/plugin that would allow you to have some specific functionality that is expected in current or modern browsers to also work in other browsers which do not have the support for that functionality built-in. - Polyfills are not part of HTML5 standard. - Polyfills are not limited to JavaScript.

42. What advantages are using arrow functions?

Scope safety => Every new function defines its own this value (a new object in the case of a constructor but undefined in strict mode). Arrow functions do not create their own this and this value of the enclosing execution context is used. Compactness => Arrow functions are easier to read and write. Clarity => Any regular function immediately sticks out for defining the scope when almost everything is an arrow function. A developer can always look up the next-higher function statement to see what this object is.

15. What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

Some examples of languages which compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript. Advantages - Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns. - Enables us to write shorter code by providing some syntactic sugar on top of JavaScript. - Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time. Disadvantages - Require a build/compile process as browsers only run JavaScript and our code will need to be compiled into JavaScript before being served to browsers. - Debugging can be a pain if our source maps don't map nicely to our pre-compiled source. - Most developers aren't familiar with these languages and will need to learn it. There's a ramp up cost involved for teams if they use it for the projects. - Smaller community (depends on the language) which means resources, tutorials, libraries, and tooling would be harder to find. - IDE/editor support might be lacking. - These languages will always be behind the latest JavaScript standard. - Developers should be cognizant of what their code is being compiled to — because that is what would actually be running and that is what matters in the end. Practically ES2015 has vastly improved JavaScript and made it much nicer to write.

43. What is the motivation for bringing Symbol to ES6?

Symbols are a new special kind of object that can be used as a unique property name in objects. Using Symbol instead of strings allows different modules to create properties that do not conflict with one another. Symbols can also be made private so that their properties can not be accessed by anyone who does not already have direct access to the Symbol. Symbol is a new primitive just like the number, string and boolean primitives. Symbol have a function that can be used to create them. Symbols do not have a literal syntax unlike the other primitives. The only way to create them is with the Symbol constructor in the following way let symbol = Symbol(); Symbols are just a slightly different way to attach properties to an object - we could easily provide the well-known Symbols as standard methods like Object.prototype.hasOwnProperty which appears in everything that inherits from Object.

46. Explain Function.prototype.bind?

The bind() method creates a new function that when called; its this keyword has set to the provided value with a given sequence of arguments. It is most useful for binding the value of this in methods of classes that we want to pass into other functions. This is frequently done in React components.

4. What is object type?

The object type refers to a compound value where we can set properties that each holds their own values of any type. var person = { name: "Mosh", age: 40, isMarried: true }; person.name; ==> Accessed with dotted notation. person["name"]; ==> Accessed with bracket notation. Bracket notation is useful when we want to access a property/key but the name is stored in a variable. var person = { name: "Mosh", age: 40 }; var name = "name"; person[name]; ==> "Mosh"

18. Explain the same-origin policy with regards to JavaScript?

The same-origin policy prevents JavaScript from making requests across domain boundaries. Origin is defined as a combination of URI scheme, hostname, and port number. It prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

36. What are the benefits of using spread syntax in ES6 and how is it different from rest syntax?

The spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create, slice or a library function. This language feature is used often in Redux and rx.js projects. function putDookieInAnyArray(arr) { return [...arr, 'dookie']; } const result = putDookieInAnyArray(['I', 'really', "don't", 'like']); ==> ["I", "really", "don't", "like", "dookie"] const person = { name: 'Todd', age: 29 }; const copyOfTodd = { ...person }; The rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax taking data and stuffing it into an array rather than unpacking an array of data. It works in function arguments as well as in array and object destructuring assignments. function addFiveToABunchOfNumbers(...numbers) { return numbers.map(x => x + 5); } const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); ==> [9, 10, 11, 12, 13, 14, 15] const [a, b, ...rest] = [1, 2, 3, 4]; ==> a => 1, b => 2, rest => [3, 4] const { e, f, ...others } = { e: 1, f: 2, g: 3, h: 4, }; ==> e => 1, f => 2, others => { g: 3, h: 4 }

30. Explain the difference between undefined and not defined in JavaScript?

When we are going to use a variable that does not exist and has not been declared then JavaScript will throw an error and the script will stop executing thereafter but If we use typeof undeclaredVariable it will return undefined. Let's understand the difference between declaration and definition. - var first; is a declaration because we are not defining what value it holds but we are declaring its existence and the need of memory allocation. - var first = 10; is both declaration and definition. Every variable and function declaration brings to the top of its current scope in which it is declared then assignment happens in order. This term is called hoisting. A variable that is declared but not defined is undefined. var first; typeof first; ==> true A variable that is neither declared nor defined when we try to access it, It will result not defined. console.log(first); ==> ReferenceError first is not defined.

27. Describe Closure concept in JavaScript?

add function is able to remember what x value was passed to adder function call. function adder(x) { // Parameter `x` is an inner variable. // `add()` is an inner function and uses `x` so it has a closure over `x`. return function add(y) { return y + x; }; } var plusOne = adder(1); var plusTen = adder(10); plusOne(3); ==> 1 (x) + 3 (y) = 4 plusTen(12); ==> 10 (x) + 12 (y) = 22 When we declare a function within another function then the local variables can remain accessible after returning from the function we called in JavaScript but in C and most other common languages all the local variables are no longer accessible because the stack frame is destroyed after a function returns. A closure is a stack frame that is allocated when a function starts its execution and is not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!). We can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

21. What's the difference between throw Error('msg') vs throw new Error('msg')?

var error = Error('message'); var error = new Error('message'); Both are fine. The function call Error(...) is equivalent to the object creation expression new Error(...) with the same arguments.


Ensembles d'études connexes

Integumentary System Assignment 3

View Set

How to Drive Chapter 15, AAA Chapters 1-17

View Set

Care of Patients With Pituitary and Adrenal Gland Problems

View Set

Quizzes BLW (26,27,28) Article 3 of the UCC

View Set

Quizlet: Dec. 2 Division math Vocabulary/ practice each day for 5 minutes.

View Set

BUS 110 Chapter 6. Entrepreneurship and starting a small business, Chapter 6 Introduction to Business

View Set