/Learning

Primary LanguageTypeScript

JAVASCRIPT

Nm #Question
1 Difference let const var
2 Difference between arrow function and function declaration, expressions
3 What is generator
4 Types Enums Interface. What for are used types? What is union, intersection? What is intersection types?
5 Difference between map, filter and forEach. Does filter, slice methods create new array or mutationg source?
6 What is this in js? Can you change value of this? What is this alone, inside object, inside event handler, inside function? What is for are used call,apply methods? If yout type this in console - what will you get?
7 Is setTimeOut async?
8 What is Promise? Example of promise? What status promis returns? Is promise aycnronious? Name wayss of handling promises. What is promise all? Make a simple example of promise and promise.all
9 What is Closure? Please provide examples. If variable is declared without keyword, is it global?
10 What is differene between sppread and rest operator - name practical examples?
11 What are sets? How to convert Set type to the array? Example.
12 Why using try catch wrapper instead just async await?
13 types and interfaces diff?
14 How to make array from collections js?
15 what is 3rd stringify parameter?
16 what is difference between try block - catch/finally? Please provide an example
17 what will be result of displaying this inside arrow function ?
18 what is object assign ?
19 How does owrk object create? ?
20 Name difference between copying primitive and object ( reference ) ? explain why let a = {};let b = {} not equal objects
21 Does nested function have an access to the outer function in JavaScript? And vice versa ( opposite)

Exercises Javascript Typescript

Nm #Question
1 What will be result of the next code?
2 Split string by some string?
3 Previoius state exampe?
4 Spread object with new key value?
5 How to fix this infinite rendering problem in provided example?
6 How recursion works in javascript?

React

Nm #Question
1 What is react
2 What is unindirectional data flow
3 What is state in react?
4 Can browser read JSX?
5 What is DOM, Virtual DOM?
6 What is difference between es5 and es6?
7 How to create basic React app?
8 what is event in React? What is synthetic event?
9 Explain how lists work in React?
10 Why key should be added to the list elements? Why index shouldn't be added as index?
11 What are the components in React?
12 How to declare state in React?
13 What are props in React?Are props mutable?
14 What is state and props difference?
15 What is high ordered comopnent?
16 UseEffect with lifeCycle methods. Useeffect and useState difference
17 what is useMemo?
18 what are controlled and uncontrolled components?
19 what are react hooks? what is bad practices using hooks?
20 what is useEffect and when we use it? what is difference in comparison to useLayouteffect? When useEffect is called?
21 when do you need to use useCallback?
22 what is useRef hook? Example of use. Is value that useRef returns is mutable?
23 what is useRef useState difference?
24 what is react context? when do we need it? Please list example of data stored in context
25 what is the recommended way to structure your React code?
26 what is good way to test your reactapplications?what is end-2-end testing? what is unit testing? What yuu use for unit testse
27 what is react dev tools? When do you need it as rule?
28 what is create portal? Provide some example of using it. What are downsides of useing portals?
29 what is lazy loading? Explain when you need it. What is difference between lazy loading and dynamic imports
30 what is code splitting? What is lazy and suspense in react? Provide some example. What is Suspense built-int
31 what is SSR and CSR? Does Gatsby.js, NExt.js supports CSR or SSR? When pages are built in ssr in gatsby.js and when page are built in csr? What is advantage of using SSR? Provide some practical example of using SSR
32 what is fragment?
33 what does mean useEffect with emtpy array?
34 asd some example of hook?
35 Provide example of using event listener in react?
36 What is wrong with too many useEffect?
37 JS design patterns used in React?
38 How can you improve performance of react application with caching?
39 Is it good practice to assign state value directly to the input inside form?

GATSBY.JS

Nm #Question
1 What is gatsby.js?

Other

Nm #Question
1 Monorepo and polyrepo (microservices) difference, advantages, disadvantages
2 What is webhooks? Name some real example.
3 What is babel?
4 What is time complexity? Please provide examples
5 Please name some frameworks
6 What is continues integration?
7 Functional and OOP programming difference?
8 what is dependencies and devdependencies difference?
9 what does it mean in package.json (scripts-typecheck)?
10 what does mean extensinos word in your paackage.json?
11 Explain this line ("transpile:clean": "rimraf ./gatsby-.js ./src/**/.js") of packages.json scripots configuration?
12 What is markdown?
13 What is web component? Key features. What is difference between iframe and web compnents
14 what is lit library
15 what is lit library
16 What is ways to improve performance of front-end application? What is prefetching? Code splitting?
17 1. Ways to improve front-end security? 2. how can be done XSS attack on your page?
18 How to improve WCAG standarts in your front-end app)
19 Best practices for front-end)
20 SPA-PWA difference)
21 Difference betwen SPA and gatsby.js, next.js pages
22 What is cookies? What is localstorage? What does have bigger size, bigger capacity? What do we store in localStorage nad what as rule do we store in cookies?
23 1. What is webpack? 2. Name difference between dev and prod webpack configuration. 3. Where is webpack configuration in gatsby.js, next.js frameworks? 4. "build": "webpack --mode production" - what will be result of this command?
24 How to create ( generate ) packages.json file?)
25 Does react testing library work on rendered react components or on dom?)
26 What for are used render, screen methods imported from react testing library?)
27 What is advantages of react-query?)

SPA: Works by loading a single HTML page and dynamically updating the content as the user interacts with the app. Uses AJAX calls to interact with the server, fetching and rendering data without reloading the entire page.

PWA: Extends the functionality of traditional web apps with features like offline access, background sync, and push notifications, thanks to Service Workers. Can be installed on a user's home screen like a native app and can run independently of the browser.

CSS

Nm #Question
1 What is box model ( what are parts of box model)?
2 What for wee need picture and sources
3 What is viewport?
4 What are possible values of position property?
5 What are types of selectors in css?
6 What is rem in css?

GIT, DEPLOYMENT, PIPELINES

Nm #Question
1 What is continuos deployment ( what is continues deployment)?
2 Git merge rebase difference?
3 What is cherry pick?

REDUX, REACT CONTEXT, REACT QUERY, STATE MANAGEMENT

Nm #Question
1 Difference beteen react context and redux
  1. what is difference between let const var

    Var - scope is global or function ( if var's used inside function ). Let, const - they have block scope.

     if(true) {
       let test = 'test'; // test variable is available only inside if block
     }

    Let - can be reasigned. Const - can't be reasigned.

  2. arrow function explanation

    Functional expression - function defined inside an expression. Example:

       const getRectArea = function (width, height) {
        return width * height;
       };
       console.log(getRectArea(3, 4));

    Functional declaration - function declared with function keyword. Functional declaration creates binding of new function to a given name.

       function calcRectArea(width, height) {
          return width * height;
       }
       console.log(calcRectArea(5, 6)););
      function print() {
        console.log(arguments)
      }
    
      print(1,2,3,4);
    
      /*
        result below:
        {
          "0": 1,
          "1": 2,
          "2": 3,
          "3": 4
        } 
      */

    Remember arrow function don't have acces to the arguments.

      const obj = {
      name: 'deeecode',
      print: function() {
        console.log(this)
      }
     }
     obj.print() // {name: 'deeecode', print: ƒ}

    You can't do smth like above with arrow function.

    Arrow function - don't have binding to this ( in inherits this from outside look code example below), arguments, super and shouldn't be used as methods. They can't be used as a constructors - we can't call them with new keyword. Cannot be used as generator functions.

    Explain next examples:

       function Person() {
         this.age = 0;
     
         setInterval(() => {
             this.age++; // `this` refers to the `Person` instance
             console.log(this.age); // Correctly logs the incremented age
         }, 1000);
       }
    
      let p = new Person();
      function Person() {
        this.age = 0;
    
        setInterval(function() {
            this.age++; // `this` refers to the global object or `undefined` in strict mode
            console.log(this.age); // NaN or throws error in strict mode
        }, 1000);
      }
      let p = new Person();
  3. Generator function

    Generator is a process that can be paused and resumed and can yield multiple values. Generator returns iterable Geneartor object.

      function* generator(i) {
         yield i;
         yield i + 10;
         yield i + 20;
       }
       
       const gen = generator(10);
       
       console.log(gen.next().value);
       // Expected output: 10
       
       console.log(gen.next().value);
       // Expected output: 20
       
       console.log(gen.next().value);
       // Expected output: 30
    
       console.log(gen.next().value);
       // Expected output: undefined

    Calling .next() returns an object in form:

      { 
        value // current value of the iterator, 
        done  // boolean indicating if iteration is finished 
      }
  4. types enums interfaces

    1. What are types, when do we use it? Types are definitions of data type. Typescript compiler use it to detect errors.
    2. What are Tuples?
        let ourTuple: [number, boolean, string];
      ``

    Tuples are typed arrays 4. What are Unions? A union type describes a value that can be one of several types. javascript function printStatusCode(code: string | number) { console.log(`My status code is ${code}.`) } 5. An intersection type is a type that merges several kinds into one.

     interface Student { 
       student_id: number; 
       name: string; 
     } 
       
     interface Teacher { 
       Teacher_Id: number; 
       teacher_name: string; 
     } 
       
     type intersected_type = Student & Teacher; 
       
     let obj1: intersected_type = { 
       student_id: 3232, 
       name: "rita", 
       Teacher_Id: 7873, 
       teacher_name: "seema", 
     }; 
       
     console.log(obj1.Teacher_Id); 
     console.log(obj1.name)
    1. What are enums? When to use? Enums are collection of constants
    2. Types is used to type your values, to avoid errors and bugs. Here more: https://blog.logrocket.com/typescript-enums-vs-types
    3. Enums example:
     enum Names {
        Vasyl,
        Yaroslav,
        Igor
      }
      var test = Names.Yaroslav;// 1
    1. Interface: An interface is used to define a structure for an object.
  5. map-foreach-difference

    Map return NEW array. It doesn't modify initial array. ForEach doesn't return array. But runs function for each element of array. Foreach returns original array. Filter, slice returns new array. They dont mutate initial array.

  6. this-meaning

    1. This is keyword. It refers to different objects depending on how and where it used.
    2. You can't change this value.
    3. ALone this refers to the global object. INside function - this refers to the global object also. In event handlers this refers to the hTML object.
      function dotest() {
          console.log(this); // here we'll get Windows object
      }
    1. Call and apply methods are used to call 1 object method on another object as argument
    2. If yout type this in console, you will get Window object.
  7. settimeout-async

    Yes setTimeout is async

  8. example-promise

    Promise object represents eventual completion or failure of asynchronous function. Whenever tasks should be executed asynchronouslo. Promisess are used. Example login function: image Promise returns fullfilled or rejected status. Promise is asyncchronous function. Promises can be handled with:

    then catch:

      const doPromise = () => {
          new Promise((resolve, reject) => {
              resolve({result: 5 });
          }).then((data) => console.log(data))
          .catch((error) => {
            console.error('Promise rejected with error: ' + error);
          });;
      }
      
      doPromise();
      Promise.then(() => datafetch).then(result => result).catch(()=>'error fetching data')

    asyn await try catch

     async function main() {
       try {
         const doc = await db.doc("user/" + uid).get()
     
         if (doc.exists) {
           console.log("User data:", doc.data());
           // use fetched data, for example in setState()
         } else {
           console.warn("No user data.");
         }
       }
       catch(error) {
         console.log("Error getting user data:", error);
       }
     }

    Promise all (method) takes an array of promises and returns a single promise. The returned promise fullfills if all promises are executed, and noone fails.

      const promise1 = Promise.resolve(3);
      const promise2 = 42;
      const promise3 = new Promise((resolve, reject) => {
        setTimeout(resolve, 100, 'foo');
      });
      
      Promise.all([promise1, promise2, promise3]).then((values) => {
        console.log(values);
      });
  9. closure-explanation

    1. If we speak about closure , we need to mention local and global scope. Functions have its local, private scope. Variables can be global or private - depending where they'are declared.
    2. if variable is declared without keyword, it is global. Even if it's declared inside the function.
      function doTest() {
        test = 5;
      }
      doTest();
      console.log(test); // 5
  10. rest-spread-operator-difference

    1. Spread operator is mostly used with arrays. It's used to efficientl merge, cop arrays, pass elements to functions.

    You can use spread operator to merge 2 objects,or 2 arrays. In React you can use spread operator to pass properties to the component:

      const props = {firstName: 'John', lastName: 'Doe'};
      const component = <UserComponent {...props} />;

    Example of copying array with spread operator:

      const arr = [1,2,3];
      const copyArr = [...arr]

    Example of merging 2 objects:

      const nameObject = { name: 'John' };
      const surnameObject = { surname: 'Cool' };
      const mergedObject = { ...nameObject, ...surnameObject };

    Example passing arguments to functions: ```javascript function sum(a, b, c) { return a + b + c; }

      const nums = [1, 2, 3];
      const result = sum(...nums);
      console.log("Result of sum:", result); //6
    

    rest operator can be used to extract the remaining properties. WHile spread operator used to exapand elements, rest operator used to condense elements into a single enti

      const {a, ...rest} = {a: 1, b: 2, c: 3};
      console.log(rest); // {b: 2, c: 3}

    It helps to get all arguments into an one array named numbers:

      function sum(...numbers) {
        return numbers.reduce((total, num) => total + num, 0);
      }
    
      function printNumbers(...numbers) {
        console.log(numbers); //
      }
      printNumbers(1,2,3,4,5); // [1,2,3,4,5] 
  11. set-object

    Set are collections of unique values:

      const testArr = [1, 2, 1, 1];
      const newSet = new Set(testArr);
      console.log(testArr); // { 0:1, 1:2 }

    if you want to convert it to the arr:

      console.log([...setValue]);

    Set Object provides: A size property that contains a number. A has() method that takes an element and returns a boolean. A keys() method that returns an iterator of the elements in the set.

  12. try-catch

    Wraps code that can fail and pass error to the catch instead of crashing the app.

  13. type-interface-diff

    Types in TypeScript are more flexible and can define primitive, intersection, union, tuple, or different types of data, while interfaces are used to describe the shape of an object

  14. collection-js-array

    Eather

    const arrray = [...yourObjectCollection];
    // Or make it with Array.from
    Array.from(yourObjectCollection)
  15. stringify-3rd-parameter

    it adds additional spacing

  16. try-catch-finally

    Eather

    openMyFile();
    try {
     // tie up a resource
     writeMyFile(theData);
    } finally {
     closeMyFile(); // always close the resource
    }

    or

    try {
        // try_statements
    } catch(error) {
       // catch_statements  
    }
    finally() {
       // codes that gets executed anyway
    }
  17. arrow-function

This inside arrow function is referenced, pointed to the global object. We normal function declaration - it points to the inner scope.

```javascript
  function RegularFunction() {
  this.value = 10;
    setTimeout(function () {
      console.log(this.value); // undefined, because `this` refers to the global object or is undefined in strict mode. It should be remembered that for example in chrome, it can console 10 instead of undefined ( it's connected with specific chrome console aspects ).
    }, 100);
  }
  
  function ArrowFunction() {
    this.value = 20;
    setTimeout(() => {
      console.log(this.value); // 20, because `this` is inherited from ArrowFunction's scope
    }, 100);
  }

  new RegularFunction(); // Logs: undefined
  new ArrowFunction();   // Logs: 20
```
  1. object-assign

Object assign method is used to clone or copy proeperties from 1 object to another.

```javascript
    const obj = { a: 1 };
    const copy = Object.assign({}, obj);
    console.log(copy); // { a: 1 }

    You can add 1 target object, and 2 source objects like that:
    
    Object.assign({}, product, {
      votes: product.votes + 1,
    });
```
  1. object-create

  With help of Object.create we can create an object from a given prototype object. It retrns a new object with the prototype set to given object. 

  ```javascript
    const myPrototype = {
      size: 'large',
      getSize() {
        return this.size;
      }
    };


    const myObject = Object.create(myPrototype);
    console.log(myObject.getSize()); // 'large'
  ```

  It can also be used Object.create to create subobject, which inherits properties and methods from their parent objects.

   ```javascript
        const mySubObject = Object.create(myObject, { 
        color: { value: 'red' } 
    });
  ```
  console.log(mySubObject.getSize()); // 'large' 
  console.log(mySubObject.color); // 'red'
  1. object-primitive-reference

Object is stored and copied "by reference", whereas primitive values strings, numbers, booleans copied as a whole value.
 ```javascript
  let message = "Hello!";
  let phrase = message;
```
In the end we have 2 independent variables.
A variable assigned to an object = stores not object itslef, but its address in memory, in other words - a reference to it.
```javascript
  let user = { name: "John" };
  let admin = user;
```
![image](https://github.com/user-attachments/assets/b687fb14-9572-4f85-bdc9-5ca86afb1a21)

When objects are equal?
![image](https://github.com/user-attachments/assets/9f1bf005-6efc-4d44-8125-c56089341c29)
Two independent objects are not equal:
let a = {};
let b = {}; // two independent objects

alert( a == b ); // false
  1. inner-outer-function-scope

Outer function doesn't have an access to the inner functions. But inner functions have an access to the outer functions. It's how lexical scope does work.

Exercises Javascript Typescript

  1. for-each-result-exercise

       const names = ["Rohit","Aakash","Vinay","Ashish","Vasu"];
       const tes = names.forEach((item) => item + 'lolo');

    Answer: it will be undefined, cause forEach doesn't return any walue, it just runs function for each element of array

  2. split-string-exercise

      var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
      s.split('~')
     ``
  3. previous-state-example

    Count example (to get previous state we need to put callback function): image

  4. spread-object-kay-value

    const test = { test: 'test '};
    {...test, name: 'pame'}
     ``
  5. infinite-rendering

    image Answer -setCounter should be used out of useEffect here to prevent infinite rendering problem.

  6. recursion-javascript

    image image


  1. What is react

    React - is library. Main React features:

    1. JSX - js extension. We can write HTML structures inside JS. For example use HTML structures inside if structure: image

    2. Components - we create reusable, independent components.

    3. Virtual DOM - it's virtual copy of DOM, with help of it preformance is improved. With help of that we update only necessary things in DOM, not rebuilding all DOM tree.

    4. One way data-binding.

    5. high performance - while updating components - we don't refresh, update all application.


  2. What is unindirectional data flow

    Children component're placed inside parent component. Data's transfered from parent component to child component. Benefits unindirectional data-flow: 1. Easy to debug - cause we know how and frome where data is coming. 2. Less errors - more control on data.


  3. What is state in react

    State in React - is object containing component an information. It can be changed. When state's changed, component is rerendered. Remember not to mutate directly React's state, cause it can lead to different problems, bugs. When state's updated, react calls render() method and component's updated.


  4. Can browser read jsx

    Nope, it's used babel to transpile jsx code to regular JS.


  5. what is dom

    Document Object Model - is interface that treats HTML as a tree structure, in which each node is object representing a part of the document. DOM defines a way nodes are accessed and manipulated. image Virtual DOM - it's virtual copy of DOM, with help of it preformance is improved. With help of that we update only necessary things in DOM, not rebuilding all DOM tree.
    React Reconciliation process of updating DOM. It updates the virtual DOM first and then uses the diffing algorithm to make efficient and optimized updates in the Real DOM.


  6. difference between es6 es6

    • es6 ins newest version of js
    • es6 has additional type Symbol
    • es6 has 2 new ways of declaring variables: let and const
    • es6 has arrow function
    • little bit difference while importing, exporting components, declaring classes

  7. basic react app

    Install node, instal crea-react-app. It's ready to use.


  8. what is event in react

    Event in React is action triggered on some change in the user interface. It can be click or key pressing for example. Synthetic event - synthetic event is object we get after triggering some event. An example:

   <button onClick={e => {
     console.log(e); // React event object
   }} />
  1. lists-in-react

    List is created with help of map method. image

  2. keys in react lists

    1. Key is a unique identifier and it is used to identify whhich element of list was updated, deleted or added. Keys also help to improve performance of rendering lists.
    2. Index should be added as index cause, if you for example filter your list - elements of list will get new indexes - other than you initialized at first.
  3. commponents in react

    React application consists of react component. Component is a reausable piece of code. Component can be stateless or statefull.

  4. state in react

    You needed constructor and set value to the this.state. Now you can just use useState hook.

  5. props in react

    Props are short for properties. In React it's object, storing value of attributes, smth. like html attributes. We need it to pass data from component to the component. Inside component we have an access to props in similar way as we have an access to the function parameters. Props aren't mutable in React.

  6. state props difference

    State is muttable. Props are unmutable. State refers to internal data of component. Props are date transfered from parent component to the child.

  7. high-ordered-component

    High ordered component is wrapper for other components. They allow to reuse some logic across different components. F.e. you want to add logger HOC, which will be loging information about mounting, demounting component. export default withLogger(SomeComponent);

  8. use-effect-lifecycle-methods

What are standart lifecycle React methods?
**getInitialState()**, **componentDidMount()**, **shouldComponentUpdate()**, **componentDidUpdate()**, **componentWillUnmount()**.
UseEffect is used for handling sideEffects - like getting some data, or handling some event.
  1. use-memo

UseMemo() hook helps to cache, remember the result of calculations between rereners.

 // trivial example of using useMemo

  ```javascript
    const sortedNames = useMemo(() => {
     [...someValue].sort();
    }, [names]);
  ```
  
 ```

// if we wanna have different value of method, depending on url value:
 ```javascript
    const method = useMemo(() => {
       method: "Post",
       url
    }, [url]);
  ```
  1. controlled-uncontrolled-componenent

We used controlled or uncontrolled components inside form ( while dealing with inputs ). If we have input connected to the state, and handle that value. It's controlled component. Displayed data is syncronized with the state of component. image

Uncontrolled components hold their state internally. And you query DOM using a ref to find its current value when you need it.

  1. react-hooks

Hooks was added in React 16.8 to allow function components to have access to state and other React features. Bad practices: - dont dynamically mutate a hook, dont dynamically use hook. Example: don't push hook as prop.

  1. use-effect-hook

    1. UseEffect allows to perform you side effects in your application ( fetchingdata, diretly update dom, setting timers).
    2. useEffect is called after first render, and every time component is updated.
    3. Difference between useEffect and UseLayoutEffect ( Useeffect runs after browser finishing painting,useLayoutEffect runs synchronically with painting browser). UseEffect has built-in error handling, so it doesn't crush entire application,whiel useLayoutEffect doesn't have it.
  2. use-callback

    Usecallback memoizes a function definition and returns momoized function during rerenders, it improves performance in that way. If you need call function, but don't want it toretriggered in useEffect, then you will need useCallback. If we want to pass some function, to the component, and we don't want that component to be rerendered. Then can use useCallback. Example: image

  3. use-ref

    1. UseREf is hook, which we need if we want to operate directly with DOM.
    2. Example of use: if we need for example some input in form to be auto focused. We need to find that element in DOM and autofocus.
    3. UseReff return object with current property.
        const refValue = useRef(0); // this will return { current: 0 } object.

    UseRef example: image

  4. use-state-use-ref-diff

    With help of both you can save some value. Whatever you store in useRef is not reactive, it means it will not cause component rerender.

  5. react-context

    React context is alternative to the 'prop drilling' ( passing data from parent to children ). Context is often consideredas lighter, simpler solution to using Redux for state management. With context API we have 1 store where all data is passed to and from all data is extracted from. Example of data stored in context: template language, user authentificated data. ANother good example is dark mode - if you want an access to it from each component.

  6. react-structuring-code

    You need specific folder for your components ( it can be also seperate folder for your common components ), for hooks, constants. It's good to have proper structure - it's easier to find what you need, it's easier to make onboarding for new team members. It's god to use absoolute imports.

  7. react-test-how-work

    1. YOu can use e2e tests ( when you test your whole applications ( all components connected 1 to another) on real scenarious, data ). You can also make unit tests ( when you testing behaviour of each component)
    2. We use react-test-library and react-test-renderer ( to render yoru components to js objects ). You operate on real DOM, while using this library. You can find element by role or by data-testid. It can be also simulated events with help of that library.
  8. react-dev-tools

    React dev tools is extension, it can be installed for any browser. As rule we use it if we have some problem with performance ( for example component is rendered too many times ).

  9. react-portals

    1. React portals let you render some component outside your normal react component structure.
    2. Example: you can use it for creating modals.
    3. portal will not inherit parent css styles. Remember using stopPropagation() - event emmited from a portal component - will propagate to the Reactt tree and trigger event on ancestor component. Example createPortal: image
  10. lazy-loading-dynamic-imports

    1. Imagine you have component, that appears afoter in some scenarios. It's allways displayed in your app. But it still exists in your bundle. To fix it you can use lazy loading or dynamic imports.
    2. Below you can see lazy loading of component. image Now inside our component we can use it with react suspense.
    3. Example of dynamic import: if some condition is met, then we import our component: image Here you will have error, cause you can't render Promise with appropriate handling of it. Acually its why is better to use lazy loading - it handles Promise issue of importing components.
  11. code-splitting

    1. Splitting code is technique which allows to optimize the performance of React application. With help of it you can split your code into smaller chunks and loading the on-deman. You can reduce load time. React provides built-in tools. Like lazy, suspend.
      const SomeComponent = React.lazy(() => import('~/components/SomeComponnent')
    1. SUspense let you load fallback, while yoru children components are loading.
    2. One more way - is using dynamic imports ( for example for functions ).
  12. ssr-csr

    1. SSR - Server side rendering. CSR - CLient side rendering.
    2. Gatsby.js and Next.js supports both CSR and SSR.
    3. Static Pages are built during build time. SSR allow to render a page during run-time. You can deal with data that is fetched when a user visits the page.
    4. 1 of the most importa benefits oF SSR can be improving performance of your website. You can reduce the amount of work the users's browser needs to do.
    5. Practical example: you need to call some script and add smth to the header only after some behaviour user on page. In gatsby.js pages are rendered statically during build, to do smth like that you need SSR.
  13. fragment-explanation

    Fragment alows you to return group ofchildren elments without need of extra DOM component.

  14. use-effect-empty-array

    Your effect will run only after initial render.

  15. example-hook

    Hooks are reusable functions. Example: hook for fetching data, or another example hook for recognition screen size. image

  16. event-listener

    Hooks are reusable functions. Example: hook for fetching data, or another example hook for recognition screen size. image

  17. #too-many-useeffect-explain

    image solution: it's better to drop it in 1 useEffect and handle different cases. Or you can drop it in distinct function.

  18. #design-patterns-react

    Observer patterns - it's actually using state in React. When state data changed, component ( dependent properties ) are updated. Singleton Pattern - singleton pattern, when global state is shared across the application.Singleton can only have 1 instance. Proxy pattern - For example handling lazy loading of images. Example: when you have RealImage class, but access to it provides ProxyImage class.

        class RealImage {
          display() {
            console.log("Displaying the real image.");
          }
        }
        
        class ProxyImage {
          constructor() {
            this.realImage = new RealImage();
          }
        
          display() {
            console.log("Loading the image...");
            this.realImage.display();
          }
        }
        
        const image = new ProxyImage();
        image.display();
  19. #caching-react

    1 of possible solutions: You can set some flag with help of localstorage f.e. after you fetch data. And the you check if this flag is true, if it's you aren't fetching data 2nd time.

  20. #form-input-react-handling

    It's better use controlled components - assign some 'handleChange' function, and control state of input inside it. It's better approach for testing, debugging approaches.


  1. Monorepo and polyrepo difference

Monorepo - its one repo, containing multiple applications, projects with well defined, structured relationships.

Polyrepo - a repo for each team, application, project. It's often has a single build artifact, and simple build pipeline. Build artifact - files produced by build ( different logs, reports, distribution pacakgs ).

1. Is **Monolith** same as monorepo? No, monolith itj just repository containing a application, but there is no well prepared dependencies, it's not wel structured and encapsulated.
2. What is advantage of **polyrepo**? With help of it we can keep team autonomy. You can decide what you do with your repo, who can have access for it, when to deploy it etc.
3. What is disadvantages of **polyrepo**? 
- problem when you want to share code betweend different repos;
- problems with compability of third party libraries;
- time consuming configuration of each repo and synchronizing it.
- if each team works only on 1 repo, code can be repeated etc; its easier to standartize work of teams.
- if we have some share repo, library and you need to make change, it should be tested change for reach repo.
- each repo can have different settings tools
- it can be problem to use projects like that.
4.What are advantages of **monorepo**? 
- easy to create new project;
- it's easy to test your change for different packages or applications.
- it's better developer mobility and performance while working on monorepoy
- all projects inside monorepo using same versions of thirls party libraries;
- atomic commits - you dont need different projects, apps dependency after each commit, change

Advantages of microfrontends ( polyrepo ):
![MicroServicesIamge](https://github.com/user-attachments/assets/e5049a98-d0cb-4fdd-a965-48f63f4456fe)
1. Independence and autonomy - teams can work on different parts of the frontend without interfering each other. Each team can use its own stack, library, deployment pipelines.
2. Technology diversity - freedom to choose any technology.
3. Resilience and fault isolation - if one micro fails, it doesn't bring down the entire application.
4. Its easeier to maintain test and refactor distinct micro frontend.

image


  1. what is webhooks

Webhooks - automated messages sent from apps when something (event) happens. Example payPal sends you notification, when some of clients payed you some money. OR when some ecomerce shops notify you when you have some new order. It's a way one app push automatically notifications to other app.

  • what is difference between webhook and API? To put it simply - API does stuff when you ask it to. Webhooks does it when some situation, event is triggered. We can say it works on its own.

  1. what is babel

    1. Babel is transpiler, with help of it developers can use newest features of language.
    2. Babel configuration. You need node.js, npm. Later create configuration file, babelrc. NExt install plugins, presets. And finally creating build script.
    3. Source target difference. Source - code written in a way Babel can understand it, target - code that should be in the end as output.
    4. How to configure babel for a specific framework? Each framework like react or angular has its own preset. Preset-react, preset-angular etc.
    5. @babel/runtime - helpers for optimisinig babel work. It helps for example to exclude repeatable code.

  1. time complexity space complexity

    Time complexity. It calculates amount of time it takes to run an algorithm.

    • O(1) - constant. Run time is independent - we don't worry about the input size. image Examples: accessing an Array Element, REtrieving a Value from object. Retrieving element of array or object takes constant times.
    • O(n) - linear time algorithm - execution is proportional to the input size. image
    • O(n²) - quadratic algorithm - number of steps is square root of input size. For example if we have for loop inside another for loop, and these loops're manipuating on the same input. image

    Space complexity - amount of memory space required to solve some problem/algorithm. Examples:

    • O(1) - constant. Run time is independent - we don't worry about the input size.
       function add(n1, n2) {
         const sum = n1 + n2
         return sum
       }

    Space complexity is constant. Cause input is constant. We'll always get 2 parameters.

    • O(n) - Linear. Space complexity is increasing depending on parameter length.
       function sum(arr) {
         const sum = 0
         for (let i = 0; i < arr.length; i++) {
           sum += arr[i]
         }
         return sum
       }

    It can be also logarithmic O(log n) time complexity or quadratic O(n^2) f.e.



  1. name some front end frameworks

Next.js, Gatsby.js.


  1. continues-integration

    Continuous integration refers to the build and unit testing stages of the software release process ( you can implement it with jenkins for example in your project)

  1. functional-oop-programming

In OOP, the fundamental basis is classes, instances of which can be stored in variables. In functional programming, however, there are no variables; there are functions and functions only.


  1. dependencies-devdependencies-difference

Dependencies are crucial for your production build. While Devdependencies are needed only while dev work, but we don't need in production build.


  1. package-json-scripts-typecheck

When you run npm run typecheck or yarn typecheck, the TypeScript compiler will analyze your TypeScript code and perform type checking based on your type annotations and configuration


  1. extensions-word-package-json

This option specifies the file extensions that Babel should consider for transpilation image


  1. transiple-clean-explanation

This line cleans all transpile files inside chooden folders, to make sure project runs properly and without transpilesd files leftovers.


  1. markdown-explanation

Markdown - markup language used to add formatting for your text ( healdlines, lists etc. )


  1. web-components

Web components - it helps to create reusable, encapsulated HTML elements. Key features: creating custom element, shadow dom ( scoped style, eventy ), html template. You have alss lifeceycle methods, you can cahange attributes etc.


  1. lit-library

***Lit library*** - is library for building web components. It's fast and provides reactive compnent ( components are automatically updated after data change ).
It has shado dom suppoort, lifecycle managements, typescript support etc.
 ![litComponentExplain](https://github.com/user-attachments/assets/8cd45ee5-13ce-46da-84b4-a3d4f894aaf3)
  1. Property - iit's like external prop
  2. state - it's something like react state
  3. Callback - it's lifecycle method.

  1. web-api

    Forms Api - helps validate forms.
      const inpObj = document.getElementById("id1");
      if (!inpObj.checkValidity()) {
    History API - accessing windows.history object.
      window.history.back();
    Web Storage API - geting, setting storage.
     localStorage.setItem("name", "John Doe");
     localStorage.getItem("name");
    Fetch api
     fetch(file)
     .then(x => x.text())
     .then(y => myDisplay(y));
    Geolocation api
        ...
       navigator.geolocation.getCurrentPosition
        ...
    Other examples: window.location, window open etc.

  1. improving-performance

    1. Clean html - check if app has appropriate html5 tags
    2. Reduce number of server calls if possible - lazy loading for example
    3. Css - prefetch fonts for example, check if there is no leftovers in css, simplify selectors. Splitting css modules - css that we don't need on page loading. Can be loaded later.
    4. Optimize videos, images - compress size, resize for different viewports, lazy loading.
    5. Prefetching in front-end development is a performance optimization technique that involves loading resources (like data, images, scripts, or other assets) in advance, before they are actually needed by the user.
    6. Caching - in next.js, gatsby.js it's is configured by the default.
    7. Code splitting - is the practice of splitting your codebase into multiple bundles or chunks that can be loaded on demand, rather than loading the entire codebase at once.

  1. front-end-security

    1. Question answer:
    2. CSP - setting csp data in meta tag, header.It helps against Cross-Site Scripting and data-injection attacks.
    3. Keep authorization data in env variables.
    4. Most commont types of attacks: Malware, cross-site scripting, data-injections, DOS ataki ( it depends alot what is your server capable of ).
    5. question naswer: IT can be posted some content, script, maleware to the form if it's not sanitized.

  1. wcag-standarts

    1. semantic html
    2. keyboard navigatoin ( tabindex)
    3. color contrast, focus contrast
    4. text alternatives for images , aria-labels for buttons forms
    5. responsive images
    6. aria links, CEO settings

  1. best-practices-frontend

    1. SOLID 1. Component or function should have oneresponsibility, purpose 2. Open for extension 3. Subsitituion Principe - input should work with all types of input. 4. Interface Segratgateion Principle - dont pass something, you dont need to component. 5. Dependency inversion - high level modules should not depend on low-level modules directly. here more Info: https://chatgpt.com/c/66d99613-6570-800c-8416-bd259966b6a3
    2. Clead readable code
    3. Component designs - sepearate login, view in different files. Dont-write to larga components
    4. Avoid rerenders, implement lazy loading.
    5. Accessibility
    6. Testing debugging
    7. Avoid inline javascript and css

  1. spa-pwa-difference

SPA Works by loading a single HTML page ( file) and dynamically updating the content as the user interacts with the app. Key parts: - onlly parts of application are updating, refreshing not the whole application - less loading - better user experience - SPA: gamil, google maps, twitter - there is probles with SEO - cause it's all 1 file and dynamic reloading of content. IT's why sometimes google has problem with crawling such site.

PWA Extends the functionality of traditional web apps with features like offline access, background sync, and push notifications, thanks to Service Workers. Can be installed on a user's home screen like a native app and can run independently of the browser. Examples: spotify, uber, telegram, PWA


  1. spa-gatsby-next-difference

SPA renders pages on client side. Content is updated without reloading pages. Single html file. Problems withs SEO. Best suited for dynamic, highly interactive applications like dashboards, social networks, or apps that need frequent, real-time updates. GATSBY, NEXT are SSG ( static site geeneration ) - pages are served as statisc files, it's super SEO friendly, provides benefits of both spa and server-rendered pages. Good SEO. Ideal for content-heavy sites, blogs, marketing pages, or e-commerce sites where performance, SEO, and fast initial loads are crucial.


  1. localstorage-cookies

The most important difference is - localstorage has bigger capacity ( 5mb), while cookies have only 4kb. In cookie we can save some small data, like info about user session durability. In localstorage we can store bigger chungs of data.


  1. webpack-explanation

    1. Webpack is a tool for configuration your project environment, it helps to bundle your project modules.\

    2. In dev we want features like:

      1. strong source mapping - allows developers to see the original source code (e.g., TypeScript, SCSS, or ES6+) in the browser’s developer tools instead of the compiled or minified code that is actually running in the browse. Frameworks like gatsby.js, next.js have it by default.
      2. Localhost, live reloading, hot moudle replacement - monitoring chamges, updating modules, replacing moudules, callback execution.
      3. Envrionment variables. So dev is about dubugging,efficient workflow.

      In prod we focus on:

      1. minifiying and optimizing sources, files, assests.
      2. code splitting - create smaller chunks, and load them if only you need it.
      3. Tree shaking - removes unused code.
      4. Ensure that any debug or tet code is stripped out and not included in production mode.
    3. Frameworks like gatsby.js, next.js have its own webpack.config. But both that framework allow to add your own additional webpack configurations.

    4. "build": "webpack --mode production" - result will be file main.js in your dist folder. In the end you will get main.js file with minified, optimized code. process.env.NODE_ENV - in that file will be set to the 'production' mode.


  1. creating-package-json

You can create it manually or you can use npm init command.


  1. react-testing-library

React testing library works on real DOM. You can find form elements by their label text, finding links and buttons from their text. You can use also datatest-id in places, where you can't use other methods.


  1. render-screen-testing-react-library

Render method is used to render component, screen method is used to find element, what you need by role, label or testid.


  1. react-query

 Advantages of react query: - simplified data fetching; - caching; - updating data in background

  1. box-model

box model - it's box which wraps every HTML element. Box model consists of content, padding, bordery, margin. image


  1. picture-sources

    Picture and source are used if we want to add alternative versions of image depending on size of screen for example.

  1. viewport-what

    The viewport is the user's visible area of a web page. The viewport varies with the device. - we set width of peage to follow screen-width of the device. Initial-scale=1.0 defines zoom defult level.

  1. position-property

    Relative, absoulte, static, fixed, sticky.

  1. selectors-css

    Id, Classs, Element, * - all. We have also Descender, children sibling selectors.

  1. rem-css

    Rem - dictate an element's font size relative to the size of the root element. In most cases 16px is default. 1 of the most valuable advantages of rem is scalability and consistency.

REACT REDUX STATE MANAGEMENT LIBRARIES

  1. react-context-redux

    Context react is more useful when you work with simple application. Redux is used when more complicated cases, applications.

What is cookies, sessiens, tokens what is turborepo in few words

What is Encapsulation https://www.linkedin.com/pulse/what-encapsulation-javascript-amit-kumar/ https://dev.to/kozlovzxc/js-interview-in-2-minutes-encapsulation-oop-2ico

arrow function with normal functino difference: https://bootcamp.uxdesign.cc/arrow-functions-vs-regular-functions-in-javascript-29db7928d696

preventDefault(): Prevents the default browser action for the event. stopPropagation() - difference

///////////// react exercises :

// create a simple react app that display a list of countris and their capitals // requiremeites: // the list of countries and capitsls should be fetched from the API // the list should be displayed in the CountiriesPage // each country should be displayed in a seperate component // the user should be able to filter the list by capital

const BASE_URL = "https://restcountries.com/v3.1/all";

/**

  • To filter by capital city, use the '/capital/{capital}' endpoint */ const FILTERABLE_CAPITALS = [ "Talinn", "Helsinki", "Stockholm", "Oslo", "Copenthagen", "Reykjavik", ];

//////////////

////// How to pass data from child to parent:

image

//////


  1. gatsby-framework

Gatsby.js is framework - used to generate static pages during build. Main feautres of gatsby.js: - it's based on React.js - it used Graphql to plull data nad structure it.


GIT, DEPLOYMENT, PIPELINES

  1. continuos-deployment

Continuos deployment - software development practice where code changes are automatically deployed to a production envrionment after passing predefined testing and qualisty assurance stages. It helps to reduce manual intervention and to ensure new code (feats, fixes etc) are delivered to users as quickly as possible. You can configure it in netlify for example.


  1. merge-rebase-difference

    merge - combining changes from one ( source branch) into another branch ( target branch). It combines history of 2 branches. Git merge pulls in the latest changes from main into the feature branch creating a new "merge commit" in the process. Use merge if you need to keep, save history of both branches. Whe fewe people collaborates on same branch. See example below: image

    rebase - is moving the changes from one branch onto another branch. It puts commits from one branch to another in linear way. See below: image

    Use merge if you need to keep, save history of both branches. Whe fewe people collaborates on same branch. Use rebase if you you want clean, linear project history. Use it to update branch with the lst changes from min branch before merging.

    Below you can see difference between git merge and git rebase. Main difference is while you doing rebase, you keep consisten commit history. image


  1. cherry-pick

In simple terms, git cherry-pick picks a specific commit from one branch and apply it to another branch without merging the entire branch.