FE Interview questions Flashcards
This
Hace referencia siempre a un objeto
El this en los arrow function
toma el valor del padre
Cambiar quien es this
bind, call y apply
bind dato interesante
bind nos devuelve una nueva función que podrá ser invocada en cualquier momento, mientras que call y apply se ejecutan sobre la misma función de manera instantanea.
Otro de los usos del bind, es para definir el valor de parámetros.


call y apply
Al igual que bind, nos permite cambiar el valor de this, pero se diferencian porque ejecuta la función.

//usamos el call, para cambiar el this y automáticamente se ejecuta
saludar.call(amigo);
//usamos apply, para cambiar el this y automáticamente se ejecuta
saludar.apply(amigo);
Diferencia entre call y apply
Como vemos arriba call y apply hacen lo mismo, la diferencia radica cuando tenemos parámetros extras en nuestra función, con call se envían por __, mientras que con apply, debemos enviar ___.
coma=call
apply=array
Closure
Funciones que recuerdan el entorno en el que se crearon, esto permite que las funciones internas(closures) tengan acceso a las variables de la función externa ya que están en el mismo scope.
Ejemplo de closures con la funcion prefijos
- Funcion prefijo, recibe prefijo por parametro
- Devuelve function con palabra de parametro
var addInPrefi = prefijos("In");
addInPrefi("creíble");

reduce
Es una función que se va a ejecutar para cada elemento del array y luego devolver un único valor conocido como acumulado.
- Usa reduce para sumar todo
let resultado,
numeros = [2,3,4];

Se ejecuta por cada elemento del array, y crea un nuevo array a partir del resultado de cada ejecución por elemento.
map
let numeros =[2,3,4];
devuelve un nuevo array con los dobles

Se ejecuta por cada elemento de array, y crea un nuevo array con los elementos que cumplen cierta condición.
filter
Saca un array nuevo con pares
let numeros =[2,3,4];

Qué es el Scope?
Cuando una línea de código está ejecutándose a que variables y funciones tengo acceso en ese momento.
La gente suele confundir, el scope con el ___, pero ___ se refiere al valor de this en determinado momento, mientras que scope se refiere a que variables y funciones tengo acceso.
contexto
Tipos de Scope
global, local y block
Global scope
Las variables y funciones están disponibles desde cualquier parte del código.
Local
Las variables y funciones están disponibles solo dentro de la función.
Global Scope
variable nombre, mostrarNombre(); colorFavorito();
block scope
entonces si declaramos variables dentro de if o for loops, estas pasan a ser del scope global o de la función, pero ya con ES6, podemos utilizar variables que solo sean para ese tipo de bloques.
Prototipos
un objeto hereda propiedades y métodos de un padre, entonces en Javascript la herencia funciona por prototipos
Prototype Chain(Cadena de prototipos)
Cada objeto tiene un prototipo, y este prototipo puede tener otro prototipo, así sucesivamente hasta encontrar a un prototipo que no tiene prototipo(el object Prototype).
Maneras de crear objetos en JS
- Objetos literales
- función contructora
- new Object()
- objeto literal con new object()
- Es6 class
Objetos Literales
Este tipo de objetos se definen dentro de brackets, se asignan sus propiedades por medio de clave y valor

Cuándo utilizar esta manera de definir objetos? la de object literal
Está manera se utiliza cuando se define una única instancia de un objeto, por ejemplo acá la instancia sería Luis, pero que hubiera pasado, si tuviera que crear a David, Kevin y Paolo?, para eso es mejor crear un constructor que se llame persona y así poder crear múltiples instancias.
Función constructora
Se crea una función la cual asigna sus propiedades con el this(haciendo referencia a la futura instancia del objeto), además puede recibir parametros para su inicialización.
Cuándo se utiliza la función constructora?
Se utiliza cuando quieres tener múltiples instancias de un objeto, se crea la función de la siguiente forma, y luego se crean las instancias.

New Object()
En esta forma se crea la instancia del objeto y luego se le asignan los valores.

Moviendo el método al prototipo
Lo que deberíamos hacer es sacar el método fuera de la función constructora, y luego asignarlo por medio de prototype.

___ is JavaScript’s default behavior of moving declarations to the top.
Hoisting is JavaScript’s default behavior of moving declarations to the top.
Value of X is:

x is not defined
value of x

undefined
Variables defined with let and const are hoisted to the top of the block, but not ___.
initialized
result of this


Why y is undefined?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.
Advices for hoisted
Declare Your Variables At the Top !
- To avoid bugs, always declare all variables at the beginning of every scope.
undefined== null
true
undefined=== null
false
undefined == “null”
false, acá null es un string
undefined== “undefined”
false
Can you name two programming paradigms important for JavaScript app developers?
javaScript is a multi-paradigm language, supporting imperative/proceduralprogramming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.
What is functional programming?
Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data.
Why use functional programming?
Avoid side-effects, simple function composition, pure functions
What is related Delegation in protoype
Delegation (i.e., the prototype chain).
What is two-way data binding ?
Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa.
What is one-way data binding ?
One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or “store” in React). Only the model has the access to change the app’s state. The effect is that data always flows in a single direction, which makes it easier to understand.
What is synchronous programming?
Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O.
What is asynchronous programming?
Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations.
Describe the difference between a cookie, sessionStorage and localStorage.
sesionStorage and localStorage has 5mb and cookies only 4k, and cookies has expiration time and are sending in each request in header, increasing traffic.
fetch
Fetch is a browser API for loading texts, images, structured data, asynchronously to update an HTML page.
Explain Ajax in as much detail as possible.
Asynchronous JavaScript And XML.
AJAX is a developer’s dream, because you can:Read data from a web server - after the page has loadedUpdate a web page without reloading the pageSend data to a web server - in the background
Diferencia entre async, defer

What are data- attributes good for?
The data-* attributes is used to store custom data private to the page or application.
Describe event bubbling.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Explain 3 phases of event propagation

Ver el tipo de algo en JS
typeof
Higher-Order function
, A Higher-Order function is a function that receives a function as an argument or returns the function as output.
first class functions
In JavaScript the functions are first class functions meaning we can store them in variable, objects and array.
what is REST
Representational State Transfer is a client-server communication architecture that creates a separation of concerns between data resources and user interfaces
Function definition
Several Ways(Declaration and Expression)
Function declaration
function foo() {
/* Warning: arguments.callee is deprecated.
Use with caution. Used here strictly for
illustration. */
return arguments.callee;
}
Function Expression
var bar = function () { return arguments.callee; };
If a function is used as an argument or return value, it’s a __
lambda
El hoisting guarda la inicialización?
JavaScript only hoists declarations, not initializations.
Explique cada parte del box model
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Como se calcula el width y height de un elemento
Total element width = width + left padding + right padding + left border + right border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
Elementos de tipo display block
- hr
- articles
- video
- header
- form
- section
Ejemplos de tipo display inline
a, b, img, br, button
span
select
input
Tipos de position
static
relative
fixed
absolute
Que es display inline block
inline-block elements are like inline elements but they can have a width and a height.
box-sizing
allows us to include the padding and border in an element’s total width and height.
Position Relative
Relativa de su posición normal
Tipos de position
static
relative
fixed
absolute
position: fixed;
Relativa con el viewport, siempre se mantiene en el mismo lugar aunque hagan scroll
position: absolute
Relativa con su padre.
Overflow
visible
hidden
scroll
auto
SOLO SIRVE CON ELEMENTOS TIPO BLOCK CON HEIGHT definido.
Explique que es display:block y inline
Block:
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
Inline
An inline element does not start on a new line and it only takes up as much width as necessary.