Javascript Flashcards
Implementing a function in JavaScript and call the function
function greet(name) {
console.log(Hello, ${name}!
);
}
// Call the function
greet(“Camila”); // Output: Hello, Camila!
how to console.log a value
console.log(Hello, ${name}!
);
how to put default parameters
function greet(name = “Guest”) {
console.log(Hello, ${name}!
);
}
how to call it with desired parameters?
greet(“Camila”); // Output: Hello, Camila!
mention 7 array methods ( do not need to explain )
map()
filter()
reduce()
forEach()
sort()
slice()
splice()
mention 4 strings methods ( do not need to explain )
split()
join()
substring()
slice()
mention 3 Object Methods
Object.keys()
Object.values()
Object.entries()
mention 5 loops
for Loop
while Loop
do…while Loop
for…of Loop
for…in Loop
steps to approach a new problem (4)
- declare a function, name it, call it
- send input as default params
- write in comment which is datatype of input/output
- console.log the desired return
- detect with data type is the input, think of avaiable methods/loops
diference de ! y !!
! (Logical NOT):
The ! operator negates a value. It first coerces the value into a boolean, and then it inverts
console.log(!0); // true (0 is falsy, so !0 is true)
console.log(!’hello’); // false (non-empty string is truthy, so !’hello’ is false)
!! (Double Logical NOT):
console.log(!!0); // false (0 is falsy, so !!0 is false)
console.log(!!’hello’); // true (non-empty string is truthy, so !!’hello’ is true)
diference de == y ===
==: Realiza comparación flexible con conversión de tipos implícita.
===: Realiza comparación estricta sin conversión de tipos, verificando tanto el valor como el tipo.
console.log(5 == ‘5’); // true (porque ‘5’ se convierte a número)
console.log(null == undefined); // true (considerados iguales en comparación débil)
console.log(0 == false); // true (0 y false son considerados iguales)
check if its an array
Array.isArray(cleanWord)
how to remove a space of letter with js?
let result = str.replace(/\s/g, ‘’); // Removes all spaces
let result = str.replace(/l/g, ‘’); // Removes all lowercase “l”
how to loop easy over an array?
arr.map((item, index) => {
if (item === target) { indexFounded = index; } })
.map() is meant for transforming arrays (i.e., creating a new array from the existing one).
why .map is not good idea to use it for a loop?
how to re do this? arr.map((item, index) => {
if (item === target) { indexFounded = index; } })
arr.forEach((item, index) => {
if (item === target) {
indexFounded = index;
}
});
why this is wrong? arr.length()
arr.length (length is a property, not a method).
sort Method, for arrays.
give an example to order: [1, 2, 5, 5, 6, 9]
orderArray.sort((a, b) => a - b);
how to order this manually?
without sort:
orderArray.sort((a, b) => a - b);
4 steps
we need a nested loop.
- we need a forEach item
arr.forEach(item => {
for each item in the array we need to see where to add it.
- for (let i = 0; i < orderArray.length; i++) {
} - inside the secound loop:
if (item < orderArray[i]) {
orderArray.splice(i, 0, item); // Insert at index i
inserted = true;
break;
}
if it dosent get in here then, we put it in the last place.
- if (!inserted) {
orderArray.push(item);
}
what method can i use for:
1.array
2.modify add, remove into an existing one
splice method is used to add, remove, or replace elements in an array. It modifies the original array in place and returns an array containing the removed elements
how to use splice just to add an item and avoid deleting.
splice(i, 0, item) Works Here
i:
This is the index where the item will be inserted in the orderArray.
0:
The deleteCount is 0, meaning no elements in the orderArray are removed. The array will just expand to accommodate the new item.
item:
This is the element being added to the orderArray.
why the function sortNamesByLength () was inserting double in the new array
function sortNamesByLength(arrNames = [“Alice”, “Bob”, “Charlie”, “David”]) {
//input is an array
//output new arrau sorred
let sortedPerLenght = [];
//add into new array
// if its smaller than other, then add it in the index of that. inserted it
arrNames.forEach((item) => {
let inserted = false;
for (let i = 0; i < sortedPerLenght.length; i++) { if (item.length < sortedPerLenght[i].length) { console.log(sortedPerLenght[i]) console.log(sortedPerLenght[i].length) sortedPerLenght.splice(i, 0, item); break; } } if (!inserted) { sortedPerLenght.push(item); } });
return sortedPerLenght;
}
console.log(sortNamesByLength());
You need to update inserted to true once the item is successfully inserted using splice().
in why the function sortNamesByLength () why a break is needed in:
for (let i = 0; i < sortedPerLenght.length; i++) {
if (item.length < sortedPerLenght[i].length) {
console.log(sortedPerLenght[i])
console.log(sortedPerLenght[i].length)
sortedPerLenght.splice(i, 0, item);
break;
}
}
Imagine an array sortedPerLenght = [3, 5, 8] and you want to insert 4. After comparing with 3:
You insert 4 between 3 and 5.
Continuing to check 4 against 5 or 8 doesn’t make sense because the array is already sorted, and 4 will always be smaller than 5 and 8.
what is the issue here: with index
arr.forEach((item, index) => {
for (let i=index; i < arr.length ; i++){ if (item + arr[i] === target ) { uniquePairsArray.push([item, arr[i]]); break; } } } ) console.log(uniquePairsArray); debugger return uniquePairsArray;
Inner loop: Starts from index + 1 to avoid pairing the element with itself.
The inner loop should not start at the same index as the outer loop, as that would lead to pairing a number with itself. Instead, you should ensure that the inner loop starts from the next index to avoid duplicates like [item, item].
in interview how to test 3 times your function…
we need 3 console.log and 3 params
why is not entering in the loop?
function findMaxInArr (arr= [1, 3, 7, 2]) {
let maxValue = null;
console.log(arr.length) for (let i; i < arr.length; i++) { if (arr[i] > maxValue || maxValue == null){ maxValue= arr[i] } } return maxValue; }
console.log(findMaxInArr());
The issue is that the variable i in your for loop is not initialized. In JavaScript, the syntax for a for loop requires initializing the loop variable.
why the secound index is wrong?
arr.forEach((item, index) => {
for (let i = index; i < arr.length; i++) {
console.log(item + arr[i] === target);
if (item + arr[i] === target) {
sumedNum = [item, arr[i]];
break;
}
}
});
return sumedNum;
Start Inner Loop at index + 1:
To avoid adding the same element to itself, the inner for loop starts at index + 1.
how to check if the num is divisible in js. with / or %.
num % 3 === 0 && num % 5 === 0.
The modulus operator gives the remainder of a division.
menor/igual en js
console.log(a <= b);
how to create a copy of two arreys into one!!! camila!
let oneSortedArray = […arr1, …arr2]
what to do if i want to map over and array and also modify it?
use a for! for (let index = 0; index < oneSortedArray.length; index++) {
DO NOT map over the array or FOREACH over it
como acceder a la 3er letra de un string usando un for
for (let i = 0; i < str.length ; i++){
newWord= str[i]+ newWord;
}
como chequear si hay una letra en un string? ejemplo letra a..
hay un metodo..
if (currentSub.includes(char)) {
currentSub = currentSub.slice(currentSub.indexOf(char) + 1);
}
can i use foreach with a string?
Strings don’t have a .forEach
you can use split(“”) to convert the string into an array of characters.
explica esto con palabras:
numList.forEach((num) => {
let inserted = false;
for (let i = 0; i < orderList.length; i++) { // Check if num should be inserted before orderList[i] if (num < orderList[i]) { // Insert num in the correct position orderList.splice(i, 0, num); inserted = true; break; } } // If num is greater than all elements, push it at the end if (!inserted) { orderList.push(num); } });
can i put a break in a forEach?
one key difference between forEach and a traditional for loop is that you cannot use the break statement inside forEach
const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
if (num === 3) {
break; // Breaks out of the loop
}
console.log(num);
}
what to use when mapping an array and using break (2 options)
for (const num of arr) {
if (num === 3) {
break; // Breaks out of the loop
}
console.log(num);
}
for (let i = 0; i < nums2.length; i++) { if (nums2[i] === item1) { duplicated = item1; break; } }
by using a stack. A stack is a data structure that follows the Last In, First Out (LIFO) principle
function isValid(s) {
// Stack to keep track of opening parentheses
let stack = [];
// Mapping of closing parentheses to opening parentheses
const map = {
‘)’: ‘(‘,
‘}’: ‘{‘,
‘]’: ‘[’
};
// Traverse each character in the string
for (let char of s) {
// If the character is a closing parenthesis
if (map[char]) {
// Pop the top of the stack, or set to a dummy value if the stack is empty
let topElement = stack.length === 0 ? ‘#’ : stack.pop();
// Check if the top element matches the corresponding opening parenthesis if (topElement !== map[char]) { return false; } } else { // If it's an opening parenthesis, push it to the stack stack.push(char); } }
// If the stack is empty, all parentheses were matched correctly
return stack.length === 0;
}
// Test cases
console.log(isValid(“()”)); // true
console.log(isValid(“()[]{}”)); // true
console.log(isValid(“(]”)); // false
console.log(isValid(“([)]”)); // false
console.log(isValid(“{[]}”)); // true
Arrays: methods
PUSH and UNSHIFT
responder:
-que hace
-mod original arr
-return
cuaderno
Arrays: methods
POP and SHIFT
responder:
-que hace
-mod original arr
-return
cuaderno
Arrays: methods
SPLICE
responder:
-que hace
-mod original arr
-return
cuaderno
Arrays: methods
CONCAT and SLICE
responder:
-que hace
-mod original arr
-return
cuaderno
Arrays: methods
arr.FOREACH vs MAP
responder:
-que hace
-mod original arr
-return
Arrays: methods
FILTER vs REDUCE
responder:
-que hace
-mod original arr
-return
Arrays: methods
SORT()
responder:
-que hace
-mod original arr
-return
Arrays: methods
INCLUDES vs INDEXOF
responder:
-que hace
-mod original arr
-return
Arrays: methods
JOIN vs TOSTRING() vs JSON.STRINSIFY
responder:
-que hace
-mod original arr
-return
Non-decreasing order meaning and how it affects algortims
Non-decreasing order means that the numbers in the array never decrease.
❌ Not non-decreasing:
[3, 2, 1] (it decreases)
`[1, 3, 2, 4
why is this wrong if(k => major)
if(k >= major)
what could be improve here?
if (prices[i]-prices[k] > maxProfit){
maxProfit= prices[i]-prices[k];
}
let profit = prices[k] - prices[i];
if (profit > maxProfit) {
maxProfit = profit;
}
why is important to check edge cases before starting the loops?
if (!strs.length) return “”;
optimization
can i break this kind of loops? for (let i = 0; i < nums.length; i++)
Yes, you can break out of a for loop like for (let i = 0; i < nums.length; i++) { using the break statement.
remove espacios y caracteres especiales
.replace(/[^a-z0-9]/g, ‘’)
how to do both: toLowerCase + replace
let cleanText = text.toLowerCase().replace(/[^a-z0-9]/g, ‘’);
NO SQL database.
Where data is store? not tables or columns
In collections and documents.
Ex collection is products
Ex collection is users
Each users is a DOCUMENT
Each product is a DOCUMENT
What is an API
application programming interface
meets in the middle
client (front- AKA BROWSER) –> get a resquest, arrives to API
–> needs a response from a server side (backend)
Allows back and front to connect!
What is wrong?
const st= “234”
const arr= st.split(“”);
arr.reduce((item) => item+item);
- arr
item is each element in the array (e.g., “2”, “3”, “4”). - The 0 at the end of reduce() is the initial value of the accumulator.
const st = “234”;
const arr = st.split(“”);
const sum = arr.reduce((acc, item) => acc + parseInt(item), 0);
console.log(sum); // Output: 9
How to check if its string or number?
if (typeof num === “number”) {
escribi una arrow function de una suma:
const suma = (a,b) => a+b;
ejemplo de Spread Operator (…)
const arr1 = [1, 2, 3];
const arr2 = […arr1, 4, 5]; // [1, 2, 3, 4, 5]
ejemplo de Desestructuración
onst persona = { nombre: ‘Juan’, edad: 30 };
const persona = { nombre: ‘Juan’, edad: 30 };
const { nombre, edad } = persona;
hace una Promesas y Async/Await
debe contener una respuesta con fetch
datos
return de datos
const obtenerDatos =
const obtenerDatos = async () => {
const respuesta = await fetch(‘url’);
const datos = await respuesta.json();
return datos;
};
why doing arr.reverse? could be wrong and make many mistakes?
let reverseArr= […arr].reverse();
DOES NOT CREATE COPY, MODIFIES ORIGINAL