Javascript Flashcards

(64 cards)

1
Q

Implementing a function in JavaScript and call the function

A

function greet(name) {
console.log(Hello, ${name}!);
}

// Call the function
greet(“Camila”); // Output: Hello, Camila!

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

how to console.log a value

A

console.log(Hello, ${name}!);

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

how to put default parameters

A

function greet(name = “Guest”) {
console.log(Hello, ${name}!);
}

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

how to call it with desired parameters?

A

greet(“Camila”); // Output: Hello, Camila!

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

mention 7 array methods ( do not need to explain )

A

map()
filter()
reduce()
forEach()
sort()
slice()
splice()

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

mention 4 strings methods ( do not need to explain )

A

split()
join()
substring()
slice()

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

mention 3 Object Methods

A

Object.keys()
Object.values()
Object.entries()

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

mention 5 loops

A

for Loop
while Loop
do…while Loop
for…of Loop
for…in Loop

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

steps to approach a new problem (4)

A
  1. declare a function, name it, call it
  2. send input as default params
  3. write in comment which is datatype of input/output
  4. console.log the desired return
  5. detect with data type is the input, think of avaiable methods/loops
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

diference de ! y !!

A

! (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)

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

diference de == y ===

A

==: 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)

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

check if its an array

A

Array.isArray(cleanWord)

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

how to remove a space of letter with js?

A

let result = str.replace(/\s/g, ‘’); // Removes all spaces

let result = str.replace(/l/g, ‘’); // Removes all lowercase “l”

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

how to loop easy over an array?

A

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).

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

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;
    }
})
A

arr.forEach((item, index) => {
if (item === target) {
indexFounded = index;
}
});

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

why this is wrong? arr.length()

A

arr.length (length is a property, not a method).

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

sort Method, for arrays.
give an example to order: [1, 2, 5, 5, 6, 9]

A

orderArray.sort((a, b) => a - b);

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

how to order this manually?
without sort:
orderArray.sort((a, b) => a - b);

4 steps

A

we need a nested loop.

  1. we need a forEach item
    arr.forEach(item => {

for each item in the array we need to see where to add it.

  1. for (let i = 0; i < orderArray.length; i++) {
    }
  2. 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.

  1. if (!inserted) {
    orderArray.push(item);
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

what method can i use for:
1.array
2.modify add, remove into an existing one

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

how to use splice just to add an item and avoid deleting.

A

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.

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

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());

A

You need to update inserted to true once the item is successfully inserted using splice().

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

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;
}
}

A

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.

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

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;
A

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].

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

in interview how to test 3 times your function…

A

we need 3 console.log and 3 params

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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.
26
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.
27
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.
28
menor/igual en js
console.log(a <= b);
29
how to create a copy of two arreys into one!!! camila!
let oneSortedArray = [...arr1, ...arr2]
30
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
31
como acceder a la 3er letra de un string usando un for
for (let i = 0; i < str.length ; i++){ newWord= str[i]+ newWord; }
32
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); }
33
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.
34
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); } });
35
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); }
36
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; } }
37
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
38
Arrays: methods PUSH and UNSHIFT responder: -que hace -mod original arr -return
cuaderno
39
Arrays: methods POP and SHIFT responder: -que hace -mod original arr -return
cuaderno
40
Arrays: methods SPLICE responder: -que hace -mod original arr -return
cuaderno
41
Arrays: methods CONCAT and SLICE responder: -que hace -mod original arr -return
cuaderno
42
Arrays: methods arr.FOREACH vs MAP responder: -que hace -mod original arr -return
43
Arrays: methods FILTER vs REDUCE responder: -que hace -mod original arr -return
44
Arrays: methods SORT() responder: -que hace -mod original arr -return
45
Arrays: methods INCLUDES vs INDEXOF responder: -que hace -mod original arr -return
46
Arrays: methods JOIN vs TOSTRING() vs JSON.STRINSIFY responder: -que hace -mod original arr -return
47
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
48
why is this wrong if(k => major)
if(k >= major)
49
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; }
50
why is important to check edge cases before starting the loops? if (!strs.length) return "";
optimization
51
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.
52
remove espacios y caracteres especiales
.replace(/[^a-z0-9]/g, '')
53
how to do both: toLowerCase + replace
let cleanText = text.toLowerCase().replace(/[^a-z0-9]/g, '');
54
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
55
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!
56
What is wrong? const st= "234" const arr= st.split(""); arr.reduce((item) => item+item);
1. arr item is each element in the array (e.g., "2", "3", "4"). 2. 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
57
How to check if its string or number?
if (typeof num === "number") {
58
escribi una arrow function de una suma:
const suma = (a,b) => a+b;
59
ejemplo de Spread Operator (...) const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
60
ejemplo de Desestructuración onst persona = { nombre: 'Juan', edad: 30 };
const persona = { nombre: 'Juan', edad: 30 }; const { nombre, edad } = persona;
61
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; };
62
why doing arr.reverse? could be wrong and make many mistakes?
let reverseArr= [...arr].reverse(); DOES NOT CREATE COPY, MODIFIES ORIGINAL
63
how to sort and array[i] where a string lays? .sort() is not enoght grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv']
grid[i] = grid[i].split('').sort().join('');
64
var removeElement = function(nums, val) { for (let i=0; i < nums.length; i++){ if (nums[i] === val){ nums.splice(i, 1); } } }; ERROR! HUGE
When you remove an element with splice(i, 1), all the elements after index i shift left by one. But your loop still moves on to the next index (i++), which causes you to skip one element. var removeElement = function(nums, val) { for (let i=0; i < nums.length; i++){ if (nums[i] === val){ nums.splice(i, 1); //remove an element i--; } }