My Javascript Set

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

What's the difference between != and !== ?

!= not equal value !== not equal value or not equal type

How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1. function isInt(num) { return num % 1 === 0; }

What's the difference between a while and a do while loop?

A while loop checks for condition first, and then executes the body. A do while loop executes the loop body first, then checks the condition.

Explain AJAX in as much detail as possible.

AJAX is acronym for Asynchronous JavaScript and XML. It is the use of the XMLHttpRequest object to communicate with server-side scripts. -Its asynchronous nature allows it to communicate to the server without reloading the page. This lets you update portions of a page based upon user events without refreshing the page, resulting in a better user experience. -It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files

What is the difference between classical inheritance and prototypal inheritance?

Class Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the `new` keyword. Class inheritance may or may not use the `class` keyword from ES6. Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or `Object.create()`. Instances may be composed from many different objects, allowing for easy selective inheritance.

What is debouncing and why is its benefits?

Debouncing is a process of holding off until a certain event has stopped occurring and handling everything at the end of it is what's called. A debounce is a higher-order function, which is a function that returns another function. It delays the processing of the event until the user has stopped triggering the event for a predetermined amount of time. This prevents your UI code from needing to process every event and also drastically reduces the number of API calls sent to your server.

Why use debouncing?

Debouncing is used to reduce overhead by preventing a function from being called several times in succession. It allows for a smooth and better user experience. Common scenarios for a debounce are resize, scroll, and keyup/keydown events. In addition, you should consider wrapping any interaction that triggers excessive calculations or API calls with a debounce.

What's the difference between variable declaration vs initialization?

Declaration is creating a variable. You declare a JavaScript variable with the var keyword. While initialization is assigning the variable its initial value.

What is Docker?

Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.

What does this line mean? if(!(key ** 2 in storageObj)){ return false }

It's a if statement that asks whether (key to the power of 2) does not exist in the object 'storageObj'. If it does not exist, then return false if(key ** 2 in storageObj) by itself means is (key^2) a key in storageObj

Explain Values and Types in JavaScript

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

What is pagination?

Pagination is how a document is divided into pages.

What's a DOM?

The Document Object Model is a model for interacting with HTML. It is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Javascript functions are executed on HTML elements which are found through the DOM.

What is Array.filter?

The filter() method creates a new array with all elements that pass the test implemented by the provided function. function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]

What is Array.map?

The map() method creates a new array with the results of calling a provided function on every element in this array. var numbers = [1, 5, 10, 15]; var roots = numbers.map(function(x){ return x * 2; });

What does blocking means?

Things on the stack that are slow running

Explain reference data

Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object's location in memory. The variables don't actually contain the value.

When should you use an object?

When order is not important. Objects provide for fast key-value pair lookups. When you need fast access / insertion and removal. They are a good candidate if you have a unique key.

Why use an IIFE (Immediately Invoked Function Expression)?

to encapsulate some code within a local scope so the variables inside do not leak to the global scope

Explain 'this' in javascript

'this' is a reference to the object that is executing this piece of code. 'this' normally refers to the object which 'owns' the method, but it depends on how a function is called. 'this' refers to the object scope that was called on. The this object is bound at runtime based on the context in which a function is executed: When used inside global functions, this is equal to window in nostrict mode and undefined in strict mode. 'this' also refers to the window when it is use inside a callback function that is not binded whereas 'this' is equal to the object when called as an object method, as a constructor, call and apply, bound functions, as dom event handler. If the function is an arrow function, it ignores all the rules above and receives the 'this' value of its surrounding scope at the time it is created. When a function is used as an event handler, this refers to the element the event was fired from. $(this).addClass(highlighted);

What does this line mean? counterMap[item] = (counterMap[item] || 0) + 1

(counterMap[item] || 0) returns whatever value that is more truthy. If counterMap[item] is undefined, then it would take on the value of 0 since 0 is more truthy than undefined. But if counterMap[item] is 1,2,or whatever, then it would be that value instead of 0

How would you develop a website which handles high traffic?

* Fewer lines of code, made possible by concise languages like Scala and Ruby, generally translates to higher productivity for application developers. * Get a good and reliable web hosting service. CHOOSE YOUR HOSTING WISELY On a typical SHARED HOSTING account, you might be sharing server space with dozens of other companies, and the speed of your website is affected by the number of people using that server. For more, consider DEDICATED HOSTING, where you alone have access to the server, or a VPS(virtual private server). * If you have multiple css, combine into one css to reduce the number of requests. Same with javascript * If your images, javascript, or css (ie. they're static) are not changing dynamically on the pages, cache them so that there loading is fast. * Check that you don't have info and debug logs enabled on production environment. * Use CDN. A CDN takes a website's static files - such as CSS, images and JavaScript - and delivers them on servers that are close to the user's physical location. Because servers are closer to the user, they load more quickly. * Use expires headers. When a user visits your website, your website files will be stored on their computer so that your website loads faster for them the next time the visit; there's an expiration date in the file header that determines how long these files will be stored on their computer, usually set to 24 hours by default. You can configure the expires header so that the files never time out or increase the expiration time significantly * Enable compression. You can compress resources to lower the number of bytes a page is sending over a network. Using the GZIP

List ways to decrease page load time

* Optimize images: Adopting new image formats, such as WebP and JPeg XR, can also help reduce image weight by 20-50 % without sacrificing quality. * Browser caching: Enabling browser caching lets you temporarily store some data on a visitors' computer, so they don't have to wait for it to load every time they visit your page. * Compression/Minifying: You can use GZIP for instance. Compression can dramatically reduce your page's size and thereby increase its speed. * Optimize CSS: Start by asking yourself, "do I use all of my CSS?" If not, get rid of the superfluous code in your files. * Load Javascript after other codes: Put script code at the end or use <script defer> * Avoid Redirects: Redirects usually require extra processing time. Instead, serve the site to the users directly * Use CDN: You may use a Content Delivery Network (CDN) such as Amazon Cloudfront. Access to a faster server near your user's geographical location ensures faster loading time for your site.

What is event delegation?

* a technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements * allows you to utilize event bubbling Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant.

What's the difference between i++ vs ++i?

++i increments the variable, returning the new value. i++ increments the variable, but returns the old value. var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43

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 is using the global namespace to define their own variables, there will be bound to be collisions. --> Anyone can update a global variable from any point in the program --> Particularly bad in JS because JS defaults all variables to the global scope unless they are explicitly defined elsewhere (ex: forgetting var)

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

--> Extending a built-in/native JS object means adding properties/functions it its prototype. --> Bad because if your code uses a few libraries that both extend the Array.prototype by adding the same contains method, the implementations will overwrite each other and the code will break if the behavior is not that same. --> Also, if a browser decides to implement its own version of your method, your method might get overridden and the browser's implementation would take over --> Only time you want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JS specification, but might not exist in the user's browser due to it being an older browser

What language constructions do you use for iterating over object properties and array items?

--> Objects: 1. For in loops → for (var property in obj) { console.log(property); } + This will also iterate through its inherited properties 2. Object.keys( ), Object.values( ) --> Arrays: 1. For loops: + Use let instead of var so that the iterator has block scope instead of function scope (as var does) 2. forEach: + This can be more convenient at time because you do not have to use the index if all you need is the array elements 3.array.map()

Explain the difference between synchronous and asynchronous functions.

--> Synchronous: + statements runs after each other in a line. Each statement has to wait until the last statement is done. + Blocking code --> Asynchronous: + Code is non-blocking. Multiple statements can occur at the same time and will continue without blocking other statements + Usually accept a callback as a parameter and execution continue on the next line immediately after the async function is invoked + Good for heavy duty operations like loading data from a web server or querying a database

Explain the difference between blocking vs non-blocking

-Blocking refers to operations that block further execution until that operation finishes. Synchronous codes are typically blocking. -Non-blocking refers to code that doesn't block execution. Asynchronous codes are typically non-blocking. One advantage of non-blocking, asynchronous operations is that you can maximize the usage of a single CPU as well as memory.

What's the difference between a variable that is: null, undefined or undeclared?

-Undefined is a variable that has been declared but no value exists and is a type of itself 'undefined'. -Null is a value of a variable and is a type of object. -Undeclared variable is a variable that has been declared without var keyword.

Describe the difference between cookies and localStorage

-cookies store very small amounts of data (4k bytes), set expiration date -localstorage can store more data (2.5-5MBs depending on browser) and doesn't expire when the user ends the session. Storage objects work much like regular JavaScript objects: simply set a property of the object to a string, and the browser will store that string for you. -localStorage = persistant and scoped to the domain. -Cookies = the old school way of doing all of the above. Stores name/value pairs per domain.

What kind of things must you be wary of when developing for multilingual sites?

-language direction can be set with <html dir="rtl" -Character encoding: making sure you have the correct character encoding (unicode - UTF-8) -Font-size: since scripts vary in size, font size is important and should vary depending on the language. -Length of words: content may take up more space for some languages than others

Difference between document load event and document ready event?

-ready means DOM (webpage interface) is ready. -load means the page fully loaded. Includes inner frames, images etc.

List some examples of asynchronous codes

-setTimeout -API call -Codes that use async await -Codes that use promise

What is the difference among var, let, and const?

-var - Hoisted within function scope (function()) -let - Hoisted within block scope (if, while, for) -const - Hoisted within block scope (if, while, for). You can only assign the value once and cannot reassign a new value

Why use a closure?

1. Data privacy/emulating private methods - only methods with access to its scope are able to access specific data 2. Partial applications or currying: + Partial applications: applying a function to some of its arguments- a function that takes a function with multiple parameters and returns a function with fewer parameters + Curry: A function that takes a function with multiple parameters as input and returns a function with exactly one parameter

How do you serve a page with content in multiple languages?

1. You must have translated/localized pages on the server for each language you intend to support. 2. Your server must recognize the browser's language request. 3. You must carefully name the files for the localized pages, so the server has a systematic way of locating them. 4. You need a method for serving a generic page when you don't have the requested language.

What is a closure?

A closure is an inner function that has access to the outer function's variables, even after the parent function has closed. This function retains the initial variable values of its parent scope even when that value changes in the parent scope. In JavaScript, closures are created every time a function is created/defined, at function creation time. To create a closure, define a function inside another function and expose it by returning it or passing it to another function.

What is a constructor?

A constructor is basically a function inside a class and it will get called whenever we create an object of that class. In React, this is typically where variables are stored and functions are binded

What is a recursive function?

A function that calls itself from within. All recursive function calls must have a base case to exit. A base case is a specific condition that causes the function to return a value instead of calling itself again. It's basically the answer to a problem at the lowest possible level. If there's no base case, it would result in this error "Uncaught RangeError: Maximum call stack size exceeded"

What is an anonymous function? When do you use one?

A function without a name. When you only plan to use the function once. It keeps codes more readable and maintainable --> Can be used in IIFEs (Immediately Invoked Function Expression) to encapsulate some code within a local scope so the variables inside do not leak to the global scope --> As a callback that is used once and does not need to be used again (easier to read and more self-contained) --> Arguments to functional programming constructs (map, forEach, etc.)

What is a Polyfill?

A polyfill is essentially the specific code (or plugin) that would allow you to have some specific functionality that you expect in current or "modern" browsers to also work in other browsers that do not have the support for that functionality built in. Polyfills are not part of the HTML5 standard Polyfilling is not limited to Javascript

What is a promise?

A promise represents the eventual result of an asynchronous operation. It is a placeholder for either the successful result value or reason for failure. --> It is an object that may produce a single value some time in the future: either a resolved value or a reason that it's not resolved. Has three states: fulfilled, rejected, pending + promise is settled if it's not pending --> Promise users can attach callbacks to handle the fulfilled value or the reason for rejection

Explain some of the pros and cons for CSS animations versus JavaScript animations.

CSS animations are lighter but less robust, JS gets you a lot more customization options (timing in seconds vs. percentages, starting, stopping and reversing animations, etc.)

What is a pure function? What's the benefit of using them?

A pure function's output is solely dependent on the arguments it receives and not something outside of the function scope. Given the same input, will always return the same output. As a result, it produces no side effects. Pure functions are a pillar of functional programming. eg. function pureFunction(a) { var b = 1 a = a * b + 2 return a } It makes our code easier to read, test, and most importantly more predictable. It constrains side effects to a definitive location and eliminating as much of them as possible. This approach will justify itself many times over, when your programs start growing in size and complexity.

When do you use a while loop? When do you use a for loop?

A while loop allows us to loop over a block of codes as long as a certain condition is true. The while loop is generally better when you don't have an iterator. It's good when you need to repeat a block of codes an unknown number of times until a specific condition is met. It is best suited when you do not know ahead of time the number of iterations that you need to do, when you want an action to repeat itself until a certain condition is met. Think of it as an if statement, but for looping For loop is more compact and it's good for iterating through an array. A for loop is used when you want to iterate through an an iterable

What is D3.js used for?

Abbreviated from Data-Driven Documents, D3 is a javascript library that makes graphic within a webpage from data and animates them. Makes building visualization easier

What is an array and when should you use it?

An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions: - Use array when you need to depend on the order of the elements in the collection. - Use array when you want to store a collection of objects that are of one type and that logically belong together. - Otherwise, don't use it

What is an infinite loop and when does it happen?

An infinite loop happens when the looping condition is never gonna be false. It happens when you forget to increment something or change a specific value, or the value never changes and the looping condition just stays true forever.

What is an object in relation to class?

An object is an instance of a class. Let's say we make a Book class. Class is a blue print of any book. It's a specification of what a book is in our program. But the object instantiation is the actual book. There, you can add specific info of a book info to the object.

What's a call stack?

An ordered set of stack frames. it's like a todo list of function invocations. It keeps track of which function has been invoked but hasn't returned yet. It's a data structure which records where in the program we are. Most recently invoked function is on top of the stack and gets run first. First function to be invoked is on the bottom of the stack. The stack is processed from top to bottom. It utilizes the principle of Last In, First Out, a principle to temporarily store and manage function invocation. It means that the last function that gets pushed into the stack is the first to be popped out, when the function returns or ends. Just think of book stacking, you add the last book on top of the stack, but if you want to remove it, then you remove the last book on top of the stack. So whatever get pushed to the stacked last will be the first to return and get popped off the stack. For functions that has a direct return without calling other functions, it gets called and removed from the stack right away.

Explain equality in JavaScript

Equality is comparing two values with the == and === sign. JavaScript has both strict and type-converting comparisons: Strict comparison (e.g., ===) checks for value equality without allowing coercion. The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and therefore the types must be the same to be considered equal. Abstract comparison (e.g. ==) checks for value equality with coercion allowed var a = "42"; var b = 42; a == b; // true a === b; // false

Explain event bubbling and how one may prevent it

Event bubbling is the concept in which an event triggers at the deepest possible element, which in turn triggers the parent elements in nesting order. As a result, when clicking on a child element, one may exhibit the handler of the parent activating. One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

What's the difference between event, event listener, and event handler

Event- something which happened. E.g. Mouse clicks, key down,etc Event Handler- A callback which is usually called when there is an event Event Listener- Detect an event and call the event handler

What is the pros and cons of functional programming?

FP Pros: — Utilizing pure functions, leads to reliable functions with no side effects that accomplish and return exactly what you expect them to. — FP utilizes a more declarative style, which focuses more on what to do and less about how it's being done. This places the emphasis on performance and optimization, leaving the door to refactor without completely reworking your code. FP Cons: — Functional programming is a newer paradigm. It's much easier to find documentation and information on the OOP approach. — Similar to one of OOP's strengths, functional programming can lack readability at times. Sometimes functions can become very verbose and become difficult to follow comparatively to the object-oriented style.

Explain hoisting and why does it matter?

Hoisting is when a JS declarations such as a var or a function declaration is brought to the beginning of their scope. It makes a variable available on top of the scope, even if it was declared after. However this variable, if accessed, would be undefined since it hasn't been assigned a value Hoisting can cause problems because the variable name is available but its values is not because it has not been assigned a value yet. This can cause some issues with what values are returned, etc. Hoisting will only hoist the declaration, not what is being assigned to it. If you try to gain access to a variable before it's declared , it will return "undefined". Hoisting only applies to var, and not let or const, or function expression

How do you catch an error in async await vs in a promise?

For async await, use throw for successful response and catch for error For promise: use .catch or pass the second argument to promise

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. Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand's type. For instance, if you do: boolean == integer the boolean operand will be converted to an integer: false becomes 0, true becomes 1. Then the two values are compared. However, if you use the non-converting comparison operator ===, no such conversion occurs. When the operands are of different types, this operator returns false, and only compares the values when they're of the same type.

Explain scope

In JavaScript, each function gets its own scope. 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. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

What is let keyword in JavaScript?

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

What is the point of using setTimeout(() => {}), 0)?

It calls a function, but executes that function only once every other synchronous function in the code has done executing.

How is javascript asynchronous?

It doesn't wait for each line of code to finish running before moving on to the next line. This can be seen in request sending. Instead of waiting for the response to come back before executing the next piece of code, we often make a callback function, which would be executed AFTER the response (promise) is sent back . For rapid prototypes, or in cases where speed and timing is not the main concern, going the synchronous way can be more productive. On the other hand, if you're planning to build an application with a lot of I/O and networking tasks, or with a lot of users, then the power of async really starts to shine.

What is a callback function?

It is a function that is passed to another function as an argument and is executed after some operation has been completed. In JavaScript, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function. It's more like a call-after function. Callbacks are a way to make sure certain code doesn't execute until other code has already finished execution. Typically used for API request, event listener, and array iterating methods

Explain HTTP requests

It is an information request message from a client to a server over the hypertext transfer protocol (HTTP). This is the protocol that your browser uses to transfer data such as text and images between a web server and your computer. They are what browsers use to fetch images, text or pages so that the data can be delivered to you. HTTP requests use key words like GET, POST, PUT, DELETE HTTPS, short for HTTP Secure, which allows you to encrypt data that you send and receive. HTTPS is important to use when passing sensitive or personal information.

What does single threaded mean?

It means doing one thing at a time. So if a program is single-threaded, it runs one piece of a code at a time. Javascript Run Time is single threaded but the browser is not, which allows us to use things like AJAX and setTimeout one thread = one call stack = one thing at any given time

What is Array.reduce?

It reduces all the element in the array to a single value. The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. var sum = [0, 1, 2, 3].reduce(function(a, b) { return a + b; }, 0);

What does object.hasOwnProperty("meow") does?

It returns a boolean value letting you know whether the object has the property "meow"

What does CORS stand for and what issue does it address?

It stands for Cross Origin Resource Sharing and it refers to when secure data is being requested from a domain other than the domain from which the content is being served. These types of requests can be a sign that you are being hacked, you can pass a token between your domain and the other domain, to ensure they are trusted.

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 hasn't been initialized : undefined. Something is currently unavailable: null.

What is typeof operator?

JavaScript typeof operator allows you to examine a value and tell you what type it is.

How do you tell if something is an empty object?

Object.keys(obj).length === 0 && obj.constructor === Object Object.keys(obj) converts all the keys of the passed-in object into an array obj.constructor returns whether obj is an array or an object

What's the pros and cons of using Object Oriented Programming(OOP)?

PROS: — Objects and methods are very readable and understandable. — OOP utilizes an imperative style, in which code reads like a straight-forward set of instructions as a computer would read it. CONS: — OOP commonly depends upon shareable state. The unfortunate result of so many objects and methods existing within the same state and being accessed in an entirely undetermined order can lead the pre-discussed concept of "race conditions".

What is prototypal inheritance? When do you want to use it?

Prototypal inheritance is a mechanism in which one object acquires/inherits all the properties and functions of another object or another class. You can make class Toyota inherits class Car by writing class Toyota extends Car{ } It is used for Code Resusability and Method Overriding. You want to use it when you want a new class to have all the properties and behaviors of another class.

What is scope and why does it matter?

Scope is like a border. The area that I'm in and what I have access to in that area. A function's definition dictates the scope of variables. A variable from a lexical scope can be accessed from a local scope, but not the other way around. Ask yourself these question to determine scope: 1/What is the current scope? 2/ Is there any locally declared variables or passed in parameters 3/ If not, what is the lexical scope?

What is a RESTful API?

Stands for REpresentational State Transfer. A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. REST is using the various HTTP methods (mainly GET/PUT/DELETE) to manipulate data. It allows requests to be cacheable so you don't have to serve the same requests again and again. The application can update its data without rendering a whole new page. This allows us to create single page application and native apps for mobile devices that all use the same REST resource Rather than using a specific URL to delete a method (say, /user/123/delete), you would send a DELETE request to the /user/[id] URL, to edit a user, to retrieve info on a user you send a GET request to /user/[id] For example, instead a set of URLs which might look like some of the following.. GET /delete_user.x?id=123 GET /user/delete GET /new_user.x GET /user/new GET /user?id=1 GET /user/id/1 You use the HTTP "verbs" and have.. GET /user/2 DELETE /user/2 PUT /user

What does "use strict" do?

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions. The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake.

What is Array.sort?

The sort( ) method sorts the elements of the array in place and returns a sorted array. The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). By default, the sort() method sorts the values as strings in alphabetical and ascending order. With number, you can add a function that defines an alternative sort order, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

What is the benefit of using switch case over an if else statement?

Switch statement is good when you want to compare one value to a bunch of different values. A switch statement is usually more efficient than a set of nested ifs. ... The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.

What's a call back queue?

The Call Back Queue is where callbacks functions are added to the queue, where they would eventually get executed once the call stack is empty. This is also where user-initiated events like click or keyboard events, or fetch responses are queued before your code has the opportunity to react to them. Or also DOM events like onLoad.

How to check if an object is an array or not?

The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding this let say we have a method called greet which take one single string and also a list of string, so making our greet method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value?

What do we use "break" for?

The break statement exits a switch statement or a loop (for, for ... in, while, do ... while). When the break statement is used in a loop, it breaks the loop and continues executing the code after the loop (if any). When the break statement is used with a switch statement, it breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block.

Explain event loop and its order

The event loop job is look at the call stack and the callback queue. If the stack is empty, it takes the first thing on the queue and pushes it on the stack. The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there's nothing in there, it goes to pick up things in the call back queue. So any synchronous codes get run first, followed by micro-tasks (.then/catch/finally promise callbacks), then by macro-tasks like setTimeout or setInterval codes. Functions passed into setTimeout are considered callbacks

What is the object type?

The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type. Bracket notation is also useful if you want to access a property/key but the name is stored in another variable

What does Grunt and Gulp do?

They are build tools for managing work flow and basically do the same thing. Both are Javascript task runner applications that runs in your command line, automatically performing common or repetitive tasks. Common uses include delinting and debugging, minifying, translating, converting Sass file to CSS and automatically adding autoprefixers necessary. Grunt is older and uses JSOM. Gulp uses regular Javascript.

What does const [boy,girl,woman] = ['con trai','con gai','dan ba'] do?

This JavaScript syntax is called "array destructuring". It means that we're making three new variables: boy, girl, woman and declaring their values on the right. So if you console log girl, you would get 'con gai'

What is the default action of a button?

To submit a form, even if you don't clarify the type="submit", therefore if you don't want it to submit by default, put type="button"

Expalin the difference between event bubbling and event capturing

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.

How would you use a closure to create a private counter?

You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.

How does async await work? When do you use it?

async/await is a syntactical sugar that makes your asynchronous codes read like synchronous codes. It is built on promises. An async function returns a promise. Putting async before a functions makes it return a promise. When you want to call this function you prepend await, and the calling code will stop until the promise is resolved or rejected. Await is saying pause the execution of this async function until you get a result for whatever code is written after the word 'await'. So for this example below, pause this code until getData() is finished running. eg. const resp = await getData( );

What is console.dir used for?

console.dir() lets you inspect the element properties. Console.dir is the way to see all the properties of a specified JavaScript object

What does this line mean? let letter = first[i]; lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;

if letter exists in the object "look up", increment, otherwise set to 1

What's the difference between event.Target vs event.currentTaregt

target is the element that triggered the event (e.g., the user clicked on) currentTarget is the element that the event listener is attached to. It's the element that listens to event. current in currentTarget refers to the present. It's the most recent target that caught the event that bubbled up from elsewhere.

How do you tell if the variable haha is an object?

typeof haha === "object" && haha !==null OR haha.constructor ====> Object

How to empty an array in JavaScript?

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; 1/ arrayList = [ ]; 2/ arrayList.length = 0; 3/ arrayList.splice(0, arrayList.length);

What is string used for?

• String is used because JS needs a wrapper for things that it doesn't understand • String character can be accessed to like an array • Anything being concatenated with a string will become a string, be it undefined, null or Boolean or NaN

What is the difference between event and event handlers?

•Event is something that triggers a block of code to be executed, for example, an element being clicked on or interacted with. •Event handlers are codes that are executed when the event happens. Codes that handle what happens after the event happens


Ensembles d'études connexes

MULTIPLE CHOICE -Chapter 13 Exam - Commercial Crime Insurance and Bonds

View Set

CHAPTER 21 STUDY GUIDE ENLIGHTENMENT AND REVOLUTION TEST REVIEW

View Set

Week 14 - PrepU Transplant & Burn Questions

View Set