WEB Flashcards

1
Q

What is a callback function?

A

A callback function is a sent function to an another function as an argument to be used.

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

What is ECMA script ? What is the difference between Javascript & ECMA script ?

A

ECMA Script is a language specification that defines how a script language should work, while Java Script is an popular implementation of it.
JavaScript is a programming language initially created by Netscape, whistl ECMAScript consists of specifications (syntax, semantics, structure) for a scripting language created by European Computer Manufacturers Association (ECMA). JavaScript is one implementation based on ECMAScript standards.

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

What is the difference between let & var ?

A

Declaring a variable with let , it will be accesible only within the block it was declared, while declaring with var, the variable can be accesed globally.

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

Write an example where using the var declaration instead of the let could create a hard to debug code.

A
function example() {
  for (var i = 0; i < 5; i++) {
    setTimeout(function () {
      console.log(i);
    }, 1000);
    s;
  }
 }

In this example the value of i will be changed before the console will be executed so it will show five times 5.

function printNumbers(){
var num = 10;

if (true){
var num = 20;
}

console.log(num)
}

printNumbers() // Output: 20
function printNumbers(){
let num = 10;

if (true){
let num = 20
}

console.log(num);
}

printNumbers() // Output: 10
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give a practical example where you would use the reduce function in javascript.

A
let cart = [
  { name: "bananas", price_per_unit: 7.99, quantity: 1.4 },
  { name: "bread", price_per_unit: 4.5, quantity: 2 },
  { name: "eggs", price_per_unit: 1, quantity: 20 },
 ];
 let total = cart.reduce((acc, curr) => acc + curr.price_per_unit * curr.quantity, 0);

The total variable will be the total of a receipt.

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

Give a practical example where you would use the map function in javascript.

A
let cart = [
  { name: "bananas", price_per_unit: 6.99, quantity: 1.4 },
  { name: "bread", price_per_unit: 3.5, quantity: 2 },
  { name: "eggs", price_per_unit: 0.8, quantity: 20 },
 ];

 cart.map((product) => 
  product.price_per_unit *= 1.2;);
 console.log(cart[0]);// {name: 'bananas', price_per_unit: 8.388, quantity: 1.4}

In this example all the prices will be increased by 20%.

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

Give a practical example where you would use the filter function in javascript.

A
let cart = [
    { name: "bananas", price_per_unit: 6.99, quantity: 1.4 },
    { name: "bread", price_per_unit: 3.5, quantity: 2 },
    { name: "eggs", price_per_unit: 0.8, quantity: 20 },
  ];

  let newcart = cart.filter((product) => product.price_per_unit < 5);

  console.log(newcart.length); // The result will be 2 because bananas price_per_unit is 6.99 > 5

In this example filter creates a new array that contains only the products that has the price_per_unit under 5.

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

What is a web server?

A

A web server is a software that responds to requests from clients or web browsers, and serves web pages to them over the Internet or a local network.

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

Explain the client-server architecture.

A

Client-server architecture is a computing model where software applications or systems are divided into two main parts: the client and the server. They iteract with each other using a communication protocol such as HTTP. When a client requests data from a server, the server sends back the requested data. The client can then use this data to provide the user with the required functionality. Same with others methods like :PUT,POST,DELETE etc

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

What is the difference between synchronous and asynchronous execution?

A

Synchronous and asynchronous execution refer to two different ways in which a computer program can execute instructions.

  • Synchronous execution means that the program executes instructions one at a time, in order, and each instruction must complete before the next one can start.
  • Asynchronous execution means that the program does not wait for an instruction to finish before moving on to the next one. Instead, the program executes instructions in a non-blocking manner, allowing multiple instructions to be executed simultaneously
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is npm? Why is it useful?

A

npm means Node Package Manager, and it is the default package manager for Node.js. It is used to install, update, and manage dependencies for Node.js projects. It also alows developers to publish their own packages, it ensures that all the packages are up to date and is easy to use with simple commands in the terminal

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

What is the difference between the dependencies & devDependencies in a package.json file ?

A

The main difference between dependencies and devDependencies is that dependencies are required for the project to function correctly, while devDependencies are only needed during development and testing.

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

What would be the impact of javascript fetch if it was not asyncronous ?

A

If fetch was not asynchronous it would blocked the execution of other code, the page would freeze until each request was completed, making the user experience slow and unresponsive.

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

What benefits would bring to a developer to use the Postman application ?

A
  • Testing APIs: Postman provide a user-friendly interface for making requests, inspecting responses, and debugging issues.
  • Collaboration: Postman allows teams to collaborate on API development by sharing collections, requests, and environments and it provides a workspace where developers can work together on a single API project
  • Automating tests: Postman allows developers to create automated tests for APIs and web services using its testing framework
  • Mock servers: Postman provides a mock server feature that allows developers to simulate an API endpoint and test the API without actually sending requests to the real server.
  • Monitoring APIs: Postman offers an API monitoring feature that allows developers to monitor APIs and web services for performance, uptime, and errors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

List the parts of the URL.

A
  • Protocol: http://, https://, ftp:// etc
  • Domain/Host (a domain name or IP address)
  • Port (ex:3000)
  • Path: /example/of/path
  • Query string: ?key1=value1&key2=value2
  • Fragment identifier(ID): #section1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does an HTTP Request look like? What are the most relevant HTTP header fields?

A
fetch(url,
  {method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token'
  },
  body: JSON.stringify(obj)})
 .then(response = response.json())
 .then(data = console.log(data))
 .catch(error = console.error(error));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is query parameter?

A

A query parameter is a part of a URL that contains data to be sent to a web server as a part of a request. Query parameters are appended to the end of a URL after a question mark (?), and multiple parameters can be separated by an ampersand (&).

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

List the parts of the URL.

A
  • Protocol: http://, https://, ftp:// etc
  • Domain/Host (a domain name or IP address)
  • Port (ex:3000)
  • Path: /example/of/path
  • Query string: ?key1=value1&key2=value2
  • Fragment identifier(ID): #section1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What kind of HTTP status codes do you know?

A
  • 200 - The request has succeeded and returned the requested data.
  • 400 Bad Request - The server was unable to understand the request due to invalid syntax.
  • 404 Not Found - The requested resource was not found on the server.
  • 405 Method Not Allowed - The requested method is not allowed for the specified resource.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why should you ignore the node_modules folder in .gitignore ?

A

Because this folder contains a large number of files and directories wich can have a big dimension. And they can be easily be instaled with npm install. Also there could be dublicates, changes and conflicts hard to be managed because of the quantity of the files.

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

Why is it recommend for a developer to use the http methods get, put, delete ?

A
  • These HTTP methods have well-defined and known meanings. For example, GET is used for retrieving resources, PUT is used for updating existing resources, and DELETE is used for deleting resources.
  • GET requests can be cached by web browsers and sending the same request multiple times ,like PUT or DELETE has the same effect as sending it once
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How does a POST request look like when it is made from a web browser (on the front end written) ?

A
fetch(url,
  {method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token'
  },
  body: JSON.stringify(obj)})
 .then(response = response.json())
 .then(data = console.log(data))
 .catch(error = console.error(error));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is an API?

A

An API is like a messenger that takes requests from one system and sends them to another system, and then delivers the response back to the requesting system.

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

What is REST API?

A

REST API is an API that follows the principles of the REST architectural style. REST is a set of constraints and principles for designing web-based software architectures. They allow developers to build systems that can be accessed from a variety of devices and platforms.

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

What is JSON and how do we use it?

A

JSON stands for JavaScript Object Notation. It is a data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
In JavaScript we can use the JSON.parse() method to parse a JSON string into a JavaScript object, and the JSON.stringify() method to convert a JavaScript object into a JSON string.

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

What is API versioning ?

A

API versioning is the practice of creating multiple versions of an API to manage changes to the API over time. Some changes can have an impact on clients that depend on the API so versioning provides a way to manage these changes while minimizing disruption to clients.

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

Give 3 examples of HTTP response status codes ? Explain what each number means.

A
  • 200 OK : It indicates that the request was successful
  • 404 Not Found: This indicates that the server could not find the requested resource because the URL is incorrect, the resource has been deleted or moved, or the user does not have permission to access the resource.
  • 400 Bad Request: It indicates that the server cannot process the client’s request because the request has invalid syntax or is malformed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How does the ternary operator looks like in javascript?

A
codintion ? expresion1 : expresion2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How to import a function from another module in JavaScript?

A
import <functionName> from "<path/to/module's/file>"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a shallow copy on an object?

A

IS a new object that is a copy of the original object but shares the same references to the objects contained within it.

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

What is a callback function? Tell some examples of its usage.

A

A callback function is a sent function to an another function as an argument to be used.

  • For asynchronus fetch functions:
 fetch('/example/data')
 .then(response = response.json())
 .then(data = {
 console.log(data)
 });
  • Adding events:
 button.addEventListener('click', function() {
 alert("Event trigered)
 });
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is object destructuring in javascript?

A

Object destructuring is a method that allows us to extract values from objects and assign them to variables.

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

What is array destructuring in javascript?

A

Array destructuring is a method that allows us to extract values from arrays and assign them to variables.

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

What is the spread operator in js ?

A

Spread operator allows us to spread the contents of an iterable (such as an array or an object) into individual elements with (...) notation

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

What are the differences between the arrow function and the regular function?

A
  • Arrow functions have a shorter and more concise syntax compared to regular functions
  • A regular function has its own this binding when it is set to an object while an arrow function doesn’t have its own this binding
33
Q

What is the import keyword used for?

A

The import keyword is used to import functionality from other modules or files. When you use the import keyword, you can load a module that defines a set of functions, classes, or variables, and then use them in your current module.

34
Q

What is the required used for?

A

require is a keyword used to load modules in Node.js. When you use require, you can load a module that defines a set of functions, classes, or variables, and then use them in your current file

35
Q

What are template literals?

A

Template literals are a way to create strings in JavaScript that allows for embedding expressions or variables inside a string, making it easier to create dynamic strings. They are enclosed within backticks `……${}`

36
Q

What is code coverage? Why is it used?

A

Code coverage is an important metric for measuring the quality of software testing, as it can help identify areas of the code that have not been thoroughly tested, and can provide insights into the effectiveness of the testing process. By identifying untested or poorly tested code, code coverage can help developers prioritize testing efforts and ensure that critical parts of the code are adequately tested.

37
Q

What is a test case? What is an assertion? Give examples!

A
  • A test case is a specific set of conditions or inputs used to test the functionality of a software application. Test cases are typically designed to verify that the software behaves correctly under a range of different conditions
  • An assertion is a statement that checks whether a certain condition is true or false, and is used to validate the behavior of a software application during testing. Assertions are typically included in test cases to ensure that the software behaves correctly under different conditions. Examples of test cases and assertions: 1. Login Page:
    • Test case: Enter valid username and password, and click on the login button.
    • Assertion: Verify that the user is redirected to the home page. 2. Shopping Cart:
    • Test case: Add an item to the shopping cart, and verify that the item is displayed correctly.
    • Assertion: Verify that the item count in the shopping cart is increased by one. 3. Search Functionality:
    • Test case: Enter a search term in the search box, and click on the search button.
    • Assertion: Verify that the search results page is displayed with relevant search results.
38
Q

What are the unit testing best practices? (Eg. how many assertion should a test case contain?)

A
  • Test One Thing at a Time: Each unit test should focus on testing a single piece of functionality, or a single method or function.
  • Use Descriptive Test Names: Test names should be descriptive and indicate what the test is testing. This makes it easier to understand what the test is doing.
  • Write Clear and Concise Tests: Tests should be clear and concise, and should be written in a way that is easy to understand. This can help to ensure that tests are maintainable and can be easily modified or updated as the code changes.
  • Use Mocks and Stubs: Mocks and stubs can be used to simulate external dependencies or interactions with other parts of the system. This can help to ensure that tests are isolated and focused on testing the specific functionality being tested.
  • Test Both Positive and Negative Scenarios: Unit tests should test both positive and negative scenarios, to ensure that the software behaves correctly in a variety of different situations.
  • Use Assertions Effectively: Each test case should contain one or more assertions to verify that the expected behavior of the software is being met.
  • Automate Tests: Automated tests should be used whenever possible to ensure that tests can be easily run and updated as the code changes. The number of assertions in a test case should be based on the specific functionality being tested, with a focus on keeping tests focused, simple, and easy to maintain. But usually
39
Q

What is arrange/act/assert pattern?

A

The Arrange/Act/Assert pattern is a common testing pattern used in software development.It is a way to structure automated tests to ensure that they are clear, organized, and repeatable.

40
Q

How do you test asynchronous code with jest ?

A
  • Callbacks:You can pass a callback function to your asynchronous code and call it when the code completes. In your test, you can use Jest’s done() function to tell Jest when the test is complete.
  • Promises: If your asynchronous code returns a Promise, you can use Jest’s expect() function with .resolves or .rejects to test the result of the Promise. You can also use async/await syntax in your test to make the code more readable.
  • async/await: If your test function is marked as async, you can use await to wait for your asynchronous code to complete. You can then use Jest’s expect() function to test the result.
41
Q

What is setup & teardown in jest ?

A

In Jest, setup and teardown are functions that are executed before and after each test suite or individual test. These functions can be used to set up the environment and prepare the system for testing (in the setup function), and then clean up after the tests are complete (in the teardown function).

42
Q

Give an example when you would use in jest the toBe & toEqual assertions.

A
function add(a, b) {
  return a + b;
 };
 test('adds 1 + 2 to equal 3', () = {
  expect(add(1, 2)).toBe(3);
 });
 test('returns an object with properties a and b',()= {
  expect(myFunction()).toEqual({a: 1, b: 2});
 })
43
Q

What benefits does it bring for a developer to use components (opposed of writing all the code in a single file) ?

A
  • Code organization and maintainability
  • Reusability
  • Collaboration
  • Testing
  • Performance
44
Q

What is the difference between Element and Component?

A

An element refers to an HTML tag, such as <div>, <p>, <span>, or any other tag that can be used in an HTML document. A component, on the other hand, is a reusable piece of code that encapsulates a set of related UI elements and their associated behavior. A component can include multiple HTML elements, CSS styles, and JavaScript logic that work together to provide a specific piece of functionality.

45
Q

How do you pass values between components in react?

A
  • Props: The simplest and most common way to pass data between components in React is by using props. You can pass data from a parent component to a child component by passing it as a prop when rendering the child component.
  • Context: Context provides a way to share data between components without having to pass props down through every level of the component tree. Context is useful for data that needs to be accessed by many components at different nesting levels.
  • State: State is used to manage component-specific data that may change over time. If a component needs to share its state with another component, you can pass the state data and a callback function as props to the child component.
46
Q

What is key prop?(For React components)

A

In React, the key prop is a special attribute that is used to identify components in a list. When rendering a list of components, React needs a way to identify each item in the list so that it can efficiently update the DOM when the list changes.

The key prop should be set to a unique value for each component in the list. React uses the key to keep track of which components have changed, been added, or been removed from the list.

47
Q

How does a child component pass data to it’s parent component ?

A

In React, you can pass data from a child component to its parent component by using callbacks.

48
Q

Write the code to create in JSX an HTML DIV element that has the innerText the contents of the variable let name = 'Andrew'

A
function MyComponent() {
 let name = 'Andrew'
 return (<div>{name}</div>)
 }
49
Q

Write the code to create in JSX an unordered list from the array let names = ["Mathew", "John", "Maverik"]

A
function MyComponent() {
 let names = ["Mathew", "John", "Maverik"]
 return (
 {names.map((name,i)=
 <div key={i}>{name}</div>)}
 )}
50
Q

Write the code to set the background color red of a div in JSX.

A
<div style={{backgroundColor:"red"}}></div>
51
Q

What are unit tests, integration tests? What is the major difference between these two?

A

Unit tests are tests that focus on testing individual components or units of code in isolation and they are usually automated using testing frameworks.

Integration tests, on the other hand, are tests that focus on testing the interactions and interfaces between different components or modules of the application.

The major difference between unit tests and integration tests is their scope. Unit tests are focused on testing small, isolated units of code, while integration tests are focused on testing the interactions and interfaces between different components or modules of the application.

52
Q

What is unit testing?

A

Unit testing is a type of software testing that is focused on verifying the behavior of individual units or components of a software application in isolation from the rest of the system. A unit can be a function, a method, a class, a module, or any other small, self-contained part of the application. The main goal of unit testing is to ensure that each unit of the application behaves correctly and meets its specification.

53
Q

What does mocking mean from a testing perspective ? Give an example when you would use it.

A

Mocking is a technique used in software testing to create artificial dependencies that simulate the behavior of real dependencies. In other words, mocking allows testers to replace real dependencies with fake ones that mimic their behavior and output, without actually calling the real dependencies.

54
Q

How do you test that function was called at least 2 times using jest ?

A

In Jest, you can use the jest.fn() method to create a mock function, which allows you to track how many times the function was called and with what arguments. To test that a function was called at least 2 times, you can use the toBeGreaterThanOrEqual() matcher to compare the number of times the function was called with the expected minimum value.

55
Q

Name 4 benefits a developer gets from writing tests.

A

1. Reduced Bugs and Errors: Writing tests can help catch bugs and errors early in the development process, before they become bigger problems.

2. Improved Code Design: Writing tests requires a developer to think more carefully about how their code is structured and how it interacts with other parts of the system. This can lead to better code design, with more modular, maintainable, and extensible code that is easier to understand and work with.

3. Faster Development and Deployment: Writing tests can help speed up the development process by catching bugs and errors early and reducing the amount of time spent on manual testing and debugging.

4. Greater Confidence and Peace of Mind: Writing tests can give a developer greater confidence in their code and peace of mind that it works as intended

56
Q

What is the difference between Real DOM and Virtual DOM?

A

They are both representations of a web page’s structure, but they differ in how they are constructed, updated, and managed.

  • The Real DOM is a tree-like data structure that is constructed by the browser when the page is loaded, and it is updated whenever changes are made to the page’s content or layout. When a change is made to the Real DOM, the browser re-renders the affected parts of the page, which can be slow and inefficient, especially for large and complex pages.
  • The Virtual DOM is a lightweight representation of the Real DOM that is maintained by a JavaScript library or framework, such as React. When a change is made to the Virtual DOM, the library or framework is updating the Real DOM.
57
Q

When adding an item to an array, why is it necessary to pass a new array to the useState hook ?

A

React uses a concept called “state immutability” to manage updates to the UI. This means that instead of directly modifying the state of a component, you must create a new state object that represents the updated state.

58
Q

Describe what techniques or tools you use to debug a react app.

A
  • console.log()
  • Chrome DevTools
59
Q

What is the difference between a react class component & a functional component ?

A
  • Class components are the older way of writing React components. They are defined using ES6 classes and can have their own internal state, lifecycle methods, and more complex features.
  • Functional components are generally faster and lighter than class components.
  • Functional components are a newer way of writing React components, introduced alongside Hooks. They are simpler and focused on just rendering UI. With the introduction of Hooks, functional components can also manage state and use other React features that were previously exclusive to class components.
60
Q

Name 3 lifecycle states in a react functional component.

A

Mounting, updating, and unmounting

61
Q

What is conditional rendering in react ? Give an example.

A

Is a technique that determine which components to render based on the current state or props of the component.

  if (isLoggedIn) {
  return <h1Welcome back!</h1;
 }
  return <h1Please sign up.</h1;
62
Q

Write the code that prints to the console component destroyed when the component it is part of is removed from the DOM tree.

A
useEffect(() => {
    // This code runs when the component is mounted
    console.log("Component mounted");

    return () => {
      // This code runs when the component is unmounted
      console.log("Component destroyed");
    };
  }, []);
63
Q

Why is there an infinite loop in this code

function App() {
  const [count, setCount] = useState(0); //initial value of this
  useEffect(() = {
    setCount((count) = count + 1); //increment this Hook
  }); //no dependency array.
  return (
    <div className="App">
      <p> value of count: {count} </p>
    </div>
  );}
A

Because the useEffect has no dependency array so it will be executeted at every rerender and because of setCount() a new rerender will be triger

64
Q

Why is there an infinite loop in this code

  async function App() {
  const [count, setCount] = useState("");
  setCount(count + 1);
  return (
    <div className="App">
      <p> value of count: {count} </p>
    </div>
  );
}
A

Beacause setCount() does a rerender and it is called everytime when the render is made with a diffrent value making the rerender be trigered again and so on.

65
Q

What is a database schema ?

A

A database schema defines the shape of the documents in a collection by specifying the fields and their data types. It can also define default values, validators, and other options for the fields.

66
Q

Why is the id unique in a database ?

A

** - Mongoose creates an _id field for each document in a collection that serves as a unique identifier.An ObjectId is a 12-byte value that contains a timestamp, machine identifier, process identifier, and a random number.**
** - It ensures that each piece of data has a distinct label, preventing duplicates, aiding in efficient searches, supporting data connections, and maintaining overall data accuracy and reliability.**

67
Q

What are the advatanges & disadvatages of using lean() function in a mongo query ?

A

The lean() function is a query modifier that can be applied to a Mongoose query before executing it.

  • Advantages:

1. When you use lean(), Mongoose skips the step of creating a full Mongoose document object and returns a plain JavaScript object instead

2. Since lean() returns a plain JavaScript object instead of a full Mongoose document object, it can help reduce the overhead of using Mongoose

3. When you use lean(), you reduce the amount of memory that is required to store the results of a query.
- Disadvantages

1. When you use lean(), you lose some of the functionality that comes with Mongoose documents, such as instance methods, virtual properties, and pre and post hooks.

2. When you use lean(), you bypass Mongoose’s schema validation, which can result in data that does not conform to your schema being returned by the query.

3. When you use lean(), Mongoose does not track changes to the data returned by the query. This can make it harder to detect and handle changes to the data in your application.

68
Q

Write the code to store the object {name: "Andrew", age: 10} to a mongo database. You can ignore the part of connection parameters.

A
try {
    const saved = await UserModel.create({name: "Andrew", age: 10});
    return res.json(saved);
  } catch (err) {
    return next(err);
  }
69
Q

Write the code to delete from a mongo database all employees that are over 18 years. The scheme for an employee is {name: string, age: int}. You can ignore the part of connection parameters.

A
try {
    const deleteUser = await UserModel.deleteMany({ age: { $gte: 18 } })
// or deleteMany({ $where: "this.age > 18" });
    return res.json(deleteUser);
  } catch (err) {
    return next(err);
  }
70
Q

Write the code to display in the console from a mongo database the employees who are over 18 years. The scheme for an employee is {name: string, age: int}. You can ignore the part of connection parameters.

A
try{
    const olderUsers = await UserModel.find({age : {$gte: 18}});
// or find({ $where: "this.age > 18" });
    return res.json(olderUsers);
  } catch (err) {
    return res.json({error: err})
  }
71
Q

Write the code to update from a mongo database the employees with name=’John’ and set the new age to 8. The scheme for an employee is {name: string, age: int}. You can ignore the part of connection parameters.

A
try {
    const updatedEmployee = await EmployeeModel.findAndUpdate({name: "John"}, {age: 8});
    return res.json(updatedEmployee);
  } catch (err) {
    return res.json({error: err})
  }
72
Q

How to properly store passwords?

A
  • You can use a hashing algorithm like SHA-256 or bcrypt to hash passwords.
  • Using secure protocols like HTTPS to protect them from interception.*
73
Q

What is encryption and decryption?

A

Encryption and decryption are techniques used to protect information by converting it into a code that can only be deciphered with a key or password.

74
Q

What is hashing?

A

Hashing is a one-way process that takes the password and produces a fixed-length string that cannot be reversed to reveal the original password.

75
Q

What is OAuth2?

A

OAuth2 is a framework for giving third-party applications access to a user’s resources without the need for the user to share their login credentials. It uses access tokens to grant temporary access to specific resources.

76
Q

What is the difference between encryption and hashing? When would you use which?

A
  • Encryption converts data into a secret code that can be reversed with a key or password. Hashing transforms data into an irreversible code used for data integrity verification or password storage.
  • Encryption is used to protect data in transit or at rest, while hashing is used for password storage and data verification.
77
Q

How/where would you store sensitive data (like db password, API key, …) of your application?

A

Sensitive data like passwords or API keys should be stored in secure locations outside of your JavaScript/React application code. This can include environment variables, configuration files, or build tools.

78
Q

What would you use a session for?

A
  • To store information about a user’s login credentials, such as their username and password.
  • To store user preferences, such as language or theme settings.
  • To store items that a user has added to their shopping cart while browsing an online store.
  • To track user behavior across multiple requests, such as recording which pages they have visited or which products they have viewed.
79
Q

What would you use a cookie for?

A
  • To manage user sessions and maintain user authentication state between requests.
  • To store user preferences, such as language or theme settings.
  • To track user behavior across multiple requests, such as recording which pages they have visited or which products they have viewed.
  • To track user interests and display targeted advertising based on their browsing behavior.
80
Q

What does MERN stand for in the context of web development ?

A
  • MERN is an acronym that stands for MongoDB, Express, React, and Node.js.
81
Q

What is routing in the context of a react app ?

A
  • Routing in React refers to the process of displaying different components based on the URL or route that the user is currently viewing. React Router is a popular library used to define routes and associate them with specific components.
82
Q

What is routing in the context of an express app ?

A
  • **In the context of an Express.js application, routing refers to the process of defining how the application responds to different HTTP requests based on the requested URL and HTTP method. **
app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

app.get('/about', (req, res) => {
  res.send('About Us');
});
83
Q

What is CORS policy ?

A
  • CORS policy is a security feature designed to prevent potential security risks that can arise when a web page on one domain attempts to make requests to a server on a different domain. Without proper security measures, malicious websites could potentially use a user’s browser to make unauthorized requests to other websites on their behalf, which could lead to data leakage, unauthorized access, and other security vulnerabilities.
84
Q

What advantages does a developer have for using bootstrap or material ui ?

A
  • Bootstrap and Material UI both provide a collection of pre-designed components
  • Both frameworks are designed with responsive web design principles in mind, meaning that they offer tools and features that make it easy to build websites
  • By using pre-designed components and styles, developers can ensure that their website or application has a consistent look and feel, which can improve the user experience and make it easier to maintain.
  • By using pre-designed components and styles, developers can save time and effort
  • Both Bootstrap and Material UI have large developer communities, which means that there are many resources available, such as documentation, tutorials