JS/TS Short/Long Answer Questions

Ace your homework & exams now with Quizwiz!

Good accessibility guidelines

- Assign `aria-role` to each element (there are many for each type of element) - Using the `alt` attribute for images. - Using `aria-disabled` if a button is disabled. - Using semantic HTML tags - When an action leads to a redirection to a different page, that element should be a link not a button. - Color is not a good way to bring attention to something due to various color related vision problems people may have. - A good focus element effect should add a thick outline to the element (not the hover effect).

What is a first-class function?

A programming language has first-class functions if functions in that language are treated like any other variable. This means that they can be passed into functions, returned from functions, and be assigned to a variable. JS allows for first-class functions. Important for JS as it allows high-order functions and callbacks to name a few.

What is a pure function?

A pure function returns the same value/set of values for the same input. This means it is therefore not dependent on state exterior to the function and does not trigger any side effects. It is therefore virtually impossible to write a program using exclusively pure functions. API calls, writes to a database, DOM manipulation are all events that are considered impure due to the external nature of these events.

What is a race condition?

A race condition is something that occurs when two or more processes try to access and change the same shared resource. More colloquially speaking, race conditions can broadly refer to undesirable behavior that is dependent on the sequence of events that are usually out of its control. This technically does not happen in JS due to it being single-threaded. It could happen if you call multiple asynchronous operations in a sequence whose times to complete are unknown -- in this case race conditions can appear to have occurred. In the example below, we can't guarantee that the time to await a response from the API will result in the results being rendered in sequence. Example: input.addEventListener("keyup", async () => { const response = await fetch(`url/to/ac/${input.value}`); displayResponse(response); // display response });

What is a `static` method or property?

A static property/method is a method/property defined in a class in which an object does not have to be instantiated in order to call it. Example: class ClassWithStaticMethod { static staticProperty = 'someValue'; static staticMethod() { return 'static method has been called.'; } static { console.log('Class static initialization block called'); } } console.log(ClassWithStaticMethod.staticProperty); // output: "someValue" console.log(ClassWithStaticMethod.staticMethod()); // output: "static method has been called."

What is AJAX?

AJAX stands for `Asynchronous Javascript and XML`. AJAX is an API allows for asynchronous HTTP requests to be sent to/received from the client. Previously, if a POST request was sent to a server, a whole new HTML file would be sent back due to it being synchronous. Technically not used very often now due to a preference for JSON over XML.

What does ARIA stand for?

Accessible Rich Internet Applications

What is an ORM?

An ORM, or object relational mapping, allows you to write easy to understand objects with simple notation that end up getting converted to low-level SQL.

What is a tuple?

An array with a pre-defined length and types for each element in it. // define our tuple let ourTuple: [number, boolean, string]; // initialize correctly ourTuple = [5, false, 'Coding God was here'];

What are the list of falsy values?

Boolean('') // false Boolean(0) // false Boolean(-0) // false Boolean(NaN) // false Boolean(null) // false Boolean(undefined) // false Boolean(false) // false Any object object/primitive value not listed will be converted to "true"

What are two ways a type can be casted in Typescript?

Casting with `as`: let x: unknown = 'hello'; console.log((x as string).length); Casting with `<>`: let x: unknown = 'hello'; console.log((<string>x).length);

Difference between const and let

Const can only be assigned to a value/reference once. Let can be reassigned. Both are block scoped (available within curly braces of switch...case, if-else, for loop).

What does cross-site scripting (XSS) do?

Cross site scripting is writing Javascript that sends requests to different servers which may record data from another

What is currying?

Currying is when a function — instead of taking all arguments at one time — takes the first one and returns a new function, which takes the second one and returns a new function, which takes the third one, etc. until all arguments are completed. Good for breaking functions down into smaller more maintainable bits of logic.

What is debouncing and how do you implement a debounce function in Javascript?

Debouncing essentially delays a function from being executed after a delay has elapsed. If our debounce period is 5 seconds and the user clicks the button once and then again after 3 seconds, the delay will be reset and the action will be dispatched after 8 seconds (provided there are no successive clicks). Essentially we pass in our debounce function as the second argument to an addEventListener function. In the debounce function let's declare a variable that is initially undefined and will hold the reference to a setTimeout function that executes the callback function after the specified delay. If such a setTimeout function exists in the variable, let's clear it to prevent the callback from being executed and then create a new setTimeout function assigned to the variable. function debounce(cb, timeout) { let timeOutFunction; return () => { if (timeOutFunction) { clearTimeout(timeOutFunction); } timeOutFunction = setTimeout(cb, timeout); } } document.getElementById('debounce').addEventListener('click', debounce(() => console.log('API Call!') , 2000))

EC2 vs Lightsail

EC2 is essentially a more advanced, configurable version of LightSail. LightSail comes pre-configured with RAM/CPU amounts.

What are enums in Typescript?

Enums represent essentially objects with unchangeable values inside. Example: enum StatusCodes { NotFound = 404, Success = 200, Accepted = 202, BadRequest = 400 } // logs 404 console.log(StatusCodes.NotFound);

Are IIFEs obsolete with ES6?

Essentially yes, the introduction of ES Modules in ES6 solves the problem IIFEs were used for. IIFEs are used to isolate variables and prevent them from bleeding into the global scope, now ES6 Modules allow you to use modules natively in JS.

Implicit vs. explicit type coercion

Explicit type coercion is when the developer explicitly tries to convert the variable/value in question. An example would be Number("3") or String(3).

What does `extends` do when defining generics?

Extends allows us to place constraints on the type passed in/returned by allowing specification of the types expected afterwards. Example: function createLoggedPair<S extends string | number, T extends string | number>(v1: S, v2: T): [S, T] { console.log(`creating pair: v1='${v1}', v2='${v2}'`); return [v1, v2]; }

What is a function declaration and a function expression?

Function expression essentially assigns the function to a variable (let, var, const) that can be called later. As such, they behave according to the hoisting behavior of let, const and var. Function declarations will hoist the function to the top of the code. They are accessible anywhere even if you call the function before the declaration.

When are generics used in Typescript?

Generics essentially create "type variables" that are passed into/returned from functions and classes, allows us to create reusable functions. Example: function createPair<S, T>(v1: S, v2: T): [S, T] { return [v1, v2]; } console.log(createPair<string, number>('hello', 42)); // ['hello', 42] The example allows us to specify the type of the pair that will be passed in as arguments into the function, this pair of generics also gets specified in the return type.

What is Github Actions and how did you use it at Picnic?

Github Actions allows you to run certain processes on different stages of Github actions. You can define this in the `.github/workflows`directory (it is a YAML file kinda like Python). This can link up to EC2 and you can define environment, steps and on events which to trigger these steps.

What does `use strict` do?

It can either be used at function or global scope. - Helps prevent accidentally setting global variables (meaning every variable needs a var declaration). - Cannot delete variables, object, functions. You cannot use let, const, static, interface, etc. (new JS features) along with `use string` mode.

What module format does Node.js inherit from?

It inherits from CommonJS with its require() and module.exports.

How does the `this` keyword work if called within a nested object? Ie. let x = { name = "Steven", child = { childName: "Steven Jr." printParent() { console.log(this.childName + "is " + this.name + "'s child"); } } }

It refers to the immediate parent. This function would have to be called like so and will only have access to the immediate parent: x.child.printParent()

How does the `this` keyword work in an arrow function?

It takes the `this` keyword from its parent function. In the example below this.name would refer to what this.name would be inside the parent x object, which would reference the window. let x = { name = "Steven", printName: () => { console.log(this.name); // points to window object! } }

Is Javascript asynchronous or synchonous?

JS is synchronous and single threaded. Certain operations/lines of code can be made asynchronous with async...await, promises, setTimeout, etc. JS runs all synchronous code first and then moves onto running asynchronous code (if any).

What is the difference between AMD and CommonJS?

Javascript (prior to ES6) did not have any way to import/export modules. CommonJS imports modules synchronously. Importing/exporting modules in Node.js borrows syntax from CJS. CJS is more so used on the backend. //importing const doSomething = require('./doSomething.js'); //exporting module.exports = function doSomething(n) { // do something } AMD (Asynchronous Module Definition) imports modules asynchronously.

What are the JS function for setting/getting/removing local and session storage?

Local storage can be accessed with the `localStorage` object. Session storage is exactly the same with the methods below except accessible with the `sessionStorage` object. `localStorage.setItem()` takes in two arguments, the key of the item in local storage you want to set and the value you want to set it to. Both of these arguments are strings, JSON will not work. `localStorage.getItem()`takes in one argument, the key of the item you are trying to access and returns the value associated with the key. `localStorage.removeItem()`takes in one argument, the key of the item you are trying to remove.

Monolithic vs. microservice architecture

Monolithic architecture means that your entire application is written as one cohesive codebase with access to the same memory resources. Microservice architecture breaks an application apart into several codebases/services of functionality that combine to make up a whole. Pros: Features in an application can have crosscutting concerns, allowing for performance advantages and a codebase that has features more easily interact with one another. Con: Code can become tightly coupled and therefore harder to decouple, making scaling of certain features and maintainability more difficult. Microservices pros and cons: Pros: Easy to scale features independent of the other. - Better organization Cons: - Cross-cutting concerns and designing middleware for all pieces to fit together can be a challenge.

Can `var`, `let` and `const` all be declared without being initialized?

No, const cannot be declared without being initialized.

Is React SEO friendly out of the box?

Not really, it depends on the configuration of it due to it being a SPA, but being an SPA is not conducive to it being SEO friendly. This is because the page starts as a shell of an HTML file lacking any rendered content. Some libraries may aid in this, like React Helmet. Next.js is a React framework that renders pages server side which makes it more friendly to web crawlers.

Explain `Object.freeze()`

Object.freeze() freezes an object and makes it immutable, essentially making it read-only. However, this freeze is shallow, meaning nested objects can be altered.

What is the difference between a value and a reference?

Objects, arrays and functions (arrays and functions are objects) are passed as a reference while primitives (boolean, string, number) are passed as values. Running an equality operator between two objects/arrays checks if they point to the same address in memory. const ar1 = [1]; const ar2 = [1]; console.log(ar1 === ar2); // false console.log(ar1 === [1]); // false const ar11 = ar1; console.log(ar1 === ar11); // true console.log(ar1 === ar1); // true

One way vs two way data binding?

One way data binding means that data flows from parent to child components. If an element on the user interface is interacted with, an action is dispatched which may change the state. In two way data binding, the state is linked directly to the element. Can make it difficult to reason about state changes,

Cookies vs. session/local storage?

See the question about session storage vs. local storage. Cookies have a maximum size of 4kb while local/session storage have a maximum size of 10mb and 5mb respectively. Local/session storage are only on the browser while cookies are sent to the server with every request the user makes to it (image, CSS, JS, etc.). This is the reason why cookie data is small, it could potentially strain the server if the data sent with each request becomes too big with the cookie data.

Explain semantic versioning?

Semantic versioning is a system for naming version changes. Versioning uses the following system: X.Y.Z X (MAJOR) = backwards incompatible changes to code Y (MINOR) = feature change (backwards compatible) Z (PATCH) = bug fix

What is the difference between session storage and local storage?

Session storage is only available as long as that tab with the data persists, accessible only within a tab. Multiple instances of the site across different tabs will have different session storage. Local storage is available in any tab you have in the browser. Expiration is set within the code for creating the data or if the user manually deletes it from the browser.

What is the difference between creating a string with `let x = "hello"` vs. `let x = new String("hello")`?

The difference is that the former assigns a primitive value of a string to the variable `x`. The latter uses a constructor function to create a string object.

Intersection type

The intersection type combines two data types into one. This is used with the "&" symbol. If there are duplicate properties/methods, the last passed in property will be what that property is in the new type/interface. Example: type Person = { name: string } type Doctor = { medicalField: string } let doctorTom: Person & Doctor = { name: 'Tom', medicalField: 'Cardiologist' }

What is the `some()` array method?

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

How does the spread operator work?

The spread operator creates a deep copy of an array or objects elements. The only time the copy is not a deep copy is if the object is nested, in this case the nested object is made into a shallow copy. const a = [1,2,[3,4]] const b = [...a]; a[0] = 619; console.log(b[0] // 1 a[2][0] = 5; console.log(b[2][0]) // 5 To avoid the nested array/object from referencing the same object, use the spread operator once more to create a deep copy. JSON.parse(JSON.stringify()) is preferred.

What is the type of `undefined` and what is the type of `null`?

The type of `null` is an object, the type of undefined is undefined.

Union type

The union type is used described to describe a value that can assume different data types. This is used with the "|" symbol. Example: let test: string | number = 3; // test can be either a number or string.

Are arrow functions hoisted? Are they anonymous?

They are not hoisted because they need to be assigned to a variable (essentially a function expression). They are always anonymous functions, they can only be assigned to a variable.

How can cookies be accessed and set?

They can be accessed via the `document.cookie` object on the document object. Ie. document.cookie = "name=Steven;"

Why does this code output (6,6,6,6,6,6): (function timer() { for (var i=0; i<=5; i++) { setTimeout(function () { console.log(i) }, i*1000); } })(); But this outputs (0,1,2,3,4,5): (function timer() { for (let i=0; i<=5; i++) { setTimeout(function () { console.log(i) }, i*1000); } })();

This is because in the first example with i being declared as a var and is function scoped. Because the for-loop finishes executing before the setTimeout callback and because var is function scoped, i will reference 6 when it is attempted to be accessed by the callback Using "let", on the other hand, creates a block scoped element, therefore a new scope is created with each run of the for-loop. The callback will search for "i" in its scope, each of which is a "unique" block scoped element.

Why has jQuery been largely made obsolete?

This is due to features in ES6 making vanilla Javascript more competent. For example, the introduction of `querySelector()` make $() in jQuery less useful.

How many types of type conversion are there in JS?

Three types: to a string, to a number and to a boolean. Objects, arrays, etc. can only be converted in the following three ways. There is no way for a value to become converted to an object.

What is throttling and how can we create a throttle function in Javascript?

Throttling is triggering a certain event when an action is performed the first time. On subsequent actions within a specified timeframe, the event will not be dispatched. Ie. User clicks a button to make an API call. Let's trigger the API call on the first click but if the user clicks the button within, for example, 5 seconds, prevent the API call from being made. Code: function throttle(cb, timeout) { let throttleID; return function() { if (throttleID) return; else { cb(); throttleID = setTimeout(() => { throttleID = undefined; }, timeout) } } } document.getElementById('debounce').addEventListener('click', throttle(() => console.log('API Call!') , 5000))

When can `let` and `const` be redeclared?

When not in the same block scope. This is known as shadowing. Example: let a = 1; { let a = 2; console.log(a); // 2 } console.log(a) // 1

How can we extend a class in JS?

With the `extend` keyword. Ie. class Person() { constructor(name) { this.name = name; } } class Doctor extends Person () { constructor(name, specialty) { super(name); this.specialty = specialty; } }

How can an array be flattened in Javascript?

With the flat() method on the Array object. You can also specify how deep you want the recursion to go on the flatten method.

Are const and let hoisted?

Yes they are, but they exist in the temporal deadzone. They are hoisted but not accessible and will throw an error: Uncaught ReferenceError: can't access lexical declaration 'l' before initialization.

When should `type` be used as opposed to `interface`?

`Interface` and `type` have a lot of overlap. Interface should ideally be used when defining properties and methods on an object. Mostly appropriate for better readability of code to make it explicit that it will be used for an object/class. Interfaces cannot be used with primitives or unions while types can be used with them.

What is the difference between `never` and `void` return types?

`never` refers to a function that never returns like an infinite loop or an error being thrown. `void` is used when a function doesn't explicitly return anything (however, all void functions will return `undefined`).

When to use `any` vs `unknown` in TS?

`unknown` should be used when the data's type is unknown and should therefore be checked in some way. A useful example of this is an API call and having to check that the data is of the correct type. The TS compiler won't allow any operation on values typed unknown

How can we create a constructor function?

function Person(firstName, lastName, age, eyeColor) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.eyeColor = eyeColor; this.changeName = function (name) { this.lastName = name; }; } // Then call Person with the new keyword to return the object. const steven = new Person('Steven', 'Wyks', 23, 'brown'); IMPORTANT: There is no returned value in a constructor function! It implicitly returns `this` Differs from a factory function in that the factory function will have a return statement with the object.

How can we create a constructor function?

function PersonMaker (firstName, lastName, eyeColor) { let person = {firstName, lastName, age, eyeColor}; person.printDetails = () => { console.log(`My name is ${firstName} ${lastName} and I'm ${age} years old. I have ${eyeColor} eyes.`); }; return person; } Differs from constructor function, doesn't need to use the `new` keyword.

How can we set a default type in generics in Typescript?

function makeState<S extends number | string = number>()


Related study sets

AT BOC Prep Domain III - Immediate and Emergency Care

View Set

Chapter 13 - Final Exam - MIE 330

View Set

Ch 4 How to Form a Business SmartBook

View Set

Operating and Financial Leverage

View Set

Management & Supervision in LE 7th Edition (Ch 8 Definition & Notes)

View Set

The Tempest Act 1-2 Test FREE RESPONSE

View Set

Champions - Promulgated Contract Forms

View Set

Law of Business Organizations Exam 1- 1, 23, 24, & 26

View Set