1/60
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
How do you detect if JavaScript is disabled on a page?
To detect if JavaScript is disabled on a page, you can use the <noscript> HTML tag. This tag allows you to display content or messages to users who have JavaScript disabled in their browsers
What’s the difference between ‘block’, ‘inline’, and ‘inline-block’?
‘Block’ elements start on a new line and take up the full width available, ‘inline’ elements do not start on a new line and only take up as much width as necessary, while ‘inline-block’ elements allow setting width and height but still flow inline with other elements.
What is the difference between ==
and ===
in JavaScript?
‘==” is the abstract equality operator while “===” is the strict equality operator. The first will compare for equality after doing type conversions. The latter will no do type conversion, so if the two vals are not the same type it will return false.
What’s the difference between state and props in React?
In React, state
is local data storage that in managed within a component and can change over time. Props
are read-only attributes passed from a parent component to a child component.
State is used for data that changes within a component. Props are used to pass data and event handlers to child components.
What’s the difference between a var that is null
and undefined
?
A variable that is null is explicitly assigned to have no value, whereas undefined means a variable has been declared but not assigned a value. Null is an assignment value, while undefined indicates the absence of value.
What is the difference between mouseenter
and mouseover
event in JavaScript and browsers?
The mouseenter event does not bubble and only triggers when the mouse enters the element, while mouseover can bubble and triggers when the mouse enters the element or any of its child elements.
What are the various data types in JavaScript?
Primitive types:
Number
String
Boolean
Undefined - declared var no assigned value
Null - Intentional absence of value
Symbol
BigInt - represents integers with arbitrary precision
Non-primitive types:
Object - used to store collections of data
Array - an ordered collection of data
Function - a callable object
Date
RegExp - regular expressions
Map - a collection of keyed data items
Set - a collection of unique values
What is the difference between a Map
object and a plain object in JavaScript?
A Map object holds key-value pairs where keys can be any datatype, while a plain object uses strings or symbols as keys. Maps maintain the insertion order of elements and have methods for iteration, while plain objects do not guarantee order.
Explain the concept of a callback function in async operations
A callback function is a function passed as an arg to another function, whis is then invoked inside the outer function to complete some kind of routine or action. In async ops, callbacks are used to handle tasks that take time to complete, such as network reqs or file I/O, without blocking the execution of the rest of the code.
Explain the concept of a microtask queue
The microtask queue is a queue of tasks that need to be executed after the currently executing script and before any other task. Microtasks are typically used for tasks that need to be executed immediately after the current operation, such as promise callbacks. The microtask queue is processed after the current script, enabling efficient handling of asynchronous operations in JavaScript.
Explain the concept of caching and how it can be used to improve performance
Caching is a technique used to store copies of files or data in a temp storage location to reduce the time it takes to access them. It improves performance by reducing the need to fetch data from the original source repeatedly. In FE Dev, caching can be implemented using browser cache, service workers, ad HTTP headers like Cache-Control
Browser Cache
The browser cache stores copies of web pages, images, and other resources locally on the user’s device. When a user revisits the website, the browser can load these resources from the cache instead of fetching them from the server, resulting in faster load times and reduced bandwidth usage.
Service workers
Service workers are scrits that run in the background and can intercept network requests. They can cache resources and serve them from the cache, even when the user is offiline. This can significantly improve performance and provide a better user experience.
HTTP caching
HTTP caching is a mechanism that allows HTTP responses to be stored and reused, minimizing the need for repeated retrieval from the server. It enhances performance by leveraging caching headers like Cache-Control and ETag to determine how and when responses can be reused.
Explain the concept of code coverage and how it can be used to assess test quality
Code coverage is a metric that measures the percentage of code that is executed when the test suite runs. It helps in assessing the quality of tests by identifying untested parts of the codebase. Higher code coverage generally indicates more thourough testing, but it doesn’t guarantee the absence of bugs. Tools like Jest can be used to measure code coverage.
Explain the concept of debouncing and throttling
Debouncing and throttling are techniques used to control the rate at which a function is executed. Debouncing measures that a function is only called after a specified delay has passed since the last time it was invoked. Throttling ensures that a function is called at most once in a specified time interval.
Explain the concept of destructuring assignment for objects and arrays
Destructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces to extract values.
Explain the concept of hoisting with regards to functions
Hoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions which are not hoisted in the same way.
Explain the concept of input validation and its importance in security
Input validation is the process of ensuring that user input is correct, safe, and meets the application’s requirement. It is crucial for security because it helps prevent attacks like SQl injection, cross-site scripting (XSS), and other forms of data manipulation. By validating inputs, you ensure that only properly formatted data enters your system, reducing the risk of malicious data causing harm.
Explain the concept of lazy loading and how it can improve performance
Lazy loading is a design pattern that delays the loading of resources until they are actually needed. This can significantly perform performance by reducing initial load times and conserving bandwidth. For exmaple, images on a webpage can be lazy-loaded so that they only load when they come into the viewport. This can be acheived by used the loading=’lazy’
attribute in HTML or by using JavaScript libraries.
Explain the concept of lexical scoping
Lexical scoping means the scope of a variable is determined by its own location within the source code, and nested functions have access to vars declared in their outer scope.
Explain the concept of scope in JavaScript
In JS, scope determines the accessibility of vars and functions at different parts of the code. THere are three main types of scope: global scope, function scope, and block scope.
Explain the concept of TDD
TDD is a software driven dev approach where you write tests before writing the actual code. The process involves writing a failed test, writing the minimum code to pass the test, and then refactoring the code while keeping the tests passing. This ensures that the code is always tested and helps in maintaining high code quality
Explain the concept of the Prototype pattern
The Prototype pattern is a creational design pattern that allows creating new objects by copying an existing object, known as the prototype. This pattern is useful for reducing the overhead of creating new instances and promoting method reuse.
Explain the concept of the Singleton pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system. In JS, this can be implemented using closures or ES6 classes.It restricts instantiation of a class to one object and helps manage shared resources in applications.
Explain the concept of the spread operator and its uses
The spread operator (…)
in JS allows you to expand elements of an iterable into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function.
Explain the concept of the Web Socket API
The WebSocket API provides a way to open a persistent connection between a client and server. Allowing for real-time, two-way communication. Unlike HTTP, which ir request-response based, WebSocket enables full-duplex communication, meaning both the client and server can send and receive messeages independently. This is particularly useful for applications like chat apps, live updates, and online gaming.
Explain the concept of this
binding in event handlers
In JavaScript, 'this' binding in event handlers refers to how the value of 'this' is determined when a function is called. In the context of an event handler, 'this' typically refers to the element that triggered the event, unless an arrow function is used, in which case it retains the value of 'this' from its enclosing scope.
Explain the concept of tree shaking in module bundling
Tree shaking is a technique used in module bundling to eliminate dead code, which is code that is never used or executed. This helps to reduce the final bundle size and improve application performance. It works by analyzing the dependency graph of the code and removing any unused exports. Tools like Webpack and Rollup support tree shaking when using ES6 module syntax (import
and export
).
Explain the difference between dot notation and bracket notation for accessing object properties
Dot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters.
Explain the difference between unit testing, integration testing, and end-to-end testing
Unit testing focuses on testing individual components or functions in isolation to ensure they work as expected. Integration testing checks how different modules or services work together. End-to-end testing simulates real user scenarios to verify the entire application flow from start to finish.
How do you prevent the default behavior of an event?
To prevent the default behavior of an event in JavaScript, you can use the preventDefault
method on the event object. For example, if you want to prevent a form from submitting, you can do the following:
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault();
});
This method stops the default action associated with the event from being executed, allowing you to implement custom behavior instead.
Explain the Observer pattern and its use cases
The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of any state changes. This pattern is useful for implementing distributed event-handling systems, such as updating the user interface in response to data changes or implementing event-driven architectures.
How do you handle errors using `try...catch` blocks?
Using try...catch
blocks, you can define a block of code to be tested for errors while executing (try
), and a block of code to handle the error if one occurs (catch
). This allows for graceful error handling without breaking the application flow.
function riskyOperation() {
const invalidJsonString = '{"name": "John}'; // Try changing this to a valid JSON string
return JSON.parse(invalidJsonString);
}
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('This will run regardless of an error');
}
How do you import and export modules in JavaScript?
// Exporting a module
export const myFunction = () => {
/* ... */
};
export default myFunction;
// Importing a module
import { myFunction } from './myModule';
import myFunction from './myModule';
How do you make an HTTP request using the Fetch API?
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));
async function fetchData() {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/todos/1',
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
What are Promises and how do they work?
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: pending
, fulfilled
, and rejected
. You can handle the results of a promise using the .then()
method for success and the .catch()
method for errors.
Creating a Promise
You create a promise using the Promise
constructor, which takes a function with two arguments: resolve
and reject
. These are callbacks that you call to change the state of the promise.
let promise = new Promise((resolve, reject) => {
// asynchronous operation
const success = true;
if (success) {
resolve('Success!');
} else {
reject('Error!');
}
});
Handling a Promise
To handle the result of a promise, you use the .then()
method for a successful outcome and the .catch()
method for an error.
let promise = new Promise((resolve, reject) => {
// asynchronous operation
const success = false;
if (success) {
resolve('Success!');
} else {
reject('Error!');
}
});
promise
.then((result) => {
console.log(result); // 'Success!'
})
.catch((error) => {
console.error(error); // 'Error!' (this will print)
});
Chaining Promises
Promises can be chained to handle multiple asynchronous operations in sequence. Each .then()
returns a new promise, allowing for further chaining.
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved after 1 second');
}, 1000);
})
.then((result) => {
console.log(result);
return 'Another promise';
})
.then((anotherResult) => {
console.log(anotherResult);
})
.catch((error) => {
console.error(error);
});
Combining Promises
You can use Promise.all()
to run multiple promises in parallel and wait for all of them to complete.
let promise1 = Promise.resolve('First');
let promise2 = Promise.resolve('Second');
let promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Third');
}, 2000);
});
Promise.all([promise1, promise2, promise3]).then((results) => {
console.log(results); // ['First', 'Second', 'Third']
});
What are Set
s and Map
s and how are they used?
Set
s and Map
s are built-in JavaScript objects that help manage collections of data. A Set
is a collection of unique values, while a Map
is a collection of key-value pairs where keys can be of any type. Set
s are useful for storing unique items, and Map
s are useful for associating values with keys.
// Set example
let mySet = new Set([1, 2, 3, 3]); // Set {1, 2, 3} (duplicate values are not added)
mySet.add(4);
console.log(mySet); // Set {1, 2, 3, 4}
// Map example
let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap.get('key1')); // 'value1'
What is currying and how does it work?
Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function f(a, b, c)
can be curried into f(a)(b)(c)
. Here's a simple example in JavaScript:
function add(a) {
return function(b) {
return a + b;
};
}
const addFive = add(5);
console.log(addFive(3)); // Outputs: 8
What is recursion and how is it used in JavaScript?
Recusrion is a programming technique where a function calls itself to solve a problem. In JS, recusrions is used to solve problems that can be broken down into smaller, similar sub-problems. A base case is essential to stop the recursive calls and prevent infinite loops. For example, calculating the factorial number can be done using recurison:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(4)); // Output: 24
What is the difference between a parameter and an argument?
A parameter is a variable in the declaration of a function, while an argument is the actual value passed to the function when it’s called
What is the DOM and how is it structured?
Document Object Model - a programming interface for web documents. Represents the page so that programs can change the document structure, style and content. The DOm is structured as a tree of objects, where each node represents part of the document, such as elements, attributes, and text.
Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
The CSS box model describes te rectangular boxes that are generated for elements in the document ree and laid out accoing to the visual formatting model. each box has a content area (e.g. text, an image, etc.) and optional surrounding padding
, border
, and margin
areas.
The CSS box model is responsible for calculating:
How much space a block element takes up.
Whether or not borders and/or margins overlap, or collapse.
A box's dimensions.
What does * { box-sizing: border-box; }
do and what are its advantages?
Makes every element on the page use the border-box model for calculating width and height, which includes padding and border in the element's total width and height.
By default, elements have box-sizing: content-box
applied and only the content size is being accounted for if an element has height and widht specified. This means that the width and height defined by the user will include the padding and border, making layout design easier and preventing elements from unexpectedly overflowing their containers.
What is the CSS display
property and can you give a few examples of its use?
The CSS display property specifies how an element is displayed on the web page. It can take values like block, inline, inline-block, and none, affecting layout and visibility.
What is React? Describe the benefits of React?
React is JavaScript library created by Facebook for building UI, primarily for single-page web applications. It allows devs to create reusable components that manage their own state. Key benefits of React include a component-based architecture for modular code, the virutal DOM for efficient updates, a declarative UI for more readble code, one-way data binding for predicatable data flow, and a strong community and ecosystem with abundant resources and tools.
Key characteristics of React:
Declarative: You describe the desired state of your UI based on data, and React handles updating the actual DOM efficiently.
Component-based: Build reusable and modular UI elements (components) that manage their own state and logic.
Virtual DOM: React uses a lightweight in-memory representation of the actual DOM, allowing it to perform updates selectively and efficiently.
JSX: While not mandatory, JSX provides a syntax extension that allows you to write HTML-like structures within your JavaScript code, making UI development more intuitive.
What are the differences between JavaScript variables created using let
, var
or const
?
In JavaScript, let
, var
, and const
are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:
Behavior |
|
|
|
---|---|---|---|
Scope | Function or Global | Block | Block |
Initialization | Optional | Optional | Required |
Redeclaration | Yes | No | No |
Reassignment | Yes | Yes | No |
Accessing before declaration |
|
|
|
What is JSX and how does it work?
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript files. It compiles to React elements, enabling developers to create user interfaces in a more intuitive and readable manner.
JSX stands for JavaScript XML
What is the purpose of the key prop in React?
The key prop in React is used to uniquely identify elements in a list. It helps React optimize rendering by efficiently updated and reordering elements. Without a unique key, React may re-render elements unnecessarily, leading to performance issues and bugs.
What are the consequences of using array indices as the value for keys
in React?
Using array indices as the value for key
s in React can lead to performance issues and bugs. When the order of items changes, React may not correctly identify which items have changed, leading to unnecessary re-renders or incorrect component updates. It's better to use unique identifiers for key
s to ensure React can efficiently manage and update the DOM.
Can you give an example of an @media
property other than screen
?
There are four types of @media
properties (including screen
):
all
: for all media type devices
print
: for printers
speech
: for screen readers that "reads" the page out loud
screen
: for computer screens, tablets, smart-phones etc.
What are some of the “gotchas” for writing efficient CSS?
First, understand that browsers match selectros from rightmost (key selector) to left. Browsers filter out elements in the DOM according to the key selector and travers up its parent elements to determine matches. The shorter length the length of the selector chain, the faster the browser can determine if that element matches the selector. Hence avoid key selectors that are tag and universal selectors. They match a large number of elements and browserswill have to do more work in determining if the parents do match.
BEM (Block Element Modifier) methodology recommends that everything has a single class and where you need hierarchy, that get baked into the name of the class as well, this naturally makes the selector efficient and easy to override.
What advantage is there for using the JS arrow syntax for a method in a contructor?
The main advantage of using an arrow function as a method inside a constructor is that the value of this
gets set at the time of the function creation and can’t change after that. When the constructor is used to create a new object, this
will always refer to that object.
What is the difference between useEffect
and useLayoutEffect
in React?
They are both React hooks used to handle side effects in functional components, but they differ in timing and use cases:
useEffect
: Runs async after the DOM has been painted. Is suitable for tasks like data fetching, subscriptions, or logging.
Common use cases
Fetching data from an API
Setting up subscriptions (e.g., WebSocket connections)
Logging or analytics tracking
Adding and removing event listeners
useLayoutEffect
: Runs synchronously after DOM mutations but before browser paints. Use it for tasks like mesasuring DOM elements or synchronizing the UI with the DOM
Common use cases
Measuring DOM elements (e.g., for animations or layouts)
Adjusting DOM properties or styles based on calculations
Fixing UI synchronization issues
What is the useRef
hook and when should it be used?
The useRef hook in React is used to create a mutable object that persists across renders. It can be used to access and manipulate DOM elements directly, store mutable values that do not cause re-renders when updated, and keep a reference to a value without triggering a re-render. For example, you can use useRef to focus an input element.
import React, { useRef, useEffect } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
useEffect(() => {
inputEl.current.focus();
}, []);
return <input ref={inputEl} type="text" />;
}
What is the useCallback
hook in React and when should it be used?
The useCallback hook in React is used to memorize a callback function, preventing them from being recreated on every render. This is particularly useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders. You should use useCallback
when you have a function that is passed as a prop to a child component and you want to avoid the child component re-rendering unnecessarily due to a change in the function reference.
What is the useReducer
hook in React and when should it be used?
The useReducer
hook in React is used for managing complex state logic in functional components. It is an alternative to useState
and is particularly useful when the state has multiple sub-values or when the next state depends on the previous one. It takes a reducer function and an initial state as args and returns the current state and a dispatch function.
const [state, dispatch] = useReducer(reducer, initialState);
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
When to use useReducer
Complex state logic: Use useReducer
when you have complex state logic that involves multiple sub-values or when the next state depends on the previous state.
State management: It is useful when you need a more predictable state management pattern, similar to Redux.
Performance optimization: useReducer
can help optimize performance in certain scenarios by avoiding unnecessary re-renders.
What are React fragments for?
Fragments are used to group multiple elements without adding extra nodes to the DOM. This is useful when you want to return multiple elements from a component’s render method without wrapping them in an additional HTML element. You can use the shorthadn syntax<></> to create a fragment without specifying a key.
Describe event bubbling in JavaScript and browsers
Event bubbling is a DOM propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event. Event bubbling is essential for event delegation, where a single event handles manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.
What are some pitfalls about using context in React?
Using context in React can lead to performance issues if not managed properly. It can cause unnecessary re-renders of components that consume the context, even if the part of the context they use hasn't changed. Additionally, overusing context for state management can make the code harder to understand and maintain. It's important to use context sparingly and consider other state management solutions like Redux or Zustand for more complex state needs.
What are the benefits of using hooks in React?
Hooks in React allow you to use state and other React features without writing a class. They make it easier to reuse stateful logic between components, improve code readability, and simplify the codebase by reducing the need for lifecycle methods. Hooks like useState
and useEffect
are commonly used to manage state and side effects in functional components.