<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cristian Campos on Medium]]></title>
        <description><![CDATA[Stories by Cristian Campos on Medium]]></description>
        <link>https://medium.com/@ccampos.aviles?source=rss-e09857a890c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZE6UHA9OE480wSwH.</url>
            <title>Stories by Cristian Campos on Medium</title>
            <link>https://medium.com/@ccampos.aviles?source=rss-e09857a890c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:27:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ccampos.aviles/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TypeScript interview]]></title>
            <link>https://medium.com/@ccampos.aviles/typescript-interview-72368c22a825?source=rss-e09857a890c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/72368c22a825</guid>
            <dc:creator><![CDATA[Cristian Campos]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 16:43:25 GMT</pubDate>
            <atom:updated>2025-01-13T18:26:44.854Z</atom:updated>
            <content:encoded><![CDATA[<p>20 questions about TypeScript to prepare your job interview.</p><p>Table of Contents</p><ul><li><a href="#0a9b">What is TypeScript? What are its main advantages over Javascript?</a></li><li><a href="#cf90">How you define a type in TypeScript?, give an example.</a></li><li><a href="#bf81">Explain to us what interfaces are in TypeScript and how to use them.</a></li><li><a href="#abb2">What are literal types and how do they differ from basic types?</a></li><li><a href="#d6bc">What is the difference between any, unknown and never in TypeScript?</a></li><li><a href="#545a">How can you define a function with parameter types and return type in TypeScript? Provide an example.</a></li><li><a href="#e332">What are classes in TypeScript and how are they different from classes in JavaScript?</a></li><li><a href="#013b">How is inheritance implemented in TypeScript? Provide an example.</a></li><li><a href="#a8b9">What are access modifiers (public, private, protected) and how are they used in classes?</a></li><li><a href="#6cdc">What are generics in TypeScript?</a></li><li><a href="#9da0">What is a union type and how is it used in TypeScript?</a></li><li><a href="#1a95">How can you create a type that is a combination of other types?</a></li><li><a href="#67c1">What are Decorators?</a></li><li><a href="#40b7">How does TypeScript handle JavaScript support? Is it possible to use JavaScript code in a TypeScript project?</a></li><li><a href="#c7a7">What is the module system in TypeScript and how do you import/export modules?</a></li><li><a href="#31d1">How do you set up a TypeScript project from scratch?</a></li><li><a href="#d31c">What tools or configurations would you recommend to make good use of TypeScript in a project?</a></li><li><a href="#3d1d">How is compile-time type checking performed and what are its benefits?</a></li><li><a href="#f52a">What is the “tsconfig.json” file and what are some of its most important settings?</a></li><li><a href="#ae56">How can you integrate TypeScript into a React project?</a></li></ul><h3>What is TypeScript? What are its main advantages over Javascript?</h3><p>Typescript is a superset of JavaScript that adds static typing and object oriented features. Its main advantages include compile-time error detection, better autocompletion and documentation, and better code organization through interfaces and types.</p><h3>How you define a type in TypeScript?, give an example.</h3><p>A type in TypeScript is defined using the type syntax. For example:</p><pre>let name: string = &quot;Juan&quot;;<br>let age: number = 25;</pre><h3>Explain to us what interfaces are in TypeScript and how to use them.</h3><p>Interfaces in TypeScript are contracts that define the structure of an object. They allow you to specify the properties and methods that an object should have. Example:</p><pre>interface Person {<br>  name: string;<br>  age: number;<br>}</pre><h3>What are literal types and how do they differ from basic types?</h3><p>Literal types allow you to define a specific set of values ​​that a variable can take. For example, you can define a literal type for a variable that only accepts “red”, “green”, or “blue”:</p><pre>type Color = &quot;rojo&quot; | &quot;verde&quot; | &quot;azul&quot;;</pre><h3>What is the difference between any, unknown and never in TypeScript?</h3><ul><li>any: Allows any type and disables type checking.</li><li>unknown: Also allows any type, but requires type checking to be performed before use.</li><li>never: Indicates that a function will never return a value (for example, in an infinite loop or error throw).</li></ul><h3>How can you define a function with parameter types and return type in TypeScript? Provide an example.</h3><p>Parameter types and return types can be defined as follows:</p><pre>function sum(a: number, b: number): number {<br>  return a + b;<br>}</pre><h3>What are classes in TypeScript and how are they different from classes in JavaScript?</h3><p>Classes in TypeScript are similar to those in JavaScript, but TypeScript allows you to add types to properties and methods, as well as implement interfaces and type accessors. This provides better structure and type safety.</p><h3>How is inheritance implemented in TypeScript? Provide an example.</h3><p>Inheritance is implemented using the extends keyword. Example:</p><pre>class Animal {<br>  name: string;<br>  constructor(name: string) {<br>    this.name = name;<br>  }<br>}<br><br>class Dog extends Animal {<br>  bark() {<br>    console.log(&quot;¡woof!&quot;);<br>  }<br>}</pre><h3>What are access modifiers (public, private, protected) and how are they used in classes?</h3><p>Access modifiers are a key concept in TypeScript that helps manage the visibility of class members. They promote encapsulation and improve the maintainability of your code by preventing unintended interactions with the internal state of objects. Using the appropriate access modifier is crucial for designing robust and scalable applications.</p><ul><li><strong>public:</strong> Properties and methods accessible from anywhere.</li><li><strong>private:</strong> Only accessible within the class.</li><li><strong>protected:</strong> Accessible within the class and by derived classes.</li></ul><pre>class Ejemplo {<br>  private privado: string;<br>  protected protegido: string;<br>  public publico: string;<br>}</pre><h3>What are generics in TypeScript?</h3><p>Generics in TypeScript are a powerful feature that allows you to create reusable components, functions, and classes that can work with any data type while maintaining type safety. They enable you to define a placeholder type that can be replaced with actual types when the code is used. This provides flexibility and allows for more abstract programming patterns.</p><p>Example:</p><pre>function identity&lt;T&gt;(arg: T): T {<br>  return arg;<br>}<br><br>// Usage<br>let output1 = identity&lt;string&gt;(&quot;Hello, TypeScript!&quot;); // output1 is of type string<br>let output2 = identity&lt;number&gt;(123); // output2 is of type number</pre><h4>Explanation of the Example</h4><ul><li>Function Definition: The identity function takes one argument arg of type T and returns a value of the same type T.</li><li>Type Parameter: The T is a type parameter that will be replaced with a concrete type when the function is called.</li><li>Usage: When calling identity, you can specify the type explicitly (&lt;string&gt; or &lt;number&gt;), or TypeScript can infer the type from the argument.</li></ul><h3>What is a union type and how is it used in TypeScript?</h3><p>A union type allows a variable to contain one of several types. It is defined using the | operator. Example:</p><pre>let id: number | string;<br>id = 123; // valid<br>id = &quot;abc&quot;; // valid</pre><h3>How can you create a type that is a combination of other types?</h3><p>Type intersection can be used with the &amp; operator. Example:</p><pre>type Person = { name: string };<br>type Employee = { salary: number };<br>type PersonEmployee = Person &amp; Employee;</pre><h3>What are Decorators?</h3><p>Decorators are special functions in TypeScript that can modify or enhance classes, methods, properties, or parameters. They allow you to add additional behavior or metadata to your code in a clean and reusable way.</p><h4>Types of Decorators</h4><p>1 —<strong> Class Decorators:</strong> Modify or replace a class.</p><pre>function LogClass(target: Function) {<br>  console.log(`Class created: ${target.name}`);<br>}<br><br>@LogClass<br>class Example {}</pre><p>2- <strong>Method Decorators:</strong> Modify the behavior of a method.</p><pre>function LogMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {<br>  const originalMethod = descriptor.value;<br>  descriptor.value = function (...args: any[]) {<br>    console.log(`Calling method: ${propertyKey}`);<br>    return originalMethod.apply(this, args);<br>  };<br>}<br><br>class Example {<br>  @LogMethod<br>  greet(name: string) {<br>    return `Hello, ${name}!`;<br>  }<br>}</pre><p>3 — <strong>Property Decorators: </strong>Add behavior to class properties.</p><pre>function LogProperty(target: any, propertyKey: string) {<br>  let value: string;<br>  const getter = () =&gt; value;<br>  const setter = (newValue: string) =&gt; { value = newValue; };<br>  Object.defineProperty(target, propertyKey, { get: getter, set: setter });<br>}<br><br>class Example {<br>  @LogProperty<br>  name: string;<br>}</pre><p>4 — <strong>Parameter Decorators:</strong> Annotate method parameters.</p><pre>function LogParameter(target: any, methodName: string, parameterIndex: number) {<br>  console.log(`Parameter at index ${parameterIndex} in method ${methodName} has been decorated`);<br>}<br><br>class Example {<br>  greet(@LogParameter name: string) {<br>    return `Hello, ${name}!`;<br>  }<br>}</pre><h4>When to Use Decorators</h4><ul><li><strong>Logging:</strong> Automatically log method calls.</li><li><strong>Validation:</strong> Check method parameters or class properties.</li><li><strong>Authorization:</strong> Control access based on user roles.</li><li><strong>Configuration:</strong> Define settings in a clear way.</li></ul><h3>How does TypeScript handle JavaScript support? Is it possible to use JavaScript code in a TypeScript project?</h3><p>TypeScript is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. You can include .js files in a TypeScript project.</p><h3>What is the module system in TypeScript and how do you import/export modules?</h3><p>TypeScript uses the ES6 module system to organize code. Modules can be exported using export and imported with import. Example:</p><pre>// archivo1.ts<br>export const PI = 3.14;<br><br>// archivo2.ts<br>import { PI } from &#39;./archivo1&#39;;</pre><h3>How do you set up a TypeScript project from scratch?</h3><p>A TypeScript project can be set up by creating a tsconfig.jsonfile and running the tsc — initcommand to initialize it. The code can then be compiled using tsc.</p><h3>What tools or configurations would you recommend to make good use of TypeScript in a project?</h3><p>It is recommended to use an editor that supports TypeScript, such as Visual Studio Code, and configure linters (such as ESLint) and formatters (such as Prettier). Also, use libraries and frameworks that support TypeScript, such as Angular or React.</p><h3>How is compile-time type checking performed and what are its benefits?</h3><p>Compile-time type checking is a feature in TypeScript that verifies the types of variables, function parameters, and return values during the compilation process, before the code is run. This checking helps catch errors related to type mismatches early in the development cycle.</p><h4>Benefits of Compile-Time Type Checking</h4><ol><li><strong>Early Error Detection:</strong> Catch type-related errors before the code runs, reducing runtime errors and bugs.</li><li><strong>Improved Code Quality:</strong> Enforcing type safety leads to more predictable and reliable code.</li><li><strong>Better Tooling and Autocomplete: </strong>IDEs can offer better autocompletion and navigation features when types are explicitly defined.</li><li><strong>Documentation:</strong> Types serve as documentation for your code, making it easier for others (and your future self) to understand how to use functions and classes.</li><li><strong>Refactoring Safety:</strong> When you make changes to your code, type checking helps ensure that the changes don’t introduce errors elsewhere in the codebase.</li></ol><h3>What is the “tsconfig.json” file and what are some of its most important settings?</h3><p>tsconfig.json is a configuration file that defines how the TypeScript compiler behaves. Some important settings include target(the output JavaScript version), module (the module system), and strict (enabling strict type checking).</p><h3>How can you integrate TypeScript into a React project?</h3><p>To integrate TypeScript into a React project, you can either create a new project using create-react-appwith the — template typescriptflag, or add TypeScript to an existing project by installing the necessary dependencies (<em>typescript</em>, <a href="http://twitter.com/types/react"><em>@types/react</em></a>, <a href="http://twitter.com/types/react-dom"><em>@types/react-dom</em></a>) and renaming the .js files to .tsx.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72368c22a825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entrevista JavaScript]]></title>
            <link>https://medium.com/@ccampos.aviles/entrevista-javascript-3a73d4f3f5c3?source=rss-e09857a890c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a73d4f3f5c3</guid>
            <dc:creator><![CDATA[Cristian Campos]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 18:51:17 GMT</pubDate>
            <atom:updated>2026-07-03T15:55:54.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tabla de contenidos</h3><ul><li><a href="#b7b4">¿ Que tipos de datos existen en JS?</a></li><li><a href="#94e6">¿Cual es la diferencia entre `==`y `===`?</a></li><li><a href="#49d0">¿Cuales son las diferencias entre let, var y const?</a></li><li><a href="#e93e">¿Cual es la diferencia entre “null” y “undefined”?</a></li><li><a href="#5e58">¿Cuales son las diferencias entre las funciones de flecha y las funciones regulares?</a></li><li><a href="#c0d4">Explíca “this” en JavaScript y da un ejemplo de cómo se puede usar de forma diferente en diferentes contextos.</a></li><li><a href="#0a4a">¿Qué es un “closure”?</a></li><li><a href="#2c95">¿Qué es “Set” y “Map” en JS?</a></li><li><a href="#097c">¿Qué es el hoisting?</a></li><li><a href="#11a0">¿Qué son las Immediately Invoked Function Expressions (IIFE)?</a></li><li><a href="#423b">¿Qué es es el “call stack”?</a></li><li><a href="#0891">¿Qué significa truthy y falsy en JS?</a></li><li><a href="#4f9b">Explica los operadores lógicos en JS</a></li><li><a href="#5830">Explica la doble negación (!!) en JS</a></li><li><a href="#9108">Explica el asincronismo en JavaScript. ¿Qué son las promesas?</a></li><li><a href="#b9de">¿Qué es “async/await”?</a></li><li><a href="#9753">¿Qué es el loop de eventos?</a></li><li><a href="#0cd6">¿Qué son los módulos en JS?</a></li><li><a href="#d9c0">¿Qué es una función de order superior (higher-order functions)?</a></li><li><a href="#7fb9">¿Qué es el currying?</a></li><li><a href="#e45f">¿Que es la “memoization” en JS?</a></li><li><a href="#0450">¿Cuales son las diferentes formas de crear objetos en Javascript?</a></li><li><a href="#daf5">¿Cómo hacer “deep clone” de un objeto en JS?</a></li><li><a href="#761a">¿Cómo funciona la herencia prototípica en JavaScript? (prototypal inheritance)</a></li><li><a href="#c19e">¿Qué es la delegación de eventos y por qué es útil?</a></li><li><a href="#33f7">¿Qué es la desestructuración de objetos?</a></li><li><a href="#3a75">¿Qué es una función “callback”?</a></li><li><a href="#5fa2">¿Cuál es la diferencia entre la coerción implícita y la explícita?</a></li><li><a href="#8413">¿Cómo comprobar si una determinada propiedad existe en un objeto?</a></li></ul><h3>¿ Que tipos de datos existen en JS?</h3><ul><li><strong>Number:</strong> números</li><li><strong>String:</strong> cadenas de texto</li><li><strong>Boolean:</strong> true or false</li><li><strong>Object:</strong> Objecto de JS</li><li><strong>null:</strong> un valor especial que representa “<em>nada</em>”, “<em>vacio</em>” o “<em>valor desconocido</em>”</li><li><strong>undefined:</strong> “<em>ningún valor a sido asignado</em>”. Este tipo es asignado si la variable es declarada sin ningún valor asignado.</li><li><strong>Symbol:</strong> un tipo de datos único e inmutable que puede utilizarse como identificador de propiedades de objetos.</li><li><strong>BigInt:</strong> usado para crear números grandes.</li></ul><h3>¿Cual es la diferencia entre `==`y `===`?</h3><ul><li><strong>== (Loose Equality):</strong> Compares two values after performing type coercion if necessary. Because it automatically converts types, it can produce unexpected results.</li><li><strong>=== (Strict Equality):</strong> Compares both the value and the data type without performing type conversion. This makes comparisons more predictable and reliable, so it is the recommended choice in most situations.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22109e52a96c0116519a8a269ab94ce1/href">https://medium.com/media/22109e52a96c0116519a8a269ab94ce1/href</a></iframe><pre>console.log(5 == &#39;5&#39;);  // true (convierte &#39;5&#39; a número)<br>console.log(5 === &#39;5&#39;); // false (compara número y string sin conversión)<br><br>console.log(null == undefined);  // true (son considerados equivalentes)<br>console.log(null === undefined);  // false (son de tipos diferentes)<br><br>const obj1 = { key: &#39;value&#39; };<br>const obj2 = { key: &#39;value&#39; };<br><br>console.log(obj1 == obj2);  // false (son objetos diferentes)<br>console.log(obj1 === obj2); // false (son objetos diferentes)<br><br>console.log(true == 1);  // true (convierte 1 a booleano)<br>console.log(true === 1); // false (diferentes tipos)</pre><h3>¿Cuales son las diferencias entre let, var y const?</h3><ul><li><strong>var:</strong> Function-scoped, can be redeclared and reassigned. Its use is generally discouraged in modern JavaScript.</li><li><strong>let:</strong> Block-scoped, can be reassigned but cannot be redeclared in the same scope.</li><li><strong>const:</strong> Block-scoped, cannot be reassigned or redeclared. Use it by default unless a variable needs to change.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbccf22c965f7f9ce97bfb3635bdb5e4/href">https://medium.com/media/fbccf22c965f7f9ce97bfb3635bdb5e4/href</a></iframe><h3>¿Cual es la diferencia entre “null” y “undefined”?</h3><p><strong>What is the difference between </strong><strong>null and </strong><strong>undefined?</strong></p><ul><li><strong>undefined:</strong> A variable has been declared but has not been assigned a value.</li><li><strong>null:</strong> An intentional assignment that represents the absence of a value.</li></ul><h3>¿Cuales son las diferencias entre las funciones de flecha y las funciones regulares?</h3><ul><li><strong>Arrow functions:</strong> Provide a shorter syntax and inherit this from the surrounding scope instead of creating their own. They cannot be used as constructors and do not have their own arguments object.</li><li><strong>Regular functions:</strong> Have their own this, which depends on how they are called. They can be used as constructors with new, have their own arguments object, and are better suited for object methods.</li></ul><h3>Explíca “this” en JavaScript y da un ejemplo de cómo se puede usar de forma diferente en diferentes contextos.</h3><p>In JavaScript, this refers to the context in which a function is called. For example:</p><ul><li><strong>Global scope:</strong> this refers to the global object (e.g., window in web browsers).</li><li><strong>Object method:</strong> this refers to the object that owns the method.</li><li><strong>Arrow functions:</strong> this has lexical scope, meaning it inherits this from the surrounding function or scope.</li></ul><h3>¿Qué es un “closure”?</h3><p>A closure is a function that has access to variables from its outer context, even after the outer function has finished executing.</p><p>A closure is created when a function is defined inside another function. The inner function can access the variables of the outer function, even after it has finished executing.</p><p><strong>Data persistence:</strong> Closures are useful for maintaining state between function calls.</p><p>Imagine you have a function that creates a counter. The inner function can access and modify the counter variable even after the outer function has finished executing.</p><pre>function crearContador() {<br>    let contador = 0; // Variable privada<br>    return function() {<br>        contador++; // Accede a la variable del contexto externo<br>        return contador; // Devuelve el valor del contador<br>    };<br>}<br><br>const contador1 = crearContador();<br>console.log(contador1()); // 1<br>console.log(contador1()); // 2</pre><p>En este ejemplo, la función interna (closure) tiene acceso a la variable contador incluso después de que crearContador ha terminado de ejecutarse. Esto permite que el valor del contador persista entre las llamadas.</p><h3>¿Qué es “Set” y “Map” en JS?</h3><ul><li><strong>Set:</strong> A collection of unique values. It automatically removes duplicates and is useful when you need to store only distinct items.</li><li><strong>Map:</strong> A collection of key-value pairs where keys can be any type (not just strings), and it preserves the order of insertion</li></ul><h3>¿Qué es el hoisting?</h3><p>Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope during the compilation phase.</p><p>This means you can use functions before they are defined in the code. However, for variables declared with var, only the declaration is hoisted, not the assignment, which can lead to undefined. Variables declared with let and const are also hoisted but cannot be accessed before initialization (they are in a temporal dead zone).</p><h3>¿Qué son las Immediately Invoked Function Expressions (IIFE)?</h3><p><strong>Son funciones que se definen y se ejecutan de inmediato. </strong>Se utilizan para ejecutar código sin dejar residuos en el ámbito global.</p><p>Las IIFE son útiles para ejecutar código de configuración o inicialización sin contaminar el espacio de nombres global y para mantener variables privadas.</p><h4>Características Clave:</h4><ol><li><strong>Ejecución Inmediata:</strong> La función se ejecuta tan pronto como se define.</li><li><strong>Ámbito Local:</strong> Crea un nuevo contexto, lo que ayuda a evitar conflictos con otras variables en el ámbito global.</li></ol><pre>(function() {<br>    // Código a ejecutar<br>    console.log(&quot;Se ejecuta de inmediato&quot;);<br>})();</pre><h3>¿Qué es es el “call stack”?</h3><p>The call stack is a data structure that keeps track of function calls in a program. It works in a Last In, First Out (LIFO) way.</p><p>When a function is called, it is added (pushed) to the stack. When the function finishes, it is removed (popped) from the stack.</p><p>It helps JavaScript know which function is currently running and what to return to when a function ends.</p><h3>¿Qué significa truthy y falsy en JS?</h3><ul><li><strong>Falsy:</strong> Valores que se consideran falsos en un contexto <em>booleano</em> (false, 0, &quot;&quot;, null, undefined, NaN).</li><li><strong>Truthy:</strong> Cualquier valor que no sea falsy (por ejemplo, true, números distintos de cero, cadenas no vacías, objetos, funciones).</li></ul><pre>if (0) {<br>    console.log(&quot;Esto no se ejecuta.&quot;); // 0 es falsy<br>}<br><br>if (&quot;hola&quot;) {<br>    console.log(&quot;Esto se ejecuta.&quot;); // &quot;hola&quot; es truthy<br>}<br><br>if (null) {<br>    console.log(&quot;Esto no se ejecuta.&quot;); // null es falsy<br>}<br><br>if (42) {<br>    console.log(&quot;Esto se ejecuta.&quot;); // 42 es truthy<br>}</pre><h3>Explica los operadores lógicos en JS</h3><p>Los <strong>operadores lógicos </strong>en JavaScript se utilizan para combinar o invertir valores booleanos (verdadero o falso). Los tres operadores lógicos principales son AND (&amp;&amp;), OR (||) y NOT (!). A continuación, se describen cada uno de ellos:</p><ul><li>AND (&amp;&amp;): Devuelve true si ambos operandos son verdaderos.</li><li>OR (||): Devuelve true si al menos uno de los operandos es verdadero.</li><li>NOT (!): Invierte el valor booleano del operando. Si el operando es verdadero, devuelve false, y si es falso, devuelve true.</li></ul><pre>let a = true;<br>let b = false;<br><br>if (a &amp;&amp; b) {<br>    console.log(&quot;Ambos son verdaderos.&quot;);<br>} else {<br>    console.log(&quot;Al menos uno es falso.&quot;); // Esto se ejecuta<br>}<br><br>if (a || b) {<br>    console.log(&quot;Al menos uno es verdadero.&quot;); // Esto se ejecuta<br>}<br><br>if (!b) {<br>    console.log(&quot;b es falso.&quot;); // Esto se ejecuta<br>}</pre><h3>Explica la doble negación (!!) en JS</h3><p>La doble negación en JavaScript es una técnica que se utiliza para convertir un valor a su equivalente <em>booleano</em>. Consiste en aplicar el operador NOT (!) dos veces a un valor. Esto puede ser útil para forzar la conversión de un valor a true o false.</p><h4>Cómo Funciona:</h4><ol><li><strong>Primera Negación</strong> (!): La primera negación convierte el valor en su opuesto <em>booleano</em>. Si el valor es &quot;<em>truthy</em>&quot;, se convierte en false, y si es &quot;<em>falsy</em>&quot;, se convierte en true.</li><li><strong>Segunda Negación</strong> (!): La segunda negación invierte nuevamente el valor, devolviendo el valor <em>booleano</em> original de forma explícita.</li></ol><pre>let valor1 = 5;          // truthy<br>let valor2 = 0;          // falsy<br>let valor3 = &quot;&quot;;         // falsy<br>let valor4 = &quot;Hola&quot;;     // truthy<br><br>console.log(!!valor1);  // true<br>console.log(!!valor2);  // false<br>console.log(!!valor3);  // false<br>console.log(!!valor4);  // true</pre><h4>Resumen</h4><ul><li>La doble negación (!!) se utiliza para convertir cualquier valor a un valor booleano.</li><li>Es una forma rápida y clara de determinar si un valor es “<em>truthy</em>” (devuelve true) o &quot;<em>falsy</em>&quot; (devuelve false).</li></ul><p>Esta técnica es especialmente útil en situaciones donde necesitas asegurarte de que una variable tenga un valor <em>booleano</em>, como al usarla en condiciones o al almacenarla en una variable que debe ser estrictamente true o false.</p><h3>Explica el asincronismo en JavaScript. ¿Qué son las promesas?</h3><p>JavaScript es un lenguaje de un solo subproceso, lo que significa que solo puede ejecutar una tarea a la vez. Sin embargo, las aplicaciones web modernas a menudo dependen de operaciones que tardan en completarse, como obtener datos de un servidor o leer un archivo. Aquí es donde entra en juego la programación asincrónica.</p><p>La programación asincrónica permite que JavaScript realice estas operaciones que consumen mucho tiempo sin bloquear el hilo principal. Esto significa que su aplicación puede seguir respondiendo a la entrada del usuario y permanecer interactiva mientras espera los resultados.</p><h4>Principales Conceptos de JavaScript Asíncrono</h4><p><strong>Callbacks:</strong></p><ul><li>Funciones que se pasan como argumentos a otras funciones y se ejecutan después de que se completa una operación.</li><li>Pueden llevar a un problema conocido como “callback hell” cuando hay múltiples niveles de anidación.</li></ul><pre>function obtenerDatos(callback) {<br>    setTimeout(() =&gt; {<br>        callback(&quot;Datos obtenidos&quot;);<br>    }, 1000);<br>}<br><br>obtenerDatos((resultado) =&gt; {<br>    console.log(resultado);<br>});</pre><p><strong>Promesas:</strong> <br>Las promesas son objetos que representan la eventual finalización (o el fracaso) de una operación asincrónica. Proporcionan una forma de manejar los resultados de estas operaciones de una manera más estructurada y legible en comparación con los <em>callbacks</em> tradicionales.</p><pre>function fetchData(url) {<br>  return fetch(url)<br>    .then(response =&gt; {<br>      if (!response.ok) {<br>        throw new Error(&#39;Network response was not ok &#39; + response.statusText);<br>      }<br>      return response.json();<br>    });<br>}<br><br>const apiUrl = &#39;https://api.example.com/data&#39;;<br><br>fetchData(apiUrl)<br>  .then(data =&gt; {<br>    console.log(&quot;Data fetched successfully:&quot;, data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&quot;Error fetching data:&quot;, error);<br>  });</pre><p><strong>Async/Await:</strong></p><ul><li>Una sintaxis más limpia para trabajar con promesas.</li><li>async se utiliza para declarar una función asíncrona, y await se utiliza para esperar a que una promesa se resuelva.</li></ul><pre>const obtenerDatos = () =&gt; {<br>    return new Promise(resolve =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&quot;Datos obtenidos&quot;);<br>        }, 1000);<br>    });<br>};<br><br>const iniciar = async () =&gt; {<br>    const resultado = await obtenerDatos();<br>    console.log(resultado);<br>};<br><br>iniciar();</pre><h3>¿Qué es “async/await”?</h3><p>async/await es una forma de manejar operaciones asíncronas en JavaScript de manera más sencilla y legible. Permite escribir código asíncrono que se parece más al código síncrono.</p><h4>¿Qué es async?</h4><ul><li>La palabra clave async se utiliza para declarar una función como asíncrona. Esto significa que la función siempre devolverá una promesa. Si la función devuelve un valor, JavaScript lo convierte automáticamente en una promesa resuelta.</li></ul><h4>¿Qué es await?</h4><ul><li>La palabra clave await se utiliza dentro de una función async para esperar a que una promesa se resuelva. Cuando se encuentra una expresión await, JavaScript pausa la ejecución de la función hasta que la promesa se resuelva o se rechace.</li></ul><h4>Cómo Usar async/await</h4><ol><li><strong>Definir una Función Asíncrona: </strong>Utiliza async antes de la definición de la función.</li><li><strong>Esperar una Promesa:</strong> Usa await antes de llamar a una promesa dentro de la función asíncrona.</li></ol><pre>// Simulando una función que devuelve una promesa<br>function obtenerDatos() {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&quot;Datos obtenidos&quot;);<br>        }, 2000); // Simula un retraso de 2 segundos<br>    });<br>}<br><br>// Función asíncrona<br>async function iniciar() {<br>    console.log(&quot;Esperando datos...&quot;);<br>    const datos = await obtenerDatos(); // Espera a que se resuelva la promesa<br>    console.log(datos); // Imprime &quot;Datos obtenidos&quot;<br>}<br><br>iniciar(); // Llamando a la función asíncrona</pre><h3>¿Qué es el loop de eventos?</h3><p>El Event Loop (bucle de eventos) en JavaScript es un mecanismo que permite que el lenguaje maneje operaciones asíncronas y eventos de manera eficiente, a pesar de ser un lenguaje de un solo hilo. Es fundamental para comprender cómo se ejecuta el código asíncrono y cómo se gestionan las tareas en JavaScript.</p><h4>¿Cómo Funciona el Event Loop?</h4><p><strong>Call Stack (Pila de Llamadas):</strong></p><ul><li>JavaScript utiliza una pila de llamadas para ejecutar funciones. Cuando se llama a una función, se agrega a la pila, y cuando la función termina, se elimina de la pila.</li></ul><p><strong>Web APIs:</strong></p><ul><li>Cuando se realizan operaciones asíncronas (como solicitudes de red, temporizadores, etc.), estas se manejan a través de las Web APIs del entorno. Una vez que se completa la operación, el resultado se coloca en la cola de tareas (task queue).</li></ul><p><strong>Task Queue (Cola de Tareas):</strong></p><ul><li>La cola de tareas contiene las funciones que deben ejecutarse después de que el call stack esté vacío. Cuando el call stack se vacía, el event loop toma la primera tarea de la cola y la coloca en el call stack para su ejecución.</li></ul><p><strong>Event Loop:</strong></p><ul><li>El event loop está en constante ejecución. Su trabajo es verificar si el call stack está vacío y, si es así, mover la siguiente tarea de la cola al call stack.</li></ul><h3>¿Qué son los módulos en JS?</h3><p>Los módulos en JavaScript son una forma de organizar y encapsular el código en archivos separados, lo que permite una mejor estructura, reutilización y mantenimiento del código.</p><h4>¿Cómo Funcionan los Módulos?</h4><ol><li><strong>Exportar: </strong>Permite que un módulo haga que ciertas funciones, objetos o variables estén disponibles para otros módulos.</li><li><strong>Importar:</strong> Permite que un módulo acceda a las funciones, objetos o variables exportadas desde otro módulo.</li></ol><h4>Exportar en Módulos</h4><p>Hay dos formas de exportar elementos en un módulo:</p><p><strong>1. Exportación Nombrada</strong></p><p>Puedes exportar múltiples elementos desde un módulo utilizando la palabra clave export.</p><pre>// archivo: matematicas.js<br><br>export const PI = 3.14;<br><br>export function sumar(a, b) {<br>    return a + b;<br>}</pre><p><strong>2. Exportación por Defecto</strong></p><p>Puedes exportar un solo elemento como exportación por defecto utilizando la palabra clave export default.</p><pre>// archivo: calculadora.js<br><br>export default function multiplicar(a, b) {<br>    return a * b;<br>}</pre><h4>Importar en Módulos</h4><p>Para importar elementos de otros módulos, utilizas la palabra clave import.</p><p><strong>1. Importar Exportaciones Nombradas</strong></p><pre>// archivo: app.js<br><br>import { PI, sumar } from &#39;./matematicas.js&#39;;<br><br>console.log(PI); // 3.14<br>console.log(sumar(2, 3)); // 5</pre><p><strong>2. Importar Exportación por Defecto</strong></p><pre>// archivo: app.js<br><br>import multiplicar from &#39;./calculadora.js&#39;;<br><br>console.log(multiplicar(2, 3)); // 6</pre><p><strong>Importar Todo desde un Módulo</strong></p><p>También puedes importar todas las exportaciones de un módulo como un objeto:</p><pre>// archivo: app.js<br><br>import * as matematicas from &#39;./matematicas.js&#39;;<br><br>console.log(matematicas.PI); // 3.14<br>console.log(matematicas.sumar(2, 3)); // 5</pre><h3><strong>¿Qué es una función de order superior (higher-order functions)?</strong></h3><ul><li><strong>Las funciones de orden superior</strong> son funciones que pueden aceptar otras funciones como argumentos o devolverlas.</li><li>Permiten escribir código más abstracto y reutilizable.</li><li>Ejemplos incluyen funciones que manipulan arrays y funciones que devuelven otras funciones. Array.prototype.map and filter are both higher-order functions.</li></ul><pre>function applyOperation(arr, operation) {<br>  return arr.map(operation);<br>}<br>const double = (n) =&gt; n * 2;<br>console.log(applyOperation([1, 2, 3], double)); // [2, 4, 6]</pre><h3><strong>¿Qué es el currying?</strong></h3><p><strong>Currying </strong>es una técnica en programación funcional que consiste en transformar una función que toma múltiples argumentos en una serie de funciones que toman un solo argumento cada una. Cada función devuelve otra función que recibe el siguiente argumento hasta que todos los argumentos han sido proporcionados.</p><h4>¿Cómo Funciona el Currying?</h4><p>El currying permite crear funciones más específicas a partir de funciones más generales. Esto es útil para crear funciones reutilizables y facilitar la creación de funciones con parámetros predefinidos.</p><h4>Ejemplo de Currying</h4><p>Veamos un ejemplo simple de currying en JavaScript.</p><pre>// Función normal que toma tres argumentos<br>function sumar(a, b, c) {<br>    return a + b + c;<br>}<br><br>// Función curried<br>function sumarCurried(a) {<br>    return function(b) {<br>        return function(c) {<br>            return a + b + c;<br>        };<br>    };<br>}<br><br>// Usando la función normal<br>console.log(sumar(1, 2, 3)); // Salida: 6<br><br>// Usando la función curried<br>const resultado = sumarCurried(1)(2)(3);<br>console.log(resultado); // Salida: 6</pre><h3>¿Que es la “memoization” en JS?</h3><p><strong>Memoization</strong> es una técnica de optimización que se utiliza para mejorar el rendimiento de funciones, especialmente aquellas que realizan cálculos costosos. Consiste en almacenar (o “cachear”) los resultados de las llamadas a funciones, de modo que si se vuelve a llamar a la misma función con los mismos argumentos, se puede devolver el resultado almacenado en lugar de volver a calcularlo.</p><h4>¿Cómo Funciona la Memoization?</h4><ol><li><strong>Almacenamiento de Resultados:</strong> Cada vez que se llama a la función, se verifica si el resultado para esos argumentos ya está almacenado en un objeto o estructura similar.</li><li><strong>Uso de Resultados Almacenados:</strong> Si el resultado ya está almacenado, se devuelve ese valor sin realizar el cálculo nuevamente.</li><li><strong>Cálculo y Almacenamiento: </strong>Si no está almacenado, se calcula el resultado, se almacena y luego se devuelve.</li></ol><h3>¿Cuales son las diferentes formas de crear objetos en Javascript?</h3><p>Existen 4 formas de crear objetos:</p><h4><strong>1- Con un constructor</strong></h4><p>El constructor no es más que una función y, con la ayuda de la palabra clave new, la función constructora permite la creación de varios objetos del mismo tipo, como se muestra a continuación:</p><pre>function Person(firstName, lastName, age) {<br>    this.firstName = firstName;<br>    this.lastName = lastName;<br>    this.age = age;<br><br>    this.greet = function() {<br>        return `Hello, my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`;<br>    };<br>}<br>var person1 = new Person(&quot;Cristian&quot;, &quot;Campos&quot;, 25);<br>// Hello, my name is Cristian Campos and I am 25 years old.</pre><h4>2- Usando objetos literales</h4><p>Los literales son formas más pequeñas y sencillas de definir objetos. Simplemente definimos la propiedad y los valores dentro de llaves {} como se muestra a continuación.</p><pre>var person = {<br>    fName: &quot;Cristian&quot;,<br>    lName: &quot;Campos&quot;,<br>    age: 25<br>};<br><br>console.log(person.fName) // Cristian<br>console.log(person[&#39;fName&#39;]) // Campos</pre><h4>3- Crear un objeto con el método Object.create()</h4><p>El método Object.create() crea un nuevo objeto, utilizando un objeto existente como prototipo del objeto recién creado.</p><pre>// Step 1: Define the Prototype Object<br>const animalPrototype = {<br>    speak: function() {<br>        return `${this.name} makes a sound.`;<br>    }<br>};<br><br>// Step 2: Create New Objects Using Object.create()<br>const dog = Object.create(animalPrototype, {<br>    name: { <br>        value: &#39;Buddy&#39;, <br>        writable: true, <br>        enumerable: true, <br>        configurable: true <br>    },<br>    breed: { <br>        value: &#39;Golden Retriever&#39;,<br>        writable: true, <br>        enumerable: true, <br>        configurable: true<br>    }<br>});<br><br>const cat = Object.create(animalPrototype, {<br>    name: { <br>        value: &#39;Whiskers&#39;, <br>        writable: true, <br>        enumerable: true, <br>        configurable: true <br>    },<br>    breed: { <br>        value: &#39;Siamese&#39;, <br>        writable: false, <br>        enumerable: true, <br>        configurable: true<br>    }<br>});<br><br>// Step 3: Access Inherited and Own Properties<br>console.log(dog.speak()); // Outputs: Buddy makes a sound.<br>console.log(dog.name);    // Outputs: Buddy<br>console.log(dog.breed);   // Outputs: Golden Retriever<br><br>console.log(cat.speak()); // Outputs: Whiskers makes a sound.<br>console.log(cat.name);    // Outputs: Whiskers<br>console.log(cat.breed);   // Outputs: Siamese<br><br>// Additional example of modifying properties if writable<br>dog.name = &#39;Max&#39;;<br>console.log(dog.name);    <br>// Outputs: Max (name changed because it&#39;s writable)<br><br>// Attempt to change the breed of the cat<br>cat.breed = &#39;Persian&#39;;<br>console.log(cat.breed);   <br>// Outputs: Siamese (breed not changed because it&#39;s not writable)</pre><h4>4- Usar clases es6</h4><p>El uso de clases ES6 en JavaScript proporciona una forma más estructurada y sintácticamente agradable de gestionar la creación y la herencia de objetos en comparación con el enfoque anterior basado en prototipos. Las clases ES6 agilizan el modelo de programación orientada a objetos basado en prototipos al introducir una sintaxis más simple para crear objetos y gestionar la herencia.</p><pre>class Employee extends Person {<br>    constructor(firstName, lastName, age, jobTitle) {<br>        super(firstName, lastName, age); // Calls the parent class constructor<br>        this.jobTitle = jobTitle;<br>    }<br><br>    describe() {<br>        return `${super.greet()} I work as a ${this.jobTitle}.`;<br>    }<br>}<br><br>const employee1 = new Employee(&quot;Jane&quot;, &quot;Smith&quot;, 28, &quot;Software Developer&quot;);<br><br>console.log(employee1.greet()); <br>// Outputs: Hello, my name is Jane Smith and I am 28 years old.<br><br>console.log(employee1.describe()); <br>// Outputs: Hello, my name is Jane Smith and I am 28 years old. <br>// I work as a Software Developer.</pre><h3>¿Cómo hacer “deep clone” de un objeto en JS?</h3><p>Un “deep clone” (o clon profundo) de un objeto en JavaScript significa crear una copia completa de ese objeto, incluyendo todos sus objetos anidados. A diferencia de un “shallow clone” (clon superficial), que solo copia el primer nivel de propiedades, un clon profundo asegura que todos los niveles de anidamiento también sean copiados.</p><h4>Métodos para Realizar un Deep Clone</h4><p>Aquí hay algunas formas comunes de realizar un clon profundo en JavaScript:</p><p><strong>1. Usando </strong><strong>JSON.stringify y </strong><strong>JSON.parse</strong></p><p>Este método es simple y funciona bien para objetos que solo contienen propiedades que pueden ser representadas en JSON (sin funciones, undefined, o tipos de datos especiales como Date).</p><pre>const objetoOriginal = {<br>    nombre: &#39;Juan&#39;,<br>    edad: 30,<br>    direccion: {<br>        ciudad: &#39;Madrid&#39;,<br>        pais: &#39;España&#39;<br>    }<br>};<br><br>const clonProfundo = JSON.parse(JSON.stringify(objetoOriginal));<br><br>console.log(clonProfundo);</pre><p><strong>2. Usando la Recursividad</strong></p><p>Puedes crear una función recursiva que copie cada propiedad del objeto original a un nuevo objeto.</p><pre>function deepClone(obj) {<br>    if (obj === null || typeof obj !== &#39;object&#39;) {<br>        return obj;<br>    }<br><br>    const clon = Array.isArray(obj) ? [] : {};<br><br>    for (const key in obj) {<br>        clon[key] = deepClone(obj[key]);<br>    }<br><br>    return clon;<br>}<br><br>const objetoOriginal = {<br>    nombre: &#39;Juan&#39;,<br>    edad: 30,<br>    direccion: {<br>        ciudad: &#39;Madrid&#39;,<br>        pais: &#39;España&#39;<br>    }<br>};<br><br>const clonProfundo = deepClone(objetoOriginal);<br><br>console.log(clonProfundo);</pre><p><strong>3. Usando </strong><strong>structuredClone</strong></p><p>A partir de ECMAScript 2021 (ES12), puedes usar la función structuredClone, que realiza un clon profundo de manera nativa y soporta muchos tipos de datos.</p><h3>¿Cómo funciona la herencia prototípica en JavaScript? (prototypal inheritance)</h3><p>La herencia prototípica en JavaScript es un mecanismo que permite a los objetos heredar propiedades y métodos de otros objetos. A diferencia de la herencia clásica que se encuentra en otros lenguajes de programación (como Java o C++), JavaScript utiliza un sistema de prototipos para implementar la herencia.</p><h4>Conceptos Clave</h4><ol><li><strong>Prototipo:</strong> Cada objeto en JavaScript tiene un objeto prototipo, que es otra referencia a un objeto del que puede heredar propiedades y métodos. Este prototipo se puede acceder a través de la propiedad interna [[Prototype]], que se puede consultar con Object.getPrototypeOf(objeto) o mediante __proto__ (aunque su uso directo no es recomendado).</li><li><strong>Cadena de Prototipos:</strong> Si un objeto no tiene una propiedad o método específico, JavaScript buscará en su prototipo. Si no lo encuentra allí, seguirá buscando en el prototipo del prototipo, y así sucesivamente, hasta llegar a null. Este proceso se denomina &quot;cadena de prototipos&quot;.</li></ol><p><strong>Ejemplo de Herencia Prototípica</strong></p><pre>// Definimos un objeto &quot;Animal&quot; con un método<br>const Animal = {<br>    hacerSonido: function() {<br>        console.log(&#39;El animal hace un sonido&#39;);<br>    }<br>};<br><br>// Creamos un objeto &quot;Perro&quot; que hereda de &quot;Animal&quot;<br>const Perro = Object.create(Animal);<br><br>// Añadimos una propiedad y un método específico a &quot;Perro&quot;<br>Perro.ladrar = function() {<br>    console.log(&#39;¡Guau!&#39;);<br>};<br><br>// Llamamos a los métodos<br>Perro.ladrar();        // ¡Guau!<br>Perro.hacerSonido();  // El animal hace un sonido</pre><h4>Herencia a través de Funciones Constructoras</h4><p>Puedes crear objetos utilizando funciones constructoras, lo que también permite establecer un prototipo.</p><pre>function Animal(nombre) {<br>    this.nombre = nombre;<br>}<br><br>Animal.prototype.hacerSonido = function() {<br>    console.log(`${this.nombre} hace un sonido`);<br>};<br><br>function Perro(nombre) {<br>    Animal.call(this, nombre); // Llama al constructor de Animal<br>}<br><br>// Establecemos el prototipo de Perro<br>Perro.prototype = Object.create(Animal.prototype);<br>Perro.prototype.constructor = Perro;<br><br>// Añadimos un método específico a Perro<br>Perro.prototype.ladrar = function() {<br>    console.log(&#39;¡Guau!&#39;);<br>};<br><br>const miPerro = new Perro(&#39;Rex&#39;);<br>miPerro.ladrar();        // ¡Guau!<br>miPerro.hacerSonido();  // Rex hace un sonido</pre><h4>Clases (ES6)</h4><p>Con la introducción de las clases en ECMAScript 2015 (ES6), la sintaxis para la herencia prototípica se simplificó, pero bajo el capó sigue usando el mismo mecanismo de prototipos.</p><pre>class Animal {<br>    constructor(nombre) {<br>        this.nombre = nombre;<br>    }<br><br>    hacerSonido() {<br>        console.log(`${this.nombre} hace un sonido`);<br>    }<br>}<br><br>class Perro extends Animal {<br>    ladrar() {<br>        console.log(&#39;¡Guau!&#39;);<br>    }<br>}<br><br>const miPerro = new Perro(&#39;Rex&#39;);<br>miPerro.ladrar();        // ¡Guau!<br>miPerro.hacerSonido();  // Rex hace un sonido</pre><h4>Ventajas de la Herencia Prototípica</h4><ul><li><strong>Reutilización de código:</strong> Permite compartir métodos y propiedades entre objetos, lo que reduce la duplicación de código.</li><li><strong>Flexibilidad:</strong> Puedes extender objetos en cualquier momento, lo que permite un diseño más dinámico.</li></ul><h4>Consideraciones</h4><ul><li><strong>Confusión sobre el origen de las propiedades:</strong> Puede ser complicado rastrear de dónde provienen ciertas propiedades y métodos en estructuras de herencia más complejas.</li><li><strong>Rendimiento: </strong>El uso excesivo de la cadena de prototipos puede afectar el rendimiento en aplicaciones grandes.</li></ul><p>En resumen, la herencia prototípica es un aspecto fundamental de JavaScript que permite la creación de objetos y la reutilización de código de manera eficiente.</p><h3>¿Qué es la delegación de eventos y por qué es útil?</h3><blockquote>La delegación de eventos implica asignar un único detector de eventos (event listener) a un ancestro común de varios elementos, lo que permite el manejo de eventos para todos sus descendientes. Esto optimiza el rendimiento y reduce la cantidad de detectores de eventos.</blockquote><p>La <strong>delegación de eventos</strong> es una técnica en JavaScript que permite manejar eventos en un elemento padre en lugar de asignar un controlador a cada elemento hijo.</p><h4>¿Cómo Funciona?</h4><p>Cuando un evento ocurre en un elemento hijo, este evento se “burbujea” hacia arriba hasta el elemento padre. Al agregar un detector de eventos al padre, puedes detectar eventos de todos los hijos sin necesidad de asignar un detector individual a cada uno.</p><pre>&lt;ul id=&quot;lista&quot;&gt;<br>    &lt;li&gt;Elemento 1&lt;/li&gt;<br>    &lt;li&gt;Elemento 2&lt;/li&gt;<br>    &lt;li&gt;Elemento 3&lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;script&gt;<br>    const lista = document.getElementById(&#39;lista&#39;);<br><br>    // Maneja el clic en el elemento padre<br>    lista.addEventListener(&#39;click&#39;, function(event) {<br>        // Verifica si se clicó en un &lt;li&gt;<br>        if (event.target.tagName === &#39;LI&#39;) {<br>            alert(`Hiciste clic en: ${event.target.textContent}`);<br>        }<br>    });<br>&lt;/script&gt;,</pre><h3>¿Qué es la desestructuración de objetos?</h3><p>La desestructuración de objetos es una función que permite extraer propiedades de los objetos y vincularlas a variables de una forma más concisa y legible. Simplifica el código cuando se trabaja con objetos complejos.</p><pre>const persona = {<br>    nombre: &#39;Juan&#39;,<br>    edad: 30,<br>    ciudad: &#39;Madrid&#39;<br>};<br><br>// Desestructuración<br>const { nombre, edad } = persona;<br><br>console.log(nombre); // Juan<br>console.log(edad);   // 30</pre><h3><strong>¿Qué es una función “callback”?</strong></h3><p>Una función “<em>callback</em>” es una función que se pasa como argumento a otra función, que luego se invoca dentro de la función externa. Los “<em>callbacks</em>” son fundamentales para la programación asincrónica y el manejo de eventos en JavaScript.</p><p>Las funciones callback son útiles en situaciones donde necesitas esperar a que se complete una tarea (como una solicitud de red o un temporizador) antes de ejecutar otra acción. Esto es especialmente común en programación asincrónica.</p><pre>function saludar(nombre, callback) {<br>    console.log(`Hola, ${nombre}!`);<br>    callback(); // Llama a la función de retorno<br>}<br><br>function despedir() {<br>    console.log(&#39;Adiós!&#39;);<br>}<br><br>// Pasamos la función despedir como callback<br>saludar(&#39;Juan&#39;, despedir);</pre><h3>¿Cuál es la diferencia entre la coerción implícita y la explícita?</h3><p>La coerción implícita ocurre cuando JavaScript convierte automáticamente un tipo de datos en otro, mientras que la coerción explícita implica convertir manualmente los tipos de datos mediante funciones como parseInto Number(). Comprender la coerción es fundamental para evitar comportamientos inesperados.</p><h4>Coerción Implícita</h4><ul><li><strong>Definición: </strong>Ocurre automáticamente cuando JavaScript convierte un tipo de dato en otro sin que el programador lo solicite.</li><li><strong>Ejemplo:</strong> Cuando sumas un número y una cadena, JavaScript convierte el número a una cadena y realiza la concatenación.</li></ul><pre>const resultado = 5 + &#39;5&#39;; // &quot;55&quot; (número 5 se convierte en cadena)<br>console.log(resultado); // &quot;55&quot;</pre><h4>Coerción Explícita</h4><ul><li><strong>Definición:</strong> Ocurre cuando el programador convierte un tipo de dato en otro de manera intencionada, utilizando funciones de conversión.</li><li><strong>Ejemplo:</strong> Usando Number() para convertir una cadena en un número.</li></ul><pre>const numero = Number(&#39;5&#39;); // 5 (cadena &quot;5&quot; se convierte en número)<br>console.log(numero); // 5</pre><h3>¿Cómo comprobar si una determinada propiedad existe en un objeto?</h3><p>Para comprobar si una determinada propiedad existe en un objeto, puede utilizar el método hasOwnPropertyo el operador in. Estos métodos garantizan una forma sólida de comprobar la existencia de propiedades en los objetos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a73d4f3f5c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entrevista React]]></title>
            <link>https://medium.com/@ccampos.aviles/entrevista-react-557f40829e77?source=rss-e09857a890c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/557f40829e77</guid>
            <dc:creator><![CDATA[Cristian Campos]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 17:54:39 GMT</pubDate>
            <atom:updated>2026-07-18T16:20:58.166Z</atom:updated>
            <content:encoded><![CDATA[<p>Preparación para entrevista, preguntas tomadas de diferentes fuentes.</p><p><strong>Tabla de contenidos:</strong></p><ul><li><a href="#65e0">¿Qué es el método del ciclo de vida de los componentes funcionales?</a></li><li><a href="#50a6">¿Qué es el hook useEffect ?</a></li><li><a href="#9a8b">¿Qué son los efectos secundarios?</a></li><li><a href="#1d36">¿Que es un hook en React? explica los tipos de hooks</a></li><li><a href="#8b80">¿Qué son los componentes HOC (higher-order components)?</a></li><li><a href="#f8c0">¿Qué es el DOM virtual?</a></li><li><a href="#a7a9">¿Cómo el VDOM mejora el rendimiento en comparación con la manipulación directa del DOM real?</a></li><li><a href="#77a5">¿Qué son los componentes controlados y los componentes no controlados?</a></li><li><a href="#5096">¿Qué son los componentes puros?</a></li><li><a href="#2cce">¿Qué es una función callback?</a></li><li><a href="#c75b">¿Cómo pasar datos de estado de un componente a otro componente?</a></li><li><a href="#1c7c">¿Qué es el “prop drilling” en React?</a></li><li><a href="#49bf">¿Qué son los controladores de eventos en React?</a></li><li><a href="#fd64">¿Qué son los eventos sinteticos en React?</a></li><li><a href="#4f3b">¿Qué es la renderización condicional en React?</a></li><li><a href="#3d42">¿Qué son las “refs” en React?</a></li><li><a href="#c77d">¿Qué es el estado en React?</a></li><li><a href="#5186">¿Cómo gestionar errores en aplicaciones React?</a></li><li><a href="#e5e3">¿Cual es la diferencia entre un componente funcional y un componente de clase?</a></li><li><a href="#5560">¿Qué es la “Context API”?</a></li><li><a href="#9025">¿Como optimizarías la performance en las aplicaciones con React?</a></li><li><a href="#5e41">¿Qué es “React Portals”?</a></li><li><a href="#ec59">¿Qué es “Server-side rendering” (SSR)?</a></li><li><a href="#a56f">¿Como implementas “server-side rendering” en React?</a></li><li><a href="#48cb">¿Qué es “ReactDOMServer”?</a></li><li><a href="#ac21">¿Cual es la diferencia entre `createElement` y `cloneElement`?</a></li><li><a href="#1970">¿Como implementarías la validación de formularios en React?</a></li><li><a href="#a5c0">¿Qué es un componente </a><a href="#a5c0">Suspense?</a></li></ul><h3>¿De que forma se manejan los ciclos de vida en los componentes funcionales?</h3><p>Los componentes de función reemplazan los métodos del ciclo de vida con Hooks:</p><ul><li><strong>Montaje:</strong> useEffect(() =&gt; {}, [])</li><li><strong>Actualización:</strong> useEffect(() =&gt; {}, [dependencias])</li><li><strong>Desmontaje:</strong> funcion limpieza -&gt;useEffect(() =&gt; { return () =&gt; {}; }, [])</li></ul><h3>¿Qué es el hook useEffect ?</h3><p>useEffect es un Hook de React que permite ejecutar efectos secundarios en componentes funcionales, como consumir APIs, manipular el DOM o suscribirse a eventos. Reemplaza el ciclo de vida de los componentes de clase.</p><p><strong>Casos de uso:</strong></p><ul><li><strong>Sin dependencias:</strong> se ejecuta después de cada render.</li><li><strong>Con </strong><strong>[]:</strong> se ejecuta solo al montar el componente.</li><li><strong>Con </strong><strong>[dependencias]:</strong> se ejecuta al montar y cuando cambia alguna dependencia.</li></ul><h3>¿Qué son los efectos secundarios?</h3><p>Efectos secundarios son acciones ejecutadas en un componente que no están relacionadas directamente a la renderización de la interfaz de usuario. Algunos efectos secundarios comunes incluyen la obtención de datos, la suscripción de eventos, la manipulación del DOM y la configuración de <em>timers</em>.</p><h3>¿Que es un hook en React? explica los tipos de hooks</h3><p>Un Hook es una función que permite usar el estado y otras características de React sin tener que escribir una clase.</p><h4>1. Hooks Básicos</h4><p>Estos son los hooks que vienen integrados en React:</p><ul><li>useState: Agrega y actualiza el estado local de un componente.</li></ul><pre>const [count, setCount] = useState(0);</pre><ul><li>useEffect: Ejecuta efectos secundarios, como llamadas a APIs, suscripciones o manipulación del DOM.</li></ul><pre>useEffect(() =&gt; {<br>  // Código a ejecutar<br>}, [dependencias]); // Las dependencias determinan cuándo se vuelve a ejecutar el efecto</pre><ul><li>useContext: Accede a datos compartidos mediante el Context API.</li></ul><pre>const value = useContext(MyContext);</pre><ul><li>useReducer: Es una alternativa a useState que permite manejar el estado de manera más compleja, similar a cómo se haría con un reducer en Redux.</li></ul><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><ul><li>useRef: Crea referencias al DOM o almacena valores persistentes sin provocar renderizados.</li></ul><pre>const inputRef = useRef(null);</pre><ul><li>useMemo: Memoriza el resultado de una función. recibe una función y un array de dependencias y retorna una valor memorizado . Es particularmente util cuando tienes cálculos costosos o que desear evitar repetir de forma innecesaria.</li></ul><pre>function ExpensiveCalculation({ a, b }) {<br>  const result = useMemo(() =&gt; {<br>    // Expensive computation<br>    return a * b;<br>  }, [a, b]); // Dependencies array</pre><pre>  return &lt;div&gt;Result: {result}&lt;/div&gt;;<br>}</pre><ul><li>useCallback : Memoriza funciones para evitar recrearlas en cada renderizado, lo cual es útil para pasar funciones a componentes hijos que dependen de referencias estables.</li></ul><pre>function ParentComponent() {<br>  const [count, setCount] = useState(0);</pre><pre>  const handleClick = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]); // Dependency array</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;ChildComponent handleClick={handleClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>function ChildComponent({ handleClick }) {<br>  return &lt;button onClick={handleClick}&gt;Increment&lt;/button&gt;;<br>}</pre><h4>2. Hooks Personalizados</h4><p>Los <strong>Hooks personalizados</strong> son funciones creadas por el desarrollador para reutilizar lógica de estado y efectos entre diferentes componentes, facilitando un código más limpio y reutilizable.</p><pre>import { useState, useEffect } from &#39;react&#39;;</pre><pre>function useCustomHook(initialValue) {<br>  const [value, setValue] = useState(initialValue);</pre><pre>  useEffect(() =&gt; {<br>    // Do something when value changes<br>    console.log(&#39;Value changed:&#39;, value);<br>  }, [value]);</pre><pre>  const handleChange = (newValue) =&gt; {<br>    setValue(newValue);<br>  };</pre><pre>  return { value, handleChange };<br>}</pre><pre>export default useCustomHook;</pre><p>Uso en componentes:</p><pre>import React from &#39;react&#39;;<br>import useCustomHook from &#39;./useCustomHook&#39;;</pre><pre>function MyComponent() {<br>  const { value, handleChange } = useCustomHook(&#39;&#39;);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;input <br>        type=&quot;text&quot; <br>        value={value} <br>        onChange={(e) =&gt; handleChange(e.target.value)} <br>      /&gt;<br>      &lt;p&gt;Value: {value}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default MyComponent;</pre><h3>¿Qué son los componentes HOC (higher-order components)?</h3><p>Un <strong>Higher-Order Component (HOC)</strong> es una función que recibe un componente y devuelve otro con funcionalidades adicionales, sin modificar el componente original.</p><h3>Casos de uso</h3><ul><li>Reutilizar lógica entre componentes.</li><li>Agregar o modificar <strong>props</strong>.</li><li>Controlar el renderizado de forma condicional.</li><li>Optimizar el rendimiento mediante memorización.</li><li>Compartir datos usando el <strong>Context API</strong>.</li><li>Extender la funcionalidad de bibliotecas de terceros.</li></ul><h3>¿Qué es el DOM virtual?</h3><p>El DOM virtual provee una abstracción del HTML DOM real. Es una copia o representación ligera del DOM real, guardada por React, que permite actualizaciones y renderizado eficiente de componentes.</p><h3>¿Cómo funciona el DOM virtual en React?</h3><p>Cuando cambia el estado o las props, React crea una nueva versión del DOM virtual, la compara con la anterior (<strong>reconciliation</strong>) y aplica únicamente los cambios necesarios al DOM real.</p><p>Esto permite reducir actualizaciones innecesarias y mejorar el rendimiento de las aplicaciones</p><h3>¿Cómo el VDOM mejora el rendimiento en comparación con la manipulación directa del DOM real?</h3><ul><li><strong>React agrupa varias actualizaciones</strong> antes de aplicarlas al DOM real, lo que reduce las repeticiones de renderizado innecesarias.</li><li><strong>Solo actualiza los componentes o elementos específicos que han cambiado</strong>, lo que minimiza las manipulaciones del DOM.</li><li>El eficiente algoritmo de comparación de React identifica el conjunto mínimo de cambios necesarios entre las representaciones del DOM virtual anterior y la nueva.</li><li>El proceso de conciliación de React optimiza las actualizaciones reutilizando los elementos del DOM existentes cuando es posible.</li></ul><h3>¿Qué son los componentes controlados y los componentes no controlados?</h3><p>En React, los componentes <strong>controlados</strong> y <strong>no controlados</strong> definen cómo se gestiona el estado de los formularios.</p><h4>Componentes controlados</h4><p>React controla el valor del componente mediante <strong>state y props</strong>. Los cambios se gestionan con eventos, proporcionando una única fuente de verdad.</p><p><strong>Ejemplos:</strong> inputs, checkbox y select.</p><h4>Componentes no controlados</h4><p>El estado lo administra directamente el <strong>DOM</strong>. React accede a los valores mediante referencias (ref) cuando es necesario.</p><p><strong>Ejemplos:</strong> inputs de archivos y formularios simples.</p><p><strong>En resumen:</strong></p><ul><li><strong>Controlados:</strong> React maneja el estado.</li><li><strong>No controlados:</strong> El DOM maneja el estado.</li></ul><h3>¿Qué son los componentes puros?</h3><p>Un <strong>componente puro</strong> en React es un componente que siempre devuelve el mismo resultado cuando recibe las mismas <strong>props</strong> y estado. No modifica datos externos ni produce efectos secundarios durante el renderizado.</p><p>Estos componentes solo se vuelven a renderizar cuando sus <strong>props o estado cambian</strong>, lo que ayuda a mejorar el rendimiento y facilita el mantenimiento del código.</p><p>Para optimizar componentes funcionales se puede utilizar React.memo, que memoriza el componente y realiza una comparación superficial de sus props para evitar renderizados innecesarios.</p><pre>import React from &quot;react&quot;;</pre><pre>const MyComponent = React.memo((props) =&gt; {<br>  return &lt;h1&gt;{props.title}&lt;/h1&gt;;<br>});</pre><pre>export default MyComponent;</pre><p><strong>En resumen:</strong> un componente puro debe ser predecible: mismas entradas → misma salida.</p><h3>¿Qué es una función callback?</h3><p>Una función callback es una función que es pasada como argumento a otra función, y su intención es ser llamada o ejecutada en algún momento posterior. <strong><em>Permite la comunicación entre diferentes componentes</em></strong> en React.</p><ul><li>Se utilizan como <strong>controladores de eventos</strong> para responder a las interacciones del usuario.</li><li>Permiten la <strong>comunicación</strong> entre los componentes padre e hijo.</li><li>Gestionan los resultados de <strong>operaciones asincrónicas</strong>.</li><li><strong>Renderización condicional</strong> de componentes o elementos.</li></ul><pre>import React from &#39;react&#39;;</pre><pre>const MyComponent = ({ onClick }) =&gt; {<br>  const handleClick = () =&gt; {<br>    // Execute the callback function passed as prop<br>    onClick(&#39;Button clicked!&#39;);<br>  };<br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>};<br>const App = () =&gt; {<br>  const handleButtonClick = (message) =&gt; {<br>    console.log(message);<br>  }; <br>  return &lt;MyComponent onClick={handleButtonClick} /&gt;;<br>};</pre><pre>export default App;</pre><h3>¿Cómo pasar datos de estado de un componente a otro componente?</h3><p>Existen varias formas de compartir estado entre componentes, según su relación.</p><h3>1. De padre a hijo (Props)</h3><p>El componente padre envía datos al hijo mediante <strong>props</strong>.</p><pre>&lt;ChildComponent data={data} /&gt;</pre><h3>2. De hijo a padre (Callback)</h3><p>El padre pasa una función al hijo y este la ejecuta para enviar información.</p><pre>&lt;ChildComponent onData={handleData} /&gt;</pre><h3>3. Entre hermanos (Lifting State Up)</h3><p>El estado se mueve al <strong>padre común</strong>, que lo comparte con ambos componentes.</p><pre>&lt;ChildA onData={setData} /&gt;<br>&lt;ChildB data={data} /&gt;</pre><h3>4. Con Context API</h3><p>Permite compartir datos entre múltiples componentes sin pasar props en cada nivel.</p><pre>const data = useContext(DataContext);</pre><h3>5. Con librerías de estado global</h3><p>Herramientas como <strong>Redux</strong>, <strong>Zustand</strong> o <strong>MobX</strong> permiten compartir y administrar el estado de toda la aplicación.</p><pre>const data = useSelector(state =&gt; state.data);</pre><h3>¿Qué es el “prop drilling” en React?</h3><p><strong><em>Prop Drilling</em></strong> es un término que se utiliza en React para describir el proceso de pasar datos de una parte de un árbol de componentes a otra parte pasando por otros componentes que no necesariamente necesitan los datos, sino que solo los pasan a través del árbol.</p><p>Para evitar el <strong><em>prop drilling</em></strong>, puedes usar la <strong>API de contexto</strong> de React o bibliotecas de administración de estado como <strong>Redux</strong>, que te permiten acceder al estado desde cualquier parte de tu árbol de componentes sin tener que pasarlo a través de cada nivel.</p><h3>¿Qué son los controladores de eventos en React?</h3><p>Los <strong>controladores de eventos</strong> son funciones que se ejecutan cuando ocurre una acción del usuario, como hacer clic en un botón, escribir en un campo o enviar un formulario.</p><p>En React, se asignan a los elementos mediante propiedades como onClick, onChange o onSubmit. Estas funciones pueden acceder al estado y a las props del componente, e incluso pasarse como props a componentes hijos.</p><pre>function Button() {<br>  const handleClick = () =&gt; {<br>    alert(&quot;¡Hiciste clic!&quot;);<br>  };<br><br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>}</pre><h3>¿Qué son los eventos sinteticos en React?</h3><p>Los <strong>eventos sintéticos (Synthetic Events)</strong> son un sistema de eventos creado por React que envuelve los eventos nativos del navegador para ofrecer una API uniforme y compatible en todos los navegadores.</p><p>Gracias a ellos, puedes manejar eventos como onClick, onChange o onSubmit de forma consistente, sin preocuparte por las diferencias entre navegadores.</p><pre>import React from &#39;react&#39;;<br><br>const MyButton = () =&gt; {<br>  const handleClick = (event) =&gt; {<br>    console.log(&#39;Button clicked:&#39;, event.type); // &#39;click&#39;<br>  };<br>  return (<br>    &lt;button onClick={handleClick}&gt;<br>      Click Me<br>    &lt;/button&gt;<br>  );<br>};<br>export default MyButton;</pre><p>En este ejemplo, el parámetro eventen handleClickes un evento sintético proporcionado por React.</p><h3>¿Qué es la renderización condicional en React?</h3><p>El renderizado condicional en React le permite <em>renderizar </em>diferentes elementos de la interfaz de usuario según ciertas condiciones. Esto se puede hacer mediante instrucciones if, operadores ternarios o el operador lógico &amp;&amp;.</p><h3>¿Cual es la diferencia entre componentes con estado y componentes sin estado? (stateful &amp; stateless)</h3><h4>Componentes con Estado</h4><ul><li><strong>Definición:</strong> Son componentes que gestionan su propio estado interno.</li><li><strong>Ejemplo:</strong> Un contador que incrementa su valor cuando haces clic en un botón.</li><li><strong>Uso:</strong> Se utilizan cuando necesitas que el componente cambie con el tiempo.</li></ul><pre>import React, { useState } from &#39;react&#39;;<br><br>const Contador = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Contador: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Incrementar&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>Componentes Sin Estado</h4><ul><li><strong>Definición:</strong> Son componentes que no tienen su propio estado. Solo reciben datos como props y los muestran.</li><li><strong>Ejemplo:</strong> Un saludo que muestra un nombre.</li><li><strong>Uso:</strong> Se utilizan para renderizar datos sin necesidad de gestionar cambios.</li></ul><pre>import React from &#39;react&#39;;<br><br>const Saludo = (props) =&gt; {<br>  return &lt;h1&gt;¡Hola, {props.name}!&lt;/h1&gt;;<br>};<br>// Uso<br>&lt;Saludo name=&quot;Alice&quot; /&gt;</pre><h3>¿Qué es la prop key en React?</h3><p><strong>Definición:</strong> La prop key es un atributo que se usa para identificar de manera única cada elemento en una lista de componentes en React.</p><h4>¿Por qué es importante?</h4><ol><li><strong>Identificación Única:</strong> Ayuda a React a saber qué elementos han cambiado, se han agregado o se han eliminado.</li><li><strong>Mejor Rendimiento:</strong> Al usar claves, React puede actualizar solo los elementos que han cambiado, en lugar de volver a renderizar toda la lista.</li><li><strong>Evita Errores:</strong> Sin claves únicas, React puede tener problemas al gestionar los elementos, lo que podría causar comportamientos inesperados.</li></ol><pre>import React from &#39;react&#39;;<br><br>const Lista = () =&gt; {<br>  const elementos = [&#39;Elemento 1&#39;, &#39;Elemento 2&#39;, &#39;Elemento 3&#39;];<br>  return (<br>    &lt;ul&gt;<br>      {elementos.map((elemento, index) =&gt; (<br>        &lt;li key={index}&gt;{elemento}&lt;/li&gt; // Se usa el índice como clave<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};</pre><h3>¿Qué son las “refs” en React?</h3><ul><li><strong>Definición:</strong> Son una forma de acceder directamente a elementos del DOM o instancias de componentes en React.</li><li><strong>Usos Comunes:</strong> Enfocar elementos, interactuar con bibliotecas de terceros, y almacenar valores sin provocar re-renders.</li><li><strong>Creación:</strong> Se pueden crear usando React.createRef() en componentes de clase o useRef() en componentes funcionales.</li></ul><h3>¿Qué es el estado en React?</h3><p>El estado (<em>la memoria de un componente</em>) es un objeto integrado de React que se utiliza para contener datos o información sobre el componente. El estado de un componente puede cambiar con el tiempo y, siempre que cambia, el componente se vuelve a renderizar.</p><ul><li>Puedes agregar estado a un componente con un <em>hook</em> useState</li><li>El hook useStatele permite <strong>declarar una variable de estado</strong>. Toma el estado inicial y devuelve un par de valores: el estado actual y una función de establecimiento de estado (<em>setter</em>) que le permite actualizarlo.</li></ul><h3>¿Cómo gestionar errores en aplicaciones React?</h3><ol><li><strong>Try/Catch en controladores de eventos:</strong> use bloques try/catch dentro de controladores de eventos para manejar excepciones que ocurren durante eventos.</li><li><strong>Estado de error en <em>hooks</em>:</strong> administre el estado de error usando el gancho useState y capture errores en operaciones asincrónicas dentro de useEffect.</li></ol><pre>function MyComponent() {<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        // Fetch data<br>      } catch (error) {<br>        setError(error);<br>      }<br>    };<br>    fetchData();<br>  }, []);<br>  if (error) {<br>    return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br>  }<br>  // Render component<br>}</pre><p><strong>3. PropTypes:</strong> valide los tipos de propiedades utilizando PropTypes para evitar errores relacionados con propiedades incorrectas.</p><pre>import PropTypes from &#39;prop-types&#39;;</pre><pre>function MyComponent({ name }) {<br>  // Component logic<br>}</pre><pre>MyComponent.propTypes = {<br>  name: PropTypes.string.isRequired,<br>};</pre><p><strong>4. Modo estricto:</strong> utilice el modo estricto de React en el desarrollo para identificar posibles problemas en los componentes.</p><pre>function App() {<br>  return (<br>    &lt;React.StrictMode&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/React.StrictMode&gt; <br>  );<br>}</pre><h3>¿Cual es la diferencia entre un componente funcional y un componente de clase?</h3><p>Los componentes funcionales son simplemente funciones de<em> JavaScript</em> que devuelven un archivo <em>JSX</em>. Los componentes de clase tienen más funciones, permiten el uso de los métodos del ciclo de vida y estados locales (antes de la introducción de <em>hooks</em>).</p><h3>¿Qué es la “Context API”?</h3><p><em>Context API </em>provee una forma de pasar datos a través del arbol de componentes sin tener que pasar <em>props</em> de forma manual en cada nivel. Esta diseñado para compartir datos que son considerados “globales” para el árbol de componentes de React.</p><h3>¿Como optimizarías la performance en las aplicaciones con React?</h3><p>Usando React.memo para componentes funcionales, componentes puros para componentes de clases, code-splitting, lazy loading, usar las keys de forma correcta en las listas, y evitando hacer re-redenders de forma innecesaria.</p><h3>¿Qué es “React Portals”?</h3><p>“Portals” provee una forma de renderizar hijos dentro de un nodo del DOM, que solo existe fuera de la jerarquía del DOM, en el componente padre. Son habitualmente usados para modales, tooltips, etc.</p><h3>¿Qué es “Server-side rendering” (SSR)?</h3><p><strong><em>SSR</em></strong> significa <strong><em>Server-Side Rendering</em></strong> (Renderizado del Lado del Servidor). Es una técnica utilizada en el desarrollo web en la que las páginas de un sitio se generan en el servidor y se envían al navegador como HTML completo, en lugar de que el navegador tenga que generar el HTML utilizando JavaScript.</p><h4>¿Cómo Funciona SSR?</h4><ol><li><strong>Solicitud del Usuario:</strong> Cuando un usuario solicita una página (por ejemplo, al escribir una URL o hacer clic en un enlace), esa solicitud se envía al servidor.</li><li><strong>Generación del HTML:</strong> El servidor ejecuta el código de la aplicación y genera el HTML necesario para esa página en particular.</li><li><strong>Respuesta al Navegador:</strong> El servidor envía el HTML generado al navegador del usuario, que lo muestra directamente.</li><li><strong>Hidratación:</strong> Después de que el HTML se carga en el navegador, se puede ejecutar JavaScript para hacer que la página sea interactiva, lo que se conoce como “<em>hidratación</em>”.</li></ol><h4>Ventajas de SSR</h4><ul><li><strong>Mejor SEO:</strong> Como el HTML completo se envía al navegador, los motores de búsqueda pueden indexar mejor el contenido de la página.</li><li><strong>Carga Inicial Rápida:</strong> Los usuarios ven el contenido más rápidamente, ya que no tienen que esperar a que se carguen todos los scripts y se renderice el contenido en el navegador.</li><li><strong>Accesibilidad:</strong> Las páginas son accesibles incluso si JavaScript no está habilitado en el navegador del usuario.</li></ul><h4>Desventajas de SSR</h4><ul><li><strong>Carga en el Servidor:</strong> Generar HTML en el servidor puede aumentar la carga en el servidor, especialmente con muchas solicitudes concurrentes.</li><li><strong>Tiempo de Respuesta: </strong>Puede haber un mayor tiempo de respuesta inicial en comparación con aplicaciones que se renderizan completamente en el cliente, especialmente en aplicaciones muy dinámicas.</li></ul><h3>¿Como implementas “server-side rendering” en React?</h3><p><strong><em>Server-side rendering</em></strong> puede ser implementado usando frameworks como Next.jso manualmente usando el método renderToString del módulo ReactDOMServer e hidratar la app en el cliente.</p><h3>¿Qué es “ReactDOMServer”?</h3><p>ReactDOMServer es un módulo de React que permite renderizar componentes de React en el lado del servidor. Esto significa que puedes generar HTML en el servidor y enviarlo al navegador, lo que mejora la velocidad de carga y la optimización para motores de búsqueda (SEO).</p><h3>¿Cual es la diferencia entre `createElement` y `cloneElement`?</h3><p>createElement es usado para crear nuevos elementos de React, mientras que cloneElement es usado para clonar y devolver un nuevo elemento de React usando uno existente como punto de partida.</p><h3>¿Como implementarías la validación de formularios en React?</h3><p>Puede ser implementada usando componentes controlados, donde se valide el input en el evento <em>onChange</em> y se guarde el estado de la validación. Librerias como <em>Formik</em> pueden se usadas para el caso de formularios complejos.</p><h3>¿Qué es un componente Suspense?</h3><p>Suspense es un componente de React que permite <strong>mostrar un contenido alternativo mientras se espera que una parte de la aplicación esté lista</strong>, como la carga de componentes de forma dinámica o datos.</p><p>Se utiliza principalmente con <strong>React.lazy</strong> para implementar <em>code splitting</em> y cargar componentes bajo demanda, mejorando el rendimiento inicial de la aplicación.</p><pre>import { Suspense, lazy } from &quot;react&quot;;</pre><pre>const Dashboard = lazy(() =&gt; import(&quot;./Dashboard&quot;));</pre><pre>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;p&gt;Cargando...&lt;/p&gt;}&gt;<br>      &lt;Dashboard /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p><strong>Funcionamiento:</strong></p><ul><li>lazy() carga el componente cuando es necesario.</li><li>Suspense muestra el contenido de fallback mientras espera.</li><li>Cuando la carga termina, React renderiza el componente real.</li></ul><p><strong>En resumen:</strong> Suspense permite manejar estados de espera mostrando una interfaz temporal mientras React carga contenido.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557f40829e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Angular Interview]]></title>
            <link>https://medium.com/@ccampos.aviles/angular-interview-cfde7f7599c2?source=rss-e09857a890c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfde7f7599c2</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Cristian Campos]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 14:45:03 GMT</pubDate>
            <atom:updated>2025-01-08T15:45:05.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Interview</h3><h3>Table of Contents</h3><ul><li><a href="#f54e">What is Angular?</a></li><li><a href="#ccef">What is angular CLI?</a></li><li><a href="#07e7">What is an Angular Component and how you create a new one?</a></li><li><a href="#67e1">What is the interpolation in Angular?</a></li><li><a href="#dfa7">What is an Angular Directive?</a></li><li><a href="#fd42">What is a pipe in Angular?</a></li><li><a href="#5ee7">Explain events on angular and give examples</a></li><li><a href="#0ba9">Explain component lifecycle in Angular</a></li><li><a href="#7d47">What is the purpose of `ngOnInit()`?</a></li><li><a href="#0c49">What is the difference between Constructor() and ngOnInit?</a></li><li><a href="#ad5b">How do components communicate in Angular?</a></li><li><a href="#5c8a">What is a module in Angular?</a></li><li><a href="#0c53">What is the difference between a component and a module?</a></li><li><a href="#f0b7">What is Angular Routing?</a></li><li><a href="#28f1">What is Lazy Loading in Angular?</a></li><li><a href="#ec58">What are services in Angular?</a></li><li><a href="#7883">What is Dependency Injection in Angular?</a></li><li><a href="#33e6">What is an Observable in Angular?</a></li><li><a href="#2cd7">What is the difference between Promise and observable?</a></li><li><a href="#1039">What is AOT compilation?</a></li><li><a href="#45fd">What is ng-content in Angular?</a></li><li><a href="#2944">What are Angular guards?</a></li><li><a href="#651a">What is the purpose of `forRoot()` and `forChild()` methods?</a></li><li><a href="#a135">What are Angular decorators?</a></li><li><a href="#549e">What is the difference between `ViewChild` and `ContentChild`?</a></li><li><a href="#8bdc">What is change detection in Angular?</a></li><li><a href="#f345">What is the purpose of `ngTemplateOutlet`?</a></li><li><a href="#6544">What is the difference between `@ViewChild()` and `@ViewChildren()`?</a></li><li><a href="#113d">What is Angular’s new control flow syntax?</a></li><li><a href="#2945">What is Angular’s defer loading feature?</a></li><li><a href="#2a88">What are signals in Angular and how do they differ from RxJS observables?</a></li><li><a href="#1a4f">What is a Behavior Subject in Angular?</a></li><li><a href="#af97">What is Reactive Programming?</a></li><li><a href="#b1ac">What is the purpose of `switchMap` operator in RxJS?</a></li><li><a href="#786c">What is the difference between `mergeMap` and `concatMap` in RxJS</a></li><li><a href="#9d7d">What is the purpose of `catchError` operator in RxJS?</a></li><li><a href="#0b1f">What is ngrx and why is it used in Angular?</a></li><li><a href="#ee1c">What are the key concepts of ngrx and how do they work?</a></li><li><a href="#a7ab">What are the benefits of using NgRx in large-scale applications?</a></li><li><a href="#d8a1">What is the purpose of the `createFeatureSelector` function in NgRx?</a></li><li><a href="#3702">How do you test NgRx reducers?</a></li><li><a href="#0ddc">What is the purpose of the `@ngrx/component-store` package?</a></li><li><a href="#1a22">Purpose of the createSelector Function in NgRx</a></li><li><a href="#8cd0">What is the purpose of the `async` pipe?</a></li></ul><p>Some Vanilla JS questions.</p><ul><li><a href="#b742">What’s the difference between == and === in JavaScript? When would you use each?</a></li><li><a href="#adf2">Explain this in JavaScript and give an example of how it can be used differently in different contexts</a></li><li><a href="#935b">How would you create a deep clone of an object in JavaScript?</a></li><li><a href="#baf2">What is the event loop in JavaScript? How does it handle asynchronous tasks?</a></li><li><a href="#129e">What is a debounce function, and when would you use it?</a></li><li><a href="#cfaa">How do JavaScript modules work? Can you explain import and export?</a></li><li><a href="#4baa">What are higher-order functions, and can you provide an example?</a></li><li><a href="#0c84">What is the difference between null and undefined? When should you use each?</a></li><li><a href="#b40c">Explain currying in JavaScript and give an example</a></li><li><a href="#411c">What is memoization, and how does it work in JavaScript?</a></li></ul><h3><strong>What is angular?</strong></h3><p>Its a front end framework developed and maintained by google. Is used to build Single page applications (SPA), libraries and progressive web apps (PWA).</p><h3>What is angular CLI?</h3><p>It’s a command line interface that is used to initialize, develop and maintain angular apps in a faster and efficient way. Its purpose is automate common develop tasks, like component creation, services, modules and the build and execution of the app.</p><h3>What is an Angular component and how you create a new one?</h3><p>A component in Angular <em>is a modular piece of the user interface</em>, that encapsulates the logic and the presentation of one specific part of an app. It is created using the command <strong><em>ng generate component</em></strong> followed by the name of the component. Example:</p><pre>ng generate component &lt;component-name&gt;</pre><h3><strong>What is the interpolation in Angular and how you use it in HTML templates?</strong></h3><p>Is a way to binding the data of the controler to the HTML. It is done using double curly braces `{{value}}`. For example, to show the value of a property `name` in the template of the component, it would be done like this: `{{name}}`.</p><h3><strong>What is an Angular directive?</strong></h3><p>An Angular directive is a class that can modify the structure or behavior of the DOM elements in Angular applications. Directives can be categorized into three types:</p><ol><li><strong>Component Directives:</strong> Directives that have a template and are used to create reusable components.</li><li><strong>Structural Directives:</strong> Directives that change the structure of the DOM by adding or removing elements (e.g., *ngIf, *ngFor).</li><li><strong>Attribute Directives:</strong> Directives that change the appearance or behavior of an existing element, component, or another directive.</li></ol><h3>What is a pipe in Angular?</h3><p>A pipe is a way to transform data in your template. It takes in data as input and transforms it to the desired output. For example:</p><pre>{{ birthday | date:’dd/MM/yyyy’ }}</pre><h3>Explain events on Angular and give examples</h3><p>Angular includes a powerful event handling system that enables to respond to user interactions, such as clicks, keyboard presses, and mouse movements. Here’s an overview of how events operate in Angular.</p><h4>1. Event Binding</h4><p>Event binding in Angular is done using the () syntax. You can bind an event to a method in your component class. When the event occurs, the method is called.</p><pre>&lt;button (click)=&quot;onClick()&quot;&gt;Click Me&lt;/button&gt;</pre><p>In this example, when the button is clicked, the onClick() method in the component class will be executed.</p><p>Component Class Example</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-example&#39;,<br>  templateUrl: &#39;./example.component.html&#39;<br>})<br>export class ExampleComponent {<br>  onClick() {<br>    console.log(&#39;Button clicked!&#39;);<br>  }<br>}</pre><h4>2. Listening to Events</h4><p>You can listen to various types of events, including:</p><ul><li>Mouse Events: click, dblclick, mouseenter, mouseleave, etc.</li><li>Keyboard Events: keydown, keyup, keypress, etc.</li><li>Focus Events: focus, blur</li><li>Touch Events: touchstart, touchend</li><li>Form Events: submit, input, change</li></ul><p><em>Example of Listening to Keyboard Events: in the html</em></p><pre>&lt;input (keydown)=&quot;onKeydown($event)&quot; /&gt;</pre><p><em>In the Component Class Example</em></p><pre>onKeydown(event: KeyboardEvent) {<br>  console.log(&#39;Key pressed:&#39;, event.key);<br>}</pre><h4>3. Passing Event Objects</h4><p>When binding to an event, you can pass the event object to your handler method. This object contains useful information about the event.</p><pre>&lt;button (click)=&quot;onClick($event)&quot;&gt;Click Me&lt;/button&gt;</pre><p><em>In the component class:</em></p><pre>onClick(event: MouseEvent) {<br>  console.log(&#39;Mouse coordinates:&#39;, event.clientX, event.clientY);<br>}</pre><h4>4. Event Modifiers</h4><p>Angular allows you to use event modifiers to alter the behavior of events. You can manage event propagation and default actions using the $event object.</p><p><em>Preventing Default Behavior</em></p><p>You can prevent the default action of an event by calling event.preventDefault().</p><p><em>html</em></p><pre>&lt;form (submit)=&quot;onSubmit($event)&quot;&gt;<br>  &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Component class</p><pre>onSubmit(event: Event) {<br>  event.preventDefault(); // Prevents form submission<br>  console.log(&#39;Form submitted!&#39;);<br>}</pre><h4>5. Template Reference Variables</h4><p>You can also use template reference variables to access DOM elements and their properties.</p><p><em>html</em></p><pre>&lt;input #myInput (keyup)=&quot;onKeyup(myInput.value)&quot; /&gt;</pre><p><em>Component class:</em></p><pre>onKeyup(value: string) {<br>  console.log(&#39;Input value:&#39;, value);<br>}</pre><h4>6. Custom Events</h4><p>You can create custom events within Angular components using EventEmitter. This is particularly useful when creating reusable components that need to communicate with their parent components.</p><p>Example: child component</p><pre>import { Component, EventEmitter, Output } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `&lt;button (click)=&quot;notifyParent()&quot;&gt;Notify Parent&lt;/button&gt;`<br>})<br>export class ChildComponent {<br>  @Output() notify = new EventEmitter&lt;string&gt;();<br><br>  notifyParent() {<br>    this.notify.emit(&#39;Hello Parent!&#39;);<br>  }<br>}</pre><p>Example: Parent component (will recieve the output event)</p><p><em>html:</em></p><pre>&lt;app-child (notify)=&quot;onNotify($event)&quot;&gt;&lt;/app-child&gt;</pre><p><em>Component class:</em></p><pre>onNotify(message: string) {<br>  console.log(&#39;Received from child:&#39;, message);<br>}</pre><h3>Explain component lifecycle in Angular:</h3><p>Each component has a lifecycle that consists of a series of stages from its creation to its destruction. The lifecycle hooks allow you to tap into specific moments of a component’s lifecycle and perform actions accordingly.</p><h4>Key Stages of the Component Lifecycle</h4><ol><li><strong>Creation: </strong>The component is initialized and created.</li><li><strong>Update:</strong> The component is updated in response to changes in data or inputs.</li><li><strong>Destruction:</strong> The component is removed from the view.</li></ol><h4>Lifecycle Hooks</h4><h4>1. ngOnInit()</h4><ul><li><strong><em>When It’s Called</em></strong>: After the component’s constructor, and right after the first ngOnChanges().</li><li><strong><em>Purpose:</em></strong> Initialize component properties, fetch data from services, etc.</li></ul><h4>2. ngOnChanges()</h4><ul><li><strong><em>When It’s Called:</em></strong> Whenever one or more input properties change.</li><li><strong><em>Purpose: </em></strong>Respond to changes in input properties.</li></ul><h4>3. ngDoCheck()</h4><ul><li><strong><em>When It’s Called:</em></strong> During every change detection run.</li><li><strong><em>Purpose:</em></strong> Implement custom change detection.</li></ul><h4>5. ngOnDestroy()</h4><ul><li><strong><em>When It’s Called:</em></strong> Just before the component is destroyed.</li><li><strong><em>Purpose:</em></strong> Cleanup logic, such as unsubscribing from observables or detaching event handlers.</li></ul><h4>Summary of Lifecycle Hooks</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da8492b933c494046353e74bce20336/href">https://medium.com/media/5da8492b933c494046353e74bce20336/href</a></iframe><h3>What is the purpose of `ngOnInit()`?</h3><p>ngOnInit is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. It’s used for any additional initialization tasks.</p><h3>What is the difference between Constructor() and ngOnInit?</h3><p>The Constructor() is called when the class is instantiated, while ngOnInit is called after the constructor and the bindings have been resolved.</p><h3>How do components communicate in Angular?</h3><p>Components in Angular can communicate in various ways:</p><ol><li><strong>Input and Output Properties:</strong> Parent to child and child to parent communication.</li><li><strong>ViewChild and ContentChild:</strong> Accessing child components directly.</li><li><strong>Service-Based Communication:</strong> Sharing data and events between unrelated components using a service</li><li><strong>State Management:</strong> NgRx can be used for managing application state and sharing data between components using a centralized store.</li></ol><h4>1. Input and Output Properties</h4><ul><li>Input Properties: Parent components can pass data to child components using @Input().</li><li>Output Properties: Child components can emit events to notify parent components using @Output() and EventEmitter.</li></ul><p><strong>Example:</strong><br><em>Parent Component</em></p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;h1&gt;Parent Component&lt;/h1&gt;<br>    &lt;app-child [childData]=&quot;data&quot; (notify)=&quot;onNotify($event)&quot;&gt;&lt;/app-child&gt;<br>  `<br>})<br>export class ParentComponent {<br>  data = &#39;Hello from Parent!&#39;;<br><br>  onNotify(message: string) {<br>    console.log(&#39;Received from child:&#39;, message);<br>  }<br>}</pre><p><em>Child Component:</em></p><pre>import { Component, Input, Output, EventEmitter } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `<br>    &lt;h2&gt;Child Component&lt;/h2&gt;<br>    &lt;p&gt;{{ childData }}&lt;/p&gt;<br>    &lt;button (click)=&quot;sendNotification()&quot;&gt;Notify Parent&lt;/button&gt;<br>  `<br>})<br>export class ChildComponent {<br>  @Input() childData: string;<br>  @Output() notify = new EventEmitter&lt;string&gt;();<br><br>  sendNotification() {<br>    this.notify.emit(&#39;Hello from Child!&#39;);<br>  }<br>}</pre><h4>2. ViewChild and ContentChild</h4><ul><li><strong><em>ViewChild:</em></strong> Allows a parent component to access a child component or directive in its template.</li><li><strong><em>ContentChild:</em></strong> Used to access a projected content element.</li></ul><p><strong>Example:</strong><br><em>Parent Component</em></p><pre>import { Component, ViewChild } from &#39;@angular/core&#39;;<br>import { ChildComponent } from &#39;./child.component&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;h1&gt;Parent Component&lt;/h1&gt;<br>    &lt;app-child&gt;&lt;/app-child&gt;<br>    &lt;button (click)=&quot;callChildMethod()&quot;&gt;Call Child Method&lt;/button&gt;<br>  `<br>})<br>export class ParentComponent {<br>  @ViewChild(ChildComponent) child: ChildComponent;<br><br>  callChildMethod() {<br>    this.child.someMethod(); // Access a method in the child component<br>  }<br>}</pre><h4>3. Service-Based Communication</h4><p><strong><em>Services</em></strong> can be used for communication between components that do not have a direct parent-child relationship. This is done using a shared service.</p><p><strong>Example:</strong><br><em>Shared Service:</em></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Subject } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class DataService {<br>  private messageSource = new Subject&lt;string&gt;();<br>  currentMessage$ = this.messageSource.asObservable();<br><br>  changeMessage(message: string) {<br>    this.messageSource.next(message);<br>  }<br>}</pre><p><em>Component A:</em></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-component-a&#39;,<br>  template: `&lt;button (click)=&quot;sendMessage()&quot;&gt;Send Message&lt;/button&gt;`<br>})<br>export class ComponentA {<br>  constructor(private dataService: DataService) {}<br><br>  sendMessage() {<br>    this.dataService.changeMessage(&#39;Hello from Component A&#39;);<br>  }<br>}</pre><p><em>Component B:</em></p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-component-b&#39;,<br>  template: `&lt;h2&gt;Message: {{ message }}&lt;/h2&gt;`<br>})<br>export class ComponentB implements OnInit {<br>  message: string;<br><br>  constructor(private dataService: DataService) {}<br><br>  ngOnInit() {<br>    this.dataService.currentMessage$.subscribe(msg =&gt; {<br>      this.message = msg;<br>    });<br>  }<br>}</pre><h3>What is a module in Angular?</h3><p>A module in Angular is a mechanism to group components, directives, pipes, and services that are related, in such a way that can be combined with other modules to create an application.</p><h4>Key Concepts of Angular Modules</h4><ol><li><strong><em>NgModule:</em></strong> The decorator used to define a module. It takes a metadata object that describes how to compile a component and launch the application.</li><li><strong><em>Declarations:</em></strong> An array where you declare the components, directives, and pipes that belong to the module.</li><li><strong><em>Imports: </em></strong>An array of other modules that are required for the functioning of the module. This allows you to use features from other modules.</li><li><strong><em>Exports:</em></strong> An array of components, directives, or pipes that can be used in the templates of other modules.</li><li><strong><em>Providers:</em></strong> An array of services that the module will provide to the components.</li><li><strong><em>Bootstrap: </em></strong>This is used only in the root module and defines the main component that gets bootstrapped when the application starts.</li></ol><p>Example of a module:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { MyComponent } from &#39;./my-component/my-component.component&#39;;<br><br>@NgModule({<br>  declarations: [<br>    MyComponent // Declare the component that belongs to this module<br>  ],<br>  imports: [<br>    CommonModule // Import necessary modules<br>  ],<br>  exports: [<br>    MyComponent // Export the component to make it available to other modules<br>  ]<br>})<br>export class MyModule { }</pre><h3>What is the difference between a component and a module?</h3><p>A component manages a specific section of the user interface (view), while a module serves as a container that groups related components, directives, pipes, and services together.</p><h3>What is Angular Routing?</h3><p>Angular routing is a feature that allows you to navigate between different views or components within a single-page application (SPA). It lets you define routes, which are paths that map to specific components. This enables users to move through different parts of your application without needing to reload the page, providing a seamless experience.</p><h4>Key Concepts of Angular Routing</h4><ol><li><strong><em>RouterModule:</em></strong> This module is responsible for configuring and managing the routes in an Angular application.</li><li><strong><em>Routes:</em></strong> An array of route objects that define path-component mappings.</li><li><strong><em>RouterOutlet:</em></strong> A directive that acts as a placeholder where the routed component will be displayed.</li><li><strong><em>RouterLink:</em></strong> A directive that allows you to create navigation links in your application.</li></ol><h4>How to use Angular Routing</h4><ol><li>Define some routes in a file, this could be the AppRoutingModule , and then import this file in the app main module:</li></ol><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { AboutComponent } from &#39;./about/about.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, component: HomeComponent }, // Default route<br>  { path: &#39;about&#39;, component: AboutComponent } // About page route<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>2. Add RouterOutlet</p><p>In your main application template (typically app.component.html), add the &lt;router-outlet&gt; directive. This is where the routed components will be displayed.</p><pre>&lt;nav&gt;<br>  &lt;a routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;<br>  &lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br>&lt;/nav&gt;<br><br>&lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;!-- This is where routed components will appear --&gt;</pre><p>3. Use RouterLink for Navigation</p><p>In your HTML, use the routerLink directive to create links for navigation.</p><pre>&lt;nav&gt;<br>  &lt;a routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;<br>  &lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br>&lt;/nav&gt;</pre><h3>What is Lazy Loading in Angular?</h3><blockquote><em>Lazy loading</em> is a <strong>design pattern</strong> used in Angular (and other frameworks) to improve the performance of an application by loading modules only when they are needed, rather than loading everything at the start. This means that if a user never navigates to a certain part of the application, the code for that part will not be loaded, reducing the initial loading time and the amount of data transferred.</blockquote><p>Lazy loading is a technique in Angular where you load JavaScript components asynchronously when a specific route is activated. This helps to decrease the startup time of an application.</p><h4>Why Use Lazy Loading?</h4><ol><li><strong><em>Performance Improvement:</em></strong> It reduces the initial load time of the application by splitting it into smaller chunks.</li><li><strong><em>Reduced Memory Usage:</em></strong> Only the necessary code is loaded into memory when needed, which can help with performance on low-end devices.</li><li><strong><em>Better User Experience:</em></strong> Users can interact with the application faster, as they won’t have to wait for all features to load at the beginning.</li></ol><h4>How to Implement Lazy Loading in Angular</h4><h4>1. Create a New Module</h4><p>You need to create a module that you want to lazy load. For example, let’s create a FeatureModule: ng generate module feature --route feature --module app.module</p><h4>2. Set Up Routes in the Feature Module</h4><p>In the newly created feature-routing.module.ts, you can define the routes for the feature module.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { FeatureComponent } from &#39;./feature.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, component: FeatureComponent } // Default route for the feature module<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forChild(routes)],<br>  exports: [RouterModule]<br>})<br>export class FeatureRoutingModule { }</pre><h4>3. Create the Feature Component</h4><p>You will need to create a component for the feature module: ng generate component feature/feature</p><h4>4. Configure Lazy Loading in the App Routing Module</h4><p>In your main routing configuration (usually found in app-routing.module.ts), set up the lazy loading route.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, redirectTo: &#39;/home&#39;, pathMatch: &#39;full&#39; },<br>  { path: &#39;home&#39;, component: HomeComponent },<br>  { path: &#39;feature&#39;, loadChildren: () =&gt; import(&#39;./feature/feature.module&#39;).then(m =&gt; m.FeatureModule) }, // Lazy loaded route<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><h4>How Lazy Loading Works in this example</h4><p>When a user navigates to the /feature route, Angular will load the FeatureModule and its associated components. Until that point, the code for the FeatureModule does not get loaded into the application, which improves the initial loading time.</p><h3>What are services in Angular?</h3><p>In Angular, services in Angular are a way to define reusable, encapsulated functionality that can be shared across components. They promote a clean architecture by separating business logic from UI logic. By using Angular’s dependency injection, you can easily inject services into components and other services as needed.</p><h4>Key Features of Services</h4><ol><li><strong><em>Reusable:</em></strong> Services are designed to be reusable across multiple components.</li><li><strong><em>Singleton:</em></strong> By default, Angular creates a single instance of a service for the entire application, making it easy to share data and functionality.</li><li><strong><em>Dependency Injection:</em></strong> Services can be injected into components or other services, allowing for a flexible architecture.</li></ol><h4>Defining a Service:</h4><p>Here’s an example that fetches a list of items:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;, // Makes the service available throughout the application<br>})<br>export class MyService {<br>  getItems() {<br>    return [&#39;Item 1&#39;, &#39;Item 2&#39;, &#39;Item 3&#39;]; // Example data<br>  }<br>}</pre><h4>Using a Service in a Component</h4><p>To use the service in a component, you need to inject it through the constructor.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { MyService } from &#39;./my-service.service&#39;; // Import the service<br><br>@Component({<br>  selector: &#39;app-my-component&#39;,<br>  template: `<br>    &lt;h2&gt;Items&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li *ngFor=&quot;let item of items&quot;&gt;{{ item }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>  `<br>})<br>export class MyComponent implements OnInit {<br>  items: string[];<br><br>  constructor(private myService: MyService) {} // Inject the service<br><br>  ngOnInit() {<br>    this.items = this.myService.getItems(); // Use the service to get data<br>  }<br>}</pre><h3>What is Dependency Injection in Angular?</h3><p>Dependency Injection (DI) is a design pattern used in Angular to manage how components and services receive their dependencies. Instead of creating dependencies (like services) directly within a component, DI allows Angular to provide those dependencies when the component is created. This promotes a more modular, testable, and maintainable code structure.</p><h4>Key Concepts of Dependency Injection</h4><ol><li><strong><em>Dependencies:</em></strong> These are the services or objects that a component needs to function.</li><li><strong><em>Injector:</em></strong> Angular uses an injector to create instances of services and pass them to components.</li><li><strong><em>Providers:</em></strong> A provider is a way to configure how a service or dependency is created. You can define providers in the module or at the component level.</li></ol><h4>How Dependency Injection Works</h4><p>Here’s a simple explanation of how DI works in Angular:</p><ol><li><strong><em>Creating a Service:</em></strong> You create a service that contains some functionality.</li><li><strong><em>Injecting the Service:</em></strong> You declare that a component needs this service by injecting it in the component’s constructor.</li><li><strong><em>Angular’s Injector:</em></strong> When the component is created, Angular’s injector provides the required service instance to the component.</li></ol><h4>Benefits of Dependency Injection</h4><ol><li><strong><em>Modularity:</em></strong> Components and services can be developed independently.</li><li><strong><em>Reusability:</em></strong> Services can be reused across multiple components.</li><li><strong><em>Testability:</em></strong> You can easily mock services in tests, making components easier to test.</li><li><strong><em>Maintainability:</em></strong> Changes to the services do not require changes to the components that use them.</li></ol><h3>What is an Observable in Angular?</h3><p>An Observable is a way to handle asynchronous data streams in Angular. It is part of the Reactive Programming paradigm and is provided by the RxJS library (Reactive Extensions for JavaScript). Observables help manage events, asynchronous operations, and data flows in a more efficient and flexible manner.</p><h4>Key Features of Observables</h4><ol><li><strong><em>Asynchronous:</em></strong> Observables allow you to work with data that arrives over time, such as HTTP responses, user input events, or timer events.</li><li><strong><em>Lazy:</em></strong> Observables do not execute until there is a subscription. This means that no data is emitted until you explicitly subscribe to it.</li><li><strong><em>Multiple Values:</em></strong> Observables can emit multiple values over time, unlike Promises, which only resolve once.</li><li><strong><em>Operators:</em></strong> RxJS provides a wide range of operators that can be used to transform, filter, and manage the data emitted by observables.</li></ol><h3>What is the difference between Promise and observable?</h3><p>In summary, while both Promise and Observable are used to handle asynchronous operations, they differ significantly in how they manage data streams, execution, cancellation, and error handling. Promises are best suited for single asynchronous events, whereas observables are more powerful for handling multiple values over time and provide a richer set of operators for data manipulation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74ef2cd910622a4b2ef6c8ab8de9210b/href">https://medium.com/media/74ef2cd910622a4b2ef6c8ab8de9210b/href</a></iframe><h3>What is AOT compilation?</h3><p>Ahead-of-Time (AOT) compilation converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase, before the browser downloads and runs that code.</p><h3>What is ng-content in Angular?</h3><p>ng-content is a directive in Angular used for content projection. It allows you to create a component that can accept content from its parent component and project that content into the child component&#39;s template. This is particularly useful for creating reusable components that can display different content based on the context in which they are used.</p><h3>What are Angular guards?</h3><p>Guards in Angular are interfaces which can tell the router whether or not it should allow navigation to a requested route. There are five different types of guards:</p><ul><li>CanActivate</li><li>CanActivateChild</li><li>CanDeactivate</li><li>Resolve</li><li>CanLoad</li></ul><h3>What is the purpose of `forRoot()` and `forChild()` methods?</h3><ul><li>`forRoot()` is used to configure the root module of the application. It’s typically used in the `AppModule`.</li><li>`forChild()` is used in feature modules to register providers without polluting the global injector.</li></ul><h3><strong>What are Angular decorators?</strong></h3><p><strong>Decorators are functions that modify JavaScript classes.</strong> Angular has many decorators that attach metadata to classes so that it knows what those classes mean and how they should work. Some examples are `<a href="http://twitter.com/Component">@Component</a>()`, `<a href="http://twitter.com/Injectable">@Injectable</a>()`, `<a href="http://twitter.com/Input">@Input</a>()`, etc.</p><h3>What is the difference between `ViewChild` and `ContentChild`?</h3><ul><li><strong>`ViewChild`</strong> gives access to elements in the component’s view (template).</li><li><strong>`ContentChild`</strong> gives access to elements that are projected into the component (via `ng-content`).</li></ul><h3>What is change detection in Angular?</h3><p>Change detection is the process that allows Angular to keep our views in sync with our models. It works by checking if the model values have changed after various events (like user events, timers, XHR, promises, etc.).</p><h3>What is the purpose of `TrackBy` in `ngFor` directive?</h3><p>`TrackBy` is used to track changes in the iterated array. It can improve performance by minimizing DOM operations when items are added or removed.</p><pre>&lt;li *ngFor=”let item of items; trackBy: trackByFn”&gt;{{item.name}}&lt;/li&gt;<br> trackByFn(index: number, item: any): number {<br> return item.id;<br> }</pre><h3>What is the purpose of `ngTemplateOutlet`?</h3><p>`ngTemplateOutlet` is used to insert a template in another template. It’s useful for creating reusable template parts.</p><h3>What is the difference between `@ViewChild()` and `@ViewChildren()`?</h3><ul><li>`<a href="http://twitter.com/ViewChild">@ViewChild</a>()` returns a single element.</li><li>`<a href="http://twitter.com/ViewChildren">@ViewChildren</a>()` returns multiple elements as a `QueryList`.</li></ul><h3>What is Angular’s new control flow syntax?</h3><p>Angular 17 introduced a new control flow syntax that replaces `*ngIf`, `*ngFor`, and `ngSwitch` with `@if`, `@for`, and `@switch`. This new syntax is more performant and easier to read.</p><pre>@if (condition) {<br> &lt;p&gt;Condition is true&lt;/p&gt;<br>} @else {<br> &lt;p&gt;Condition is false&lt;/p&gt;<br>}<br><br>@for (item of items; track item.id) {<br> &lt;li&gt;{{item.name}}&lt;/li&gt;<br>}<br><br>@switch (value) {<br> @case (&#39;A&#39;) { &lt;p&gt;A&lt;/p&gt; }<br> @case (&#39;B&#39;) { &lt;p&gt;B&lt;/p&gt; }<br> @default { &lt;p&gt;Other&lt;/p&gt; }<br>}</pre><h3>What is Angular’s defer loading feature?</h3><p>Defer loading is a new feature in Angular 17 that allows you to defer the loading of components or blocks of content until they are needed. This can significantly improve initial load times.</p><pre>@defer {<br>   &lt;heavy-component /&gt;<br>} @placeholder {<br>   &lt;p&gt;Loading…&lt;/p&gt;<br>}</pre><h3>What is Reactive Programming?</h3><p><strong><em>Reactive Programming</em></strong> is a programming paradigm<strong> focused on the</strong> <strong>asynchronous data streams and the propagation of changes</strong>. It allows you to work with data that changes over time, enabling you to react to those changes in a declarative and efficient way.</p><h4>Key Concepts of Reactive Programming</h4><ol><li><strong><em>Data Streams:</em></strong> In reactive programming, data is represented as streams, which can be anything that emits values over time, such as user inputs, sensor readings, or HTTP responses.</li><li><strong><em>Observables:</em></strong> These are the core building blocks in reactive programming. They represent a collection of future values or events, which can be observed and acted upon.</li><li><strong><em>Subscribers:</em></strong> These are the entities that listen to the data streams (observables) and react whenever new data is emitted.</li><li><strong><em>Operators:</em></strong> Reactive programming often includes a set of functions (operators) that allow you to transform, combine, filter, and manipulate the data streams in a functional way.</li></ol><h3>What is a Behavior Subject in Angular?</h3><p>A Behavior Subject is a type of observable provided by the RxJS library that allows you to maintain a current value and emit it to new subscribers. It is a specialized version of a Subject that requires an initial value and always emits the latest value to subscribers upon subscription.</p><h4>Key Features of Behavior Subject</h4><ul><li><strong><em>Initial Value:</em></strong> When you create a Behavior Subject, you must provide an initial value. This value is emitted immediately to any new subscribers.</li><li><strong><em>Latest Value: </em></strong>It holds the latest emitted value, allowing subscribers to receive the most recent update even if they subscribe later.</li><li><strong><em>Multicast:</em></strong> Like a Subject, a Behavior Subject is multicast, meaning that all subscribers share the same instance and receive the same emitted values.</li><li><strong><em>Can be Used in Services:</em></strong> Behavior Subjects are commonly used in Angular services to share data between components or manage state.</li></ul><h3>What are signals in Angular and how do they differ from RxJS observables?</h3><p>Signals are a new reactive primitive introduced in Angular 14. They are simpler than RxJS observables and are designed for representing values that change over time. Unlike observables, signals are always synchronous and don’t have a completion state.</p><pre>import { signal } from &#39;@angular/core&#39;;<br><br>export class MyComponent {<br> count = signal(0);<br> increment() {<br>   this.count.update(value =&gt; value + 1);<br> }<br>}</pre><h3>What is the purpose of `switchMap` operator in RxJS?</h3><p>The switchMap operator in RxJS is used to flatten an observable of observables into a single observable. It switches to a new inner observable every time a new value is emitted by the source observable. The previous inner observable is cancelled and any remaining values are discarded. This is useful in scenarios such as handling user input in real-time search, where you want to cancel the previous search request and start a new one whenever the user enters new input.</p><pre>import { switchMap } from ‘rxjs/operators’;<br><br>searchTerms$.pipe(<br> switchMap(term =&gt; this.searchService.search(term))<br>).subscribe(results =&gt; this.results = results);</pre><h3>What is the difference between `mergeMap` and `concatMap` in RxJS</h3><ul><li><strong>`mergeMap`</strong> subscribes to inner Observables concurrently.</li><li><strong>`concatMap`</strong> subscribes to inner Observables sequentially, waiting for each to complete before moving to the next.</li></ul><h3><strong>What is the purpose of `catchError` operator in RxJS?</strong></h3><p><strong><em>`catchError`</em></strong> is used to handle errors in an Observable stream. It catches errors on the source Observable, passing them to a function that returns a new Observable.</p><pre> import { catchError } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>this.http.get(&#39;api/data&#39;).pipe(<br> catchError(error =&gt; of([])) <br>).subscribe(data =&gt; this.data = data);</pre><h3>What is ngrx and why is it used in Angular?</h3><p><strong><em>ngrx</em></strong> is a state management library for Angular that uses the principles of <em>Redux</em>. It helps manage the state of an application by providing a single source of truth for the state and enforcing strict rules for state updates. This makes it easier to manage complex and large-scale applications.</p><h3>What are the key concepts of ngrx and how do they work?</h3><p>There are five key concepts in ngrx:</p><ul><li><strong><em>Actions:</em></strong> represent the facts about “something has happened” in the application, such as user interaction or data received from a server.<br> Actions are dispatched from components and services to signal state changes.</li><li><strong><em>Reducers:</em></strong> are pure functions that take the current state and an action, and return a new state. They specify how the state changes in response to actions.</li><li><strong><em>Store:</em></strong> is the central object that holds the current state and provides access to the state. It also allows dispatching actions to trigger state updates.</li><li><strong><em>Selectors</em></strong>: are pure functions that select slices of the state from the store and return them as observables. They can be used to derive new data from the state, for example to transform or filter data.</li><li><strong><em>Effects:</em></strong> are used to handle side effects in NgRx applications. They listen for dispatched actions and perform side effects, such as making HTTP requests.</li></ul><h3>What is the difference between merge and concat in RxJS?</h3><p>The merge operator in RxJS takes multiple streams and merges them into a single stream, emitting values from each of the streams as soon as they arrive. The concat operator also takes multiple streams, but it concatenates them into a single stream, emitting values from each stream one after the other, only starting with the next stream when the previous one completes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/facc65da550b9cd17912640e36ea6268/href">https://medium.com/media/facc65da550b9cd17912640e36ea6268/href</a></iframe><h3>What are the benefits of using NgRx in large-scale applications?</h3><ul><li>Centralized, immutable state management</li><li>Predictable state changes through pure functions</li><li>Powerful dev tools for time-travel debugging</li><li>Scalable architecture for managing complex state interactions</li><li>Clear separation of concerns</li><li>Improved testability</li></ul><h3>What is the purpose of the `createFeatureSelector` function in NgRx?</h3><p>createFeatureSelectoris a convenience function that returns a typed selector function for a feature slice of state.</p><pre>import { createFeatureSelector } from ‘@ngrx/store’;<br> export const selectFeature = createFeatureSelector&lt;FeatureState&gt;(‘feature’);</pre><h3>How do you test NgRx reducers?</h3><p>Reducers are pure functions, so they can be tested by providing an initial state and an action, and asserting on the returned state.</p><h4>Example of Testing a Reducer</h4><p><em>Let’s say we have a simple counter reducer that increments and decrements a counter based on specific actions.</em></p><p><em>Counter Reducer (counter.reducer.ts)</em></p><pre> import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { increment, decrement } from &#39;./counter.actions&#39;;<br><br>export const initialState = 0;<br><br>const _counterReducer = createReducer(<br>  initialState,<br>  on(increment, state =&gt; state + 1),<br>  on(decrement, state =&gt; state - 1)<br>);<br><br>export function counterReducer(state, action) {<br>  return _counterReducer(state, action);<br>}</pre><p><em>Testing the Counter Reducer (counter.reducer.spec.ts)</em></p><pre>import { counterReducer, initialState } from &#39;./counter.reducer&#39;;<br>import { increment, decrement } from &#39;./counter.actions&#39;;<br><br>describe(&#39;Counter Reducer&#39;, () =&gt; {<br>  it(&#39;should return the default state&#39;, () =&gt; {<br>    const action = {} as any; // No action provided<br>    const state = counterReducer(undefined, action);<br>    expect(state).toBe(initialState); // Expect the initial state<br>  });<br><br>  it(&#39;should increment the state&#39;, () =&gt; {<br>    const action = increment(); // Create the increment action<br>    const state = counterReducer(initialState, action);<br>    expect(state).toBe(1); // Expect the state to be incremented<br>  });<br><br>  it(&#39;should decrement the state&#39;, () =&gt; {<br>    const action = decrement(); // Create the decrement action<br>    const state = counterReducer(1, action); // Start from state 1<br>    expect(state).toBe(0); // Expect the state to be decremented<br>  });<br>});</pre><h3>What is the purpose of the `@ngrx/component-store` package?</h3><p><em>`</em><a href="http://twitter.com/ngrx/component-store"><em>@ngrx/component-store</em></a><em>`</em> is a standalone library for managing local component state. It’s useful for managing state that doesn’t need to be shared across the entire application.</p><h3>Purpose of the createSelector Function in NgRx</h3><p>The createSelector function in NgRx is a powerful utility used to create memoized selectors for selecting slices of state from the NgRx store. It allows you to define how to derive data from the state and provides a way to efficiently compute values based on the state.</p><h4>Key Features and Benefits</h4><ol><li><strong>Memoization:<br></strong>createSelector automatically caches the results of the selector function. If the input state doesn&#39;t change, it returns the cached result instead of recalculating it. This improves performance by avoiding unnecessary computations.</li></ol><p><strong>2. Combination:<br></strong>You can combine multiple selectors together to create more complex selectors. This allows you to build a hierarchy of selectors that can derive data from various parts of the state.</p><p><strong>3. Separation of Concerns:<br></strong>Using selectors helps to separate state selection logic from component logic, making your components cleaner and more focused on presentation.</p><p><strong>4. Reactivity:</strong><br>Selectors can be used with the select operator to create observables in your components, ensuring that the components automatically update when the selected state changes.</p><h3>What is the purpose of the `async` pipe?</h3><p>The <em>`async`</em> pipe is used to handle asynchronous data in templates. It allows you to subscribe to observables or promises directly in your Angular templates without the need for manual subscription and unsubscription, thus simplifying the process of working with asynchronous data.</p><h3>Key Features</h3><ol><li><strong>Automatic Subscription:</strong><br>The async pipe automatically subscribes to the observable or promise when the template is rendered. This means you don’t have to manage subscriptions manually in your component code.</li><li><strong>Automatic Unsubscription:</strong><br>When the component is destroyed, the async pipe automatically unsubscribes from the observable or promise, helping to prevent memory leaks.</li><li><strong>Value Extraction:</strong><br>The async pipe extracts the latest value emitted by the observable or resolved by the promise and makes it available for use in the template.</li><li><strong>Simplifies Code:</strong><br>Using the async pipe reduces boilerplate code in components, as it eliminates the need for separate subscription handling logic.</li></ol><p><strong>Example Scenario</strong><br>Let’s say you have an Angular service that fetches a list of users from an API and returns an observable.</p><p><em>User Service (user.service.ts):</em></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>@Injectable({<br> providedIn: &#39;root&#39;<br>})<br>export class UserService {<br>   constructor(private http: HttpClient) {}<br>   getUsers(): Observable&lt;User[]&gt; {<br>     return this.http.get&lt;User[]&gt;(&#39;https://api.example.com/users&#39;);<br>   }<br>}</pre><h4>Using the async Pipe in a Component</h4><p><em>User List Component (user-list.component.ts):</em></p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `<br>    &lt;h2&gt;User List&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li *ngFor=&quot;let user of users$ | async&quot;&gt;{{ user.name }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>  `<br>})<br>export class UserListComponent implements OnInit {<br>  users$: Observable&lt;User[]&gt;; // Define an observable property<br><br>  constructor(private userService: UserService) {}<br><br>  ngOnInit() {<br>    this.users$ = this.userService.getUsers(); // Assign observable<br>  }<br>}</pre><h3>What is Server-Side Rendering (SSR) in Angular 17?</h3><p>Refers to the process of rendering Angular applications on the server rather than in the browser. This technique generates HTML content on the server, which is then sent to the client. In Angular, SSR is primarily accomplished using Angular Universal.</p><h4>Key Benefits of SSR</h4><ul><li><strong>Improved Performance:</strong><br>SSR reduces the time it takes for the initial page to load, as the server sends a fully rendered page to the browser. This minimizes the time users have to wait before they see content on the screen.</li><li><strong>Better SEO:</strong><br>Search engines can index server-rendered pages more effectively, leading to better search engine optimization (SEO). This is particularly important for content-heavy applications where the visibility in search results is crucial.</li><li><strong>Faster Time to First Render:</strong><br>Users see the rendered HTML faster, as there’s no need to wait for JavaScript to load and execute to display content.</li></ul><h4>Here’s a simplified flow of how SSR works:</h4><ul><li><strong>Client Request:</strong><br>When a user requests a page, the server receives the request.</li><li><strong>Server Rendering:</strong><br>The server uses Angular Universal to render the requested page and generate HTML.</li><li><strong>Response:</strong><br>The server sends the rendered HTML to the client.</li><li><strong>Hydration:</strong><br>The client receives the HTML and Angular’s JavaScript bundles. Angular then takes over (or “hydrates”) the page, making it interactive.</li></ul><h3>What’s the difference between == and === in JavaScript? When would you use each?</h3><ul><li>== (loose equality) compares values for equality, allowing for type coercion, so 2 == &quot;2&quot; is true.</li><li>=== (strict equality) compares both value and type, so 2 === &quot;2&quot; is false.</li><li><strong>Use </strong><strong>===</strong> when exact type matching is required, which is preferred in most cases to avoid unexpected type coercion.</li></ul><h3>Explain `this` in JavaScript and give an example of how it can be used differently in different contexts.</h3><ul><li>In JavaScript, this refers to the context in which a function is called. For example:</li><li><strong>Global scope</strong>: this refers to the global object (e.g., window in browsers).</li><li><strong>Object method</strong>: this refers to the object that owns the method.</li><li><strong>Arrow functions</strong>: this is lexically scoped, meaning it inherits this from the outer function.</li></ul><pre>const obj = {<br>  name: &quot;The Expert Developer&quot;,<br>  getName: function() { return this.name; } // &#39;this&#39; refers to obj<br>};<br>console.log(obj.getName()); // &quot;The Expert Developer&quot;</pre><h3>How would you create a deep clone of an object in JavaScript?</h3><ul><li><strong>Shallow clone</strong>: Using Object.assign() or the spread operator ({ ...obj }), but it doesn’t clone nested objects.</li><li><strong>Deep clone</strong>: For a true deep clone, use JSON.parse(JSON.stringify(obj)) (may fail with functions, Dates, etc.) or libraries like Lodash’s cloneDeep.</li><li><strong>Example</strong>:</li></ul><pre> const obj = { a: { b: 1 } };<br>const deepClone = JSON.parse(JSON.stringify(obj));</pre><h3>What are JavaScript promises, and how do they work? Promise chaining vs. async/await?</h3><ul><li><strong>Promises</strong> are objects representing eventual completion (or failure) of asynchronous operations.</li><li><strong>Promise chaining</strong> uses .then() and .catch() to handle async operations sequentially.</li><li><strong>Async/await</strong> provides a more readable, synchronous way to handle asynchronous code.</li><li><strong>Example</strong>:</li></ul><pre>async function fetchData() {<br>  try {<br>    const response = await fetch(&#39;https://api.example.com/data&#39;);<br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><h3>What is the event loop in JavaScript? How does it handle asynchronous tasks?</h3><ul><li>The <strong>event loop</strong> is responsible for handling JavaScript’s single-threaded asynchronous behavior. It constantly checks the <strong>call stack</strong> and <strong>task queue</strong>.</li><li><strong>Asynchronous tasks</strong> (e.g., setTimeout, Promises) are queued in the <strong>task queue</strong> and wait until the call stack is empty before they execute.</li><li>This is how JavaScript achieves concurrency without multi-threading.</li></ul><h3>What is a debounce function, and when would you use it?</h3><ul><li><strong>Debounce</strong> limits the execution rate of a function. It ensures that a function is only called once after a specified delay.</li><li><strong>Use case</strong>: When you want to limit the rate of execution for event listeners, like resize or scroll.</li><li><strong>Example</strong>:</li></ul><pre>function debounce(func, delay) {<br>  let timeout;<br>  return function(...args) {<br>    clearTimeout(timeout);<br>    timeout = setTimeout(() =&gt; func.apply(this, args), delay);<br>  };<br>}</pre><h3>How do JavaScript modules work? Can you explain import and export?</h3><ul><li>JavaScript <strong>modules</strong> allow you to break up code into reusable, maintainable chunks.</li><li><strong>export</strong> is used to make variables, functions, or classes accessible to other modules.</li><li><strong>import</strong> is used to include these exports in other files.</li><li><strong>Example</strong>:</li></ul><pre>// module.js<br>export const greet = () =&gt; console.log(&#39;Hello&#39;);<br><br>// main.js<br>import { greet } from &#39;./module.js&#39;;<br>greet(); // Hello</pre><h3>What are higher-order functions, and can you provide an example?</h3><ul><li><strong>Higher-order functions</strong> are functions that take other functions as arguments or return them.</li><li><strong>Example</strong>: Array.prototype.map and filter are both higher-order functions.</li><li><strong>Custom example</strong>:</li></ul><pre>function applyOperation(arr, operation) {<br>  return arr.map(operation);<br>}<br>const double = (n) =&gt; n * 2;<br>console.log(applyOperation([1, 2, 3], double)); // [2, 4, 6]</pre><h3>What is the difference between null and undefined? When should you use each?</h3><ul><li><strong>null</strong> is an assignment value, representing the absence of value.</li><li><strong>undefined</strong> means a variable has been declared but not assigned.</li><li><strong>When to use</strong>: null is used intentionally to signify an empty value, while undefined often indicates an uninitialized state.</li></ul><h3>Explain currying in JavaScript and give an example.</h3><ul><li><strong>Currying</strong> is the process of breaking down a function that takes multiple arguments into a series of functions that take one argument at a time.</li><li><strong>Example</strong>:</li></ul><pre>function add(a) {<br>  return function(b) {<br>    return a + b;<br>  };<br>}<br>const addFive = add(5);<br>console.log(addFive(3)); // 8</pre><h3>What is memoization, and how does it work in JavaScript?</h3><ul><li><strong>Answer:</strong></li><li><strong>Memoization</strong> is a caching technique that stores function results for specific inputs, speeding up future calls with the same inputs.</li><li><strong>Example</strong>:</li></ul><pre> function memoize(fn) {<br>  const cache = {};<br>  return function(...args) {<br>    const key = JSON.stringify(args);<br>    if (cache[key]) return cache[key];<br>    const result = fn(...args);<br>    cache[key] = result;<br>    return result;<br>  };<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfde7f7599c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>