Job interview Flashcards

prepare for js interview

1
Q

Create a ‘Like’ button with the following UI design and states - https://i.imgur.com/4JLyipM.png

Requirements

x - The button should show the text ‘Like’ and an icon to the left of the text.
x- The button should have gray text, icon and border.
x- When the user hovers over the button, the text, icon and border should turn red.
x- When the user clicks the button its state should toggle, the text and icon should turn white and the background colour should become red.
x- When the button is mounted it should call an API endpoint get the initial state (enabled or disabled).
- Clicking the button should call an API endpoint to update the new state (enabled or disabled).
- While the request is processing, the button should show a loading state.

*/—

A
import React, { useState, useEffect } from 'react';
import styles from './Button.module.css'; // Import CSS using CSS Modules

const ButtonComponent = () => {
  const [isActive, setIsActive] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const fetchData = async (url, method, body = null) => {
    setIsLoading(true);
    try {
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: body ? JSON.stringify(body) : null,
      });
      if (!response.ok) {
        throw new Error(`Failed to ${method} data`);
      }
      const data = await response.json();
      return method === 'GET' ? data.isActive : null; // Assuming 'isActive' property
    } catch (error) {
      console.error(`Error ${method}ing data:`, error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData('your-api-endpoint', 'GET')
      .then(data => setIsActive(data)) // Set initial state
      .catch(error => console.error(error));
  }, []);

  const toggleActive = async () => {
    const updatedActive = !isActive;
    await fetchData('your-api-endpoint', 'POST', { isActive: updatedActive });
    setIsActive(updatedActive);
  };

  return (
    <button
      className={`${styles.button} ${isActive ? styles.active : styles.inactive}`}
      disabled={isLoading}
      onClick={toggleActive}
    >
      {/* ... rest of the component JSX ... */}
    </button>
  );
};

export default ButtonComponent;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are keys in react?

A

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.

Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Disadvantages of real DOM :

A

Every time the DOM gets updated, the updated element and its children have to be rendered again to update the UI of our page. For this, each time there is a component update, the DOM needs to be updated and the UI components have to be re-rendered.
Example:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

React JS Refs

A

Refs are a function provided by React to access the DOM element and the React elements created in components. They are used in cases where we want to change the value of a child component, without making use of props and state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does virtual DOM actually make things faster?

A

When anything new is added to the application, a virtual DOM is created and it is represented as a tree. Each element in the application is a node in this tree. So, whenever there is a change in the state of any element, a new Virtual DOM tree is created. This new Virtual DOM tree is then compared with the previous Virtual DOM tree and make a note of the changes. After this, it finds the best possible ways to make these changes to the real DOM. Now only the updated elements will get rendered on the page again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Controled components

A

Controlled Components
In simple HTML elements like input tags, the value of the input field is changed whenever the user type. But, In React, whatever the value the user types we save it in state and pass the same value to the input tag as its value, so here DOM does not change its value, it is controlled by react state. These are known as Controlled Components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are react hooks?

A

Hooks are reusable functions that provide access to state in React Applications. Hooks give access to states for functional components while creating a React application. It allows you to use state and other React features without writing a class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Use Context ?

A

Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props.

global data -> current authenticated user or theme(e.g. color, paddings, margins, font-sizes).

The Context API allows for more flexibility in how state is managed and accessed compared to Redux, which follows a more structured pattern with actions, reducers, and a single store.

Context lets a component provide some information to the entire tree below it.
To pass context:
Create and export it with export const MyContext = createContext(defaultValue).
Pass it to the useContext(MyContext) Hook to read it in any child component, no matter how deep.
Wrap children into <MyContext.Provider value={…}> to provide it from a parent.
Context passes through any components in the middle.
Context lets you write components that “adapt to their surroundings”.
Before you use context, try passing props or passing JSX as children.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

useState Hook

A

The useState Hook provides those two things:

A state variable to retain the data between renders.
A state setter function to update the variable and trigger React to render the component again.

When you call useState, you are telling React that you want this component to remember something:

const [index, setIndex] = useState(0);
In this case, you want React to remember index.

The convention is to name this pair like const [something, setSomething].

The only argument to useState is the initial value of your state variable

Every time your component renders, useState gives you an array containing two values:

The state variable (index) with the value you stored.
The state setter function (setIndex) which can update the state variable and trigger React to render the component again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is useEffect hook in React?

A

Some components need to stay connected to the network, some browser API, or a third-party library, while they are displayed on the page. These systems aren’t controlled by React, so they are called external.

To connect your component to some external system, call useEffect at the top level of your component:

The useEffect in ReactJS is used to handle the side effects such as fetching data and updating DOM. This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering

So run on update of var in the dependancy [test]

Once when dependacy is []

and on every render wheren there is no dependacy array so if you set state in useEffect and dont have dependancy array you have an infinite loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does it useEffect work?

A

You call useEffect with a callback function that contains the side effect logic.
By default, this function runs after every render of the component.
You can optionally provide a dependency array as the second argument.
The effect will only run again if any of the values in the dependency array change.

Controlling side effects in useEffect :
1. To run useEffect on every render do not pass any dependency

useEffect(()->{
// Example Code
})

  1. To run useEffect only once on the first render pass any empty array in the dependecy

useEffect(()->{
// Example Code
}, [] )

  1. To run useEffect on change of a particular value. Pass the state and props in the dependency array
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Syntax Parser, Execution Context, and Lexical Environment

A

Syntax parser - a program that reads your code and determines what it does and if its grammar/syntax is valid.

When you write JavaScript it isn’t directly telling computer what to do. You’re writing code, but then someone else built programs that convert your JS into something that computer can understand. Those programs are called compilers or interpreters.

Compilers go character by character and translate your code into a set of instructions. Important to understand is that during that process programmers who wrote that compiler can choose to do extra stuff. Your code is not what actually is given to a computer but a translation of it.

Lexical environment - where something sits physically in the code you write and what surrounds it. In JavaScript where you write something is important.

Execution context - a wrapper to help manage the code that is running. There are lots of lexical environments, areas of the code that you look at physically, but which one is currently running is managed via execution contexts. Execution context contains your running code, but it can also contain things beyond what you’ve written in your code. Because remember that your code is being translated by a syntax parser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

The Scope Chain

A

If JavaScript engine doesn’t find variable in it’s own environment it looks in the outer environment. That whole process of searching of variable in outer lexical environments down the chain is called the scope chain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Hoisting

A

Hoisting - because of the way JS works, you can write in your code a call to a function before an actual function and it will execute without any errors.

b();

function b() {
console.log(‘This works!’);
}

let avoids Hoisting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Asynchronous Callbacks

A

Asynchronous - executed more than one at a time. What is happening inside JS engine is synchronous. Its just the browser is putting things asynchronously in the event queue.

Event queue - events like click and others are placed in the queue. And this queue starts to get processed in the order it happened only when execution stack is empty.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Conceptual Aside Coercion

A

Coercion - converting a value from one type to another. This happens quite often in JavaScript because it’s dynamically typed. For example adding a number to a string would result in number being converted to a string:

7 + ‘7’// would be = ‘77’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Immediately Invoked Functions Expressions (IIFEs)

A

Using an Immediately Invoked Function Expression (IIFE):

var firstname = ‘John’;

(function(name) {

var greeting = 'Inside IIFE: Hello';
console.log(greeting + ' ' + name);

}(firstname)); // IIFE

Framework Aside IIFEs and Safe Code

IIFE creates a new execution context so it’s safe code because it is wrapped in separate execution context and prevents variable names collision. Wrapping code libraries is very common pattern to not clash code with the global object. You can reference to global object by passing window as a parameter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Understanding Closures

A

When a function runs and completes it is removed from execution stack, but variables created and saved in that execution phase are still stored in memory and can be accessed from down the scope.
~~~
function greet(whattosay) {

return function(name) {
console.log(whattosay + ‘ ‘ + name;
}

}

var sayHi = greet(‘Hi’);
sayHi(‘Jason’);
~~~

Inside the variable sayHi we run greet function which returns another function and passes string ‘Hi’. After that functions is finished and it is popped from the execution stack. But whattosay variable still sits saved in the memory with a value Hi. So when we call function sayHi it will go in the outer environment and look for whattosay variable and will find it and log “Hi Jason”. We describe this proccess as execution context has closed in outer variables.

Closures And Callbacks
Callback function - a function you give to another function to be run when the other function is finished.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Describe the key differences between state and props in React

A

In React, both state and props are used to pass data, but they serve different purposes. State is mutable and managed within a component, while props are immutable and passed down from a parent component.

10
Q

Explain the concept of a closure in JavaScript.

A

A closure is created when a function is defined inside another function, allowing the inner function to access variables from the outer (enclosing) function even after the outer function has finished executing. Closures are a powerful mechanism for data encapsulation and maintaining the state.

11
Q

Explain the concept of components in React.

A

Components are the building blocks of a React application, encapsulating both the UI and behavior of a specific part of the application. They promote reusability and modularity by allowing developers to compose complex interfaces from smaller, self-contained units.

12
Q

How do you ensure accessibility in your frontend applications?

A

To ensure accessibility, I follow the Web Content Accessibility Guidelines (WCAG), use semantic HTML elements, add appropriate ARIA attributes, ensure proper contrast ratios, and test my applications using screen readers and other assistive technologies

13
Q

Can you explain the concept of web components and their benefits?

A

Web components are a set of web platform APIs that enable developers to create custom, reusable HTML elements. They promote modularity, encapsulation, and interoperability, allowing for more maintainable and scalable frontend applications.

14
Q

What is the role of design systems in frontend development?

A

Design systems provide a collection of reusable components, guidelines, and principles that help ensure a consistent user experience and visual language across applications. They promote efficiency, collaboration, and maintainability in frontend development.

15
Q

How do you handle internationalization (i18n) and localization (l10n) in frontend applications

A

I handle internationalization and localization by using libraries like i18next or react-intl to manage translations and formatting. These libraries provide a mechanism for storing and retrieving translated strings, as well as handling date, time, and number formatting based on the user’s locale.

16
Q

Can you explain the concept of event delegation in JavaScript?

A

Event delegation is a technique that involves binding an event listener to a parent element instead of individual child elements. When an event occurs on a child element, it bubbles up to the parent, which then handles the event. This technique can improve performance and memory usage by reducing the number of event listeners and simplifying event management.

17
Q

Can you explain the role of custom elements in frontend development?

A

Custom elements are part of the web components standard that allows developers to define and create reusable, encapsulated HTML elements with custom behavior and styling. They promote modularity and interoperability in frontend applications, making it easier to build and maintain complex UI components.

18
Q

Can you explain the role of the Shadow DOM in frontend development?

A

The Shadow DOM is a part of the Web Components standard that provides encapsulation for DOM elements and their styles, keeping them separate from the main document tree. It enables the creation of reusable and self-contained components that don’t interfere with other parts of the application. The Shadow DOM promotes modularity and maintainability in frontend development by preventing global style and DOM conflicts.

19
Q

What’s the difference between a Callback and a Promise?

A

Calback
A function passed as an argument to another function and executed later -> useEffect

Promise
An object representing a future value of an asynchronous operation
Single .catch() to handle errors in the chain
Has pending, fulfilled, and rejected states

20
Q

What do you think will become the next big trend in web development?

A
21
Q

What are the React lifecycle methods?

A

function MyComponent() {
useEffect(() => {
// componentDidMount logic here
// componentDidUpdate logic here for dependency changes

return () => {
  // componentWillUnmount logic here
};   }, []);  // Dependency array makes this behave like componentDidMount and componentWillUnmount }
22
Q

Mutatate inmutabale data why whaty

A

In React, immutability means creating new copies of state rather than modifying the original data. This is crucial because React relies on reference changes to detect updates and re-render components. If data is mutated directly, React may miss changes, leading to unexpected behavior.

For example:

To add an item to an array: setItems([…items, newItem]) instead of items.push(newItem).
To update an object: setUser({ …user, age: 26 }) instead of user.age = 26.
Immutability makes state changes predictable and helps React perform efficiently.

23
Q

Example of useCallback real word example in react?

A
24
Q

What is useCallback and what is useMemo diference and example

A
25
Q

What is jsx?

A
26
Q

Promise, async await. asyncronios request history explanation?

what’s the diference between them what are they ?

A
27
Q

How does react work ? How is it built how do you render it in the browser how works under the hood?

A
28
Q

Most common patterns in front end development ?

A
29
Q

How next js works ? what’s the difrenece between it and react?

A
30
Q

Best Practices for Testing in React?

A

Write unit tests for simple, isolated logic (e.g., functions or standalone components). - Jest: A JavaScript testing framework ,
React Testing Library: This library is built on top of Jest and provides utilities to render components and query

Use integration tests for components that interact with each other or that depend on context or state. - Cypress: This end-to-end testing tool

Avoid testing implementation details (like class names or internal states) and focus on user interactions and output.

31
Q

jQuery and JavaScript/ES6
diferences what is each how are they related to each other why jQuery went away?

A
  1. What is JavaScript/ES6?
    JavaScript is a core, versatile programming language native to the web. It allows developers to add interactivity, animations, and control over webpage content and behavior.

ES6 (ECMAScript 2015) is a major update to JavaScript that introduced new features, syntax improvements, and functionality to make the language more powerful and concise.

Examples include arrow functions, classes, template literals, let and const, Promise objects, and async functions.

  1. What is jQuery?
    jQuery is a JavaScript library released in 2006 that simplifies HTML document traversal, manipulation, event handling, and animation. It was created to address cross-browser compatibility issues and to make JavaScript more accessible for common tasks with a simplified, unified syntax.
32
Q

Arrow functions vs normal functions

A

this Binding: Arrow functions don’t have their own this context; instead, they inherit this from the surrounding (lexical) scope.

preserve the this context from the outer scope.

This is useful in cases like callbacks within a method where you want to maintain the class’s this.

Implicit Return: If an arrow function has only one expression, it can implicitly return the value of that expression without needing the return keyword.

// Regular function in a method
function Person() {
this.name = “Alice”;
setTimeout(function() {
console.log(this.name); // undefined, because this refers to the global context
}, 1000);
}

// Using an arrow function
function Person() {
this.name = “Alice”;
setTimeout(() => {
console.log(this.name); // Alice, because this refers to the Person instance
}, 1000);
}

33
Q

Classes in javascript

A

Classes are a syntactical sugar over JavaScript’s existing prototype-based inheritance. They make it easier to create and understand object-oriented code.

Key Features:

Constructor: The constructor method is used to initialize an object created with the class.
Inheritance: Classes support inheritance with the extends keyword, allowing one class to inherit properties and methods from another.
Static Methods: Classes can have static methods that are called on the class itself, not on instances.

// ES5 Constructor function
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(${this.name} makes a noise.);
};

// ES6 Class
class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(${this.name} makes a noise.);
}
}

const dog = new Animal(“Dog”);
dog.speak(); // Dog makes a noise.

34
Q

ES6 - Template Literals

A

Template literals are a way to embed variables and expressions directly within strings using backticks (`) and ${} syntax. They make string concatenation and multi-line strings more readable and manageable.

35
Q

Typescript

A

Enums define named constants, making code more readable and easier to work with than using plain constants.

enum Direction {
Up,
Down,
Left,
Right,
}
let move: Direction = Direction.Up;

Intersection Type Example:

interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type Staff = Person & Employee;
const staff: Staff = { name: “Alice”, employeeId: 101 };

Union Type Example:
function format(input: string | number) {
return input.toString();
}

Interfaces and type aliases allow you to define custom types and create complex type structures, making code more readable and manageable.

interface User {
name: string;
age: number;
isAdmin: boolean;
}
const user: User = { name: “Alice”, age: 30, isAdmin: false };

Utility Types
const user: Partial<User> = {}; // All properties are optional now</User>