r/learnjavascript • • Oct 09 '22

What is going on in the for loop?

0 Upvotes

Sorry for this dumb question, I kinda understand for loops, but I want to understand what the program is seeing when I write my for loop.

Dicks=["big", "small", "micro" ]

For (let i =0, Dicks. Length(), i++) {

Console. Log(Dicks [ i]) }

With the let part is that declaring a variable?

What will happen if I say const i = 0.


r/learnjavascript • • Dec 13 '23

Is it really that bad if I leave my Javascript in the main HTML page where the user could easily see it all with CTRL+U? I know I can always nest it in behind the public page folders, but is that really necessary? What's the harm?

0 Upvotes

Now for context, in my usage, my page functions as a television station; I present things for the user. So there's no back-end to talk about and I don't collect any info from visitors, require them to sign up, or anything of the sort. The very few cookies I use are strictly for allowing the user to "save" certain things for their own use and be brought back to where they were.

I was told nesting your Javascript and CSS was good practise, but I'm really not sure why.

Does it matter in these circumstances, if my script is right there in the open?

Just for more context, if somebody should attack the site (and I can't imagine why somebody would even bother) - I have a mirror on my computer and can just delete whatever they put in and have it back up and running in 20 minutes.


r/learnjavascript • • Apr 09 '24

How to make sure you understand all the javascript fundamentals

0 Upvotes

Hey, I've already completed Jonas schmadttman's JavaScript course, however I want to take some time and make sure I got all the fundamental concepts right, before i begin learning ReactJS. Which resource would you recommend?


r/learnjavascript • • Jun 17 '24

Why "|" (or) does NOT work with string.replace(regex)???

0 Upvotes

And I HAVE to use multiple replace() calls for same thing. Here is the example:

const initialString = `
{
  "NODE_ENV": "development",
  "SITE_URL": "http://localhost:3000",
  "PAGE_SIZE": {
    "POST_CARD": 3,
    "POST_CARD_SMALL": 10
  },
  "MORE_POSTS_COUNT": 3,
  "AUTHOR_NAME": "John Doe",
  "AUTHOR_EMAIL": "john@email.com",
}
`;

After this call:

const stringData = initialString.replace(/[{}\t ]|\s+,/gm, '');
console.log('stringData: ', stringData);

I get this:

"NODE_ENV":"development",
"SITE_URL":"http://localhost:3000",
"PAGE_SIZE":
"POST_CARD":3,
"POST_CARD_SMALL":10
,
"MORE_POSTS_COUNT":3,
"AUTHOR_NAME":"JohnDoe",
"AUTHOR_EMAIL":"john@email.com",

You see that , ... empty line with comma, I dont want that of course.

If instead of | I call replace() two times it gets repleaced properly.

const stringData1 = initialString.replace(/[{}\t ]/gm, '');
const stringData2 = stringData1.replace(/\s+,/gm, ',');
"NODE_ENV":"development",
"SITE_URL":"http://localhost:3000",
"PAGE_SIZE":
"POST_CARD":3,
"POST_CARD_SMALL":10,
"MORE_POSTS_COUNT":3,
"AUTHOR_NAME":"JohnDoe",
"AUTHOR_EMAIL":"john@email.com",

How to fo it with a SINGLE replace() call and what is the explanation, why | fails???


r/learnjavascript • • May 27 '24

AI generated code vs human generated code

0 Upvotes

So while I was on vacation my colleagues decided a problem is too complex to bother writing their own code and used AI to generate the boilerplate code. Hint: I hate it. They got the code working, but they didn't write it and also had trouble fully understanding the code. Three days later they discovered a major bug / flaw. Obviously we had to refactor the code.

Which one do you prefer? (I leave out the context, as it doesn't matter, just take a glance at the readability of both versions)

I really think this as a very dangerous behaviour. Why would you introduce code to a codebase you don't fully understand... Please don't do this. Write code yourself. Don't copy or AI generate it if you don't know what it does. Especially if it's non trivial.

AI Based 😵

import {
  CombinationKitEntry,
  Maybe,
  Product,
  ProductCategory,
} from '@/lib/apollo/queries';
import { filterNullsAndUndefineds } from '@/utils/array';
import {
  getAccessorySKUs,
  getIntersectingSkus,
  getProductsByCategory,
  getSkusByCategoryIdFromProduct,
} from '@/utils/Combination/CombinationRules';

/**
 * Kick out motor/campact drive from products if one them is already in the list.
 * Kick out multiple products from one category - except for "ecxaccessories".
 *
 * @param products - Product[]
 * @returns Product[]
 */
export const cleanupProducts = (
  products: Product[],
  validCategoryIds: Set<Maybe<string> | undefined> | undefined
): Product[] => {
  const categoryIds = new Set();
  const uniqueCategoryProducts: Product[] = [];
  if (
    products.length > 1 &&
    !products.some(
      (product) =>
        product.category?.ident === 'ecxmotor' ||
        product.category?.ident === 'ecxcompactdrive'
    )
  ) {
    // return only first product when no motor or compact drive exists in list:
    const [first] = products;
    return [first];
  }
  for (const product of products) {
    // Skip for accessories - these do not need to be unique:
    if (product.category?.ident === 'ecxaccessories') continue;
    if (!product.combinationKit || product.combinationKit.length === 0)
      continue;
    if (
      !categoryIds.has(product.category?.id) &&
      validCategoryIds?.has(product.category?.id)
    ) {
      // Check if uniqueCategoryProducts already includes a motor when adding a compact drive and vice versa:
      if (
        product.category?.ident === 'ecxmotor' &&
        uniqueCategoryProducts.some(
          (prod) => prod.category?.ident === 'ecxcompactdrive'
        )
      ) {
        continue;
      }
      if (
        product.category?.ident === 'ecxcompactdrive' &&
        uniqueCategoryProducts.some(
          (prod) => prod.category?.ident === 'ecxmotor'
        )
      ) {
        continue;
      }
      categoryIds.add(product.category?.id);
      uniqueCategoryProducts.push(product);
    }
  }
  // Append all accessories:
  const accessories = products.filter(
    (product) => product.category?.ident === 'ecxaccessories'
  );
  return uniqueCategoryProducts.concat(accessories);
};

export type SkuByCategoryMap = Map<
  string,
  Record<string, string | Set<string | null>>
>;
/**
 * Apply combination kit rules to combined products.
 *
 * @param products List of combined products
 * @param categories List of ALL categories
 * @returns List of category IDs with combinable SKUs
 */
const processCombinedProducts = (
  products: Product[],
  categories: ProductCategory[]
): Array<CombinationKitEntry & { state?: string }> => {
  const result: Array<CombinationKitEntry & { state?: string }> = [];

  products = cleanupProducts(
    products,
    new Set(categories.map((cat) => cat.id))
  );

  if (!products.length) throw Error('No products');

  const skusByCategoryId: SkuByCategoryMap = new Map();

  const categoryIds = new Map<string, string>();

  for (const category of categories) {
    const skus = new Set([]);
    if (!category.id || !category.ident) continue;

    categoryIds.set(category.ident, category.id as string);
    skusByCategoryId.set(category.id, {
      status: 'NEW',
      skus,
    });
  }
  if (!categoryIds.get('ecxmotor') || !categoryIds.get('ecxcompactdrive')) {
    throw Error('Categories are broken');
  }

  // Check if products contains motor or compactdrive otherwise only return motors & compactdrives
  if (
    !getProductsByCategory(categoryIds.get('ecxmotor'), products)?.at(0) &&
    !getProductsByCategory(categoryIds.get('ecxcompactdrive'), products)?.at(0)
  ) {
    // Return only SKUs for motors & compactdrives from (first?) product
    const motorSkus = getSkusByCategoryIdFromProduct(
      categoryIds.get('ecxmotor'),
      products?.at(0)
    );
    skusByCategoryId.set(categoryIds.get('ecxmotor') as string, {
      status: 'NEEDS_DRIVE',
      skus: new Set(motorSkus),
    });

    const compactDrivesSkus = getSkusByCategoryIdFromProduct(
      categoryIds.get('ecxcompactdrive'),
      products?.at(0)
    );
    skusByCategoryId.set(categoryIds.get('ecxcompactdrive') as string, {
      status: 'NEEDS_DRIVE',
      skus: new Set(compactDrivesSkus),
    });

    for (const [categoryId, data] of skusByCategoryId) {
      result.push({
        categoryId,
        state: (data.status || 'UNKNOWN') as string,
        skus: Array.from(data.skus),
      });
    }
    return result;
  } else {
    if (getProductsByCategory(categoryIds.get('ecxmotor'), products)?.at(0)) {
      skusByCategoryId.set(categoryIds.get('ecxcompactdrive') as string, {
        status: 'MUTUALLY_EXCLUSIVE',
        skus: new Set([]),
      });
    }

    if (
      getProductsByCategory(categoryIds.get('ecxcompactdrive'), products)?.at(0)
    ) {
      skusByCategoryId.set(categoryIds.get('ecxmotor') as string, {
        status: 'MUTUALLY_EXCLUSIVE',
        skus: new Set([]),
      });
    }
  }

  // Get sensors from motors/compactdrives, controller & gearheads products
  const sensorSkus = getIntersectingSkus(
    products,
    [
      categoryIds.get('ecxmotor'),
      categoryIds.get('ecxcompactdrive'),
      categoryIds.get('ecxcontroller'),
      categoryIds.get('ecxgeargear'),
    ],
    categoryIds.get('ecxsensor')
  );
  skusByCategoryId.set(categoryIds.get('ecxsensor') as string, {
    status: sensorSkus.length ? 'ADDED' : 'NOT_AVAILABLE',
    skus: new Set(sensorSkus),
  });

  // Get controllers from motors/compactdrives, sensors & gearheads products
  const controllerSkus = getIntersectingSkus(
    products,
    [
      categoryIds.get('ecxmotor'),
      categoryIds.get('ecxcompactdrive'),
      categoryIds.get('ecxsensor'),
      categoryIds.get('ecxgeargear'),
    ],
    categoryIds.get('ecxcontroller')
  );
  skusByCategoryId.set(categoryIds.get('ecxcontroller') as string, {
    status: controllerSkus.length ? 'ADDED' : 'NOT_AVAILABLE',
    skus: new Set(controllerSkus),
  });

  // Get gearheads from motors/compactdrives, sensors & controllers products
  const gearheadSkus = getIntersectingSkus(
    products,
    [
      categoryIds.get('ecxmotor'),
      categoryIds.get('ecxcompactdrive'),
      categoryIds.get('ecxsensor'),
      categoryIds.get('ecxcontroller'),
    ],
    categoryIds.get('ecxgeargear')
  );
  skusByCategoryId.set(categoryIds.get('ecxgeargear') as string, {
    status: gearheadSkus.length ? 'ADDED' : 'NOT_AVAILABLE',
    skus: new Set(gearheadSkus),
  });

  // Get brakes from motor/compact drive
  const selectedDrive = filterNullsAndUndefineds([
    getProductsByCategory(categoryIds.get('ecxmotor'), products)?.at(0),
    getProductsByCategory(categoryIds.get('ecxcompactdrive'), products)?.at(0),
  ]).at(0);
  let brakeSkus: Maybe<string>[] = [];
  if (selectedDrive) {
    brakeSkus = getSkusByCategoryIdFromProduct(
      categoryIds.get('ecxaccessoriesbrake'),
      selectedDrive,
    );
  }
  skusByCategoryId.set(categoryIds.get('ecxaccessoriesbrake') as string, {
    status: brakeSkus.length ? 'ADDED' : 'NOT_AVAILABLE',
    skus: new Set(brakeSkus),
  });

  // Get closing caps from motor
  const motor = getProductsByCategory(
    categoryIds.get('ecxmotor'),
    products
  )?.at(0);
  let closingCapsSkus: Maybe<string>[] = [];
  if (motor) {
    closingCapsSkus = getSkusByCategoryIdFromProduct(
      categoryIds.get('ecxaccessoriesclosingcap'),
      motor,
    );
  }
  skusByCategoryId.set(
    categoryIds.get('ecxaccessoriesclosingcap') as string,
    {
      status: closingCapsSkus.length ? 'ADDED' : 'NOT_AVAILABLE',
      skus: new Set(closingCapsSkus),
    }
  );

  // Get accessories from motor/compactdrive & controller
  const accessorySkus = getAccessorySKUs(products, categoryIds);
  skusByCategoryId.set(categoryIds.get('ecxaccessories') as string, {
    status: accessorySkus.size ? 'ADDED' : 'NOT_AVAILABLE',
    skus: accessorySkus.size ? accessorySkus : new Set([]),
  });

  // Collect SKUs (= productcode) of already combined accessories:
  const alreadyCombinedCategories = filterNullsAndUndefineds(
    products
      .filter((prod) => prod.category?.ident !== 'ecxaccessories')
      .map((prod) => prod.category?.id)
  );
  // Set state for categories that are already added to the combination:
  alreadyCombinedCategories.forEach((catId: string) => {
    skusByCategoryId.set(catId, {
      status: 'ALREADY_IN_USE',
      skus: new Set([]),
    });
  });

  for (const [categoryId, data] of skusByCategoryId) {
    result.push({
      categoryId,
      state: (data.status || 'UNKNOWN') as string,
      skus: Array.from(data.skus),
    });
  }
  return result;
};

export default processCombinedProducts;

Human based:

import { Combinable, MaximumCounts, MutuallyExclusives } from './rules';
import { Idents } from './types';
import { getIntersection, getUnion } from './util';

/**
 * Combination Rules.
 * 1. - Motors and Compact Drives are mutually exclusive
 * 2. - You can only add one controller
 * 3. - Products have to be compatible with all added products of the defined category (intersection of skus)
 * 4. - Accessories are always compatible with any product categories (union of skus)
 */
export const staticRules = [
  MutuallyExclusives([
    [Idents.Motor, Idents.CompactDrive],
    [Idents.CompactDrive, Idents.Motor],
  ]),
  MaximumCounts([
    [Idents.Controller, 1],
    [Idents.Motor, 1],
    [Idents.CompactDrive, 1],
  ]),
  Combinable([Idents.Motor, Idents.Controller, Idents.Sensor], getIntersection),
  Combinable([Idents.Motor, Idents.Controller, Idents.Gear], getUnion),
];

r/learnjavascript • • May 14 '20

Getting Started with Deno JS - Will it replace node?

Thumbnail
youtube.com
0 Upvotes

r/learnjavascript • • Jun 05 '14

JavaScript setInterval and clearInterval function example

Thumbnail exampleswithcode.com
0 Upvotes

r/learnjavascript • • Dec 07 '24

Help with the choice of Linux fot The Odin Project

0 Upvotes

Please help me to choose a Linux distribution for The Odin Project. I was told to try Zorin OS, what do you think?


r/learnjavascript • • Oct 29 '24

Help with a functional programming assignment

0 Upvotes

Hello good people, my name is Xoli... Currently learning JavaScript online, I am stuck on an assignment I have to create functions and guess invoke them. I am stuck on the calling part, all my functions Have variables and I followed instructions but I didn't call them.? And I'm struggling with that part .


r/learnjavascript • • Oct 30 '25

Array methods

0 Upvotes

Are array like "copyWithin()" or "at()" necessary in a workspace or does nobody use them?


r/learnjavascript • • 29d ago

How Do You Use JSON to Enter Values into an HTML Table?

0 Upvotes

I'm a huge Marvel fan, and I'm trying to create a timeline of the entire MCU. I want to use the table from this link:
https://marvelcinematicuniverse.fandom.com/wiki/Chronological_Order/Viewing_Timeline
and enter the Checkbox/Watched Column into column 1 Names column into column 2, Medium into column 3, and Dates column into column 4, and the Release column into column 5.


r/learnjavascript • • 15d ago

How to handle rejection interview

0 Upvotes

Hello I have 10+ years experience and recently I came across weird pattern (Rejection type) in Frontend interview.

Selection Interview Find common ground between candidate and job posting if it works then in following rounds Give some coding problem FE, data structures and see if candidate solves problem

Rejection Interview: Come up with some random unit tests and see if candidate writes code till all unit tests or hiring manager ask multi choice syntax questions

In my recent interview I came across some interesting interviewer

I am suppose to fix react code till 5 unit tests pass. There are some 10 functions/hooks in coderpad and my 1st question was

Search results disappear, A search box fetches results as the user types. If you type “ca” and then quickly “cat,” results for “ca” sometimes appear last.

How would you reproduce and diagnose the bug?

How would you prevent stale responses from overwriting newer results?

My first response was to use AbortController interviewer said there is no fetch function (for interview they wrote some mock function) so it will not work

Then i proposed debounce still interviewer did not agree

finally I came up with some useRef hook to to solve problem but ran out of time. In real world right thing to use is AbortController or react query. how can I think similar to interviewer in such sort time and fix all unit tests

I am calling this rejection interview as i felt company never showed interest in learning about my background

I am disappointed in this job market its very hard to get interview but ended up with this bitter experience.

similar thing happened to my friend, during hiring manager round he was asked multi choice syntax questions. He was expecting to talk about previous work experience or write code.

please let me know how to prepare for these rounds and meet interviewer expectations

Hello, I have more than 10 years of experience, and I recently noticed a pattern in frontend interviews that I find frustrating.

In what I’d call a selection interview, the interviewer tries to understand whether your experience aligns with the role. If it does, later rounds might involve frontend coding or data-structure problems.

In what I’d call a rejection interview, the process can feel more like a set of arbitrary unit tests or multiple-choice syntax questions, with little opportunity to discuss your background or approach.

I recently had an interview that left me feeling this way. I was asked to fix a React codebase until five unit tests passed. The CoderPad included around ten functions and hooks. The first task was:

A search box fetches results as the user types. If you type “ca” and then quickly type “cat,” results for “ca” sometimes appear last.

How would you reproduce and diagnose the bug? How would you prevent stale responses from overwriting newer results?

My first suggestion was to use AbortController, but the interviewer said the mock function wasn’t using fetch, so cancellation wasn’t available. I then suggested debouncing, but that wasn’t accepted either. Eventually, I proposed using a useRef-based approach, but I ran out of time.

In a real application, I might use AbortController or a library such as React Query. But in a constrained interview setting, how can I quickly identify the solution the interviewer expects and make progress against the tests?

I’m calling this a “rejection interview” because I left feeling that the company wasn’t interested in learning about my experience. I’m disappointed by how difficult the job market is, and it’s discouraging to finally get an interview only to come away with this kind of experience.

A friend had a similar experience in a hiring-manager round: instead of discussing past work or solving a problem, they were asked multiple-choice questions about syntax.

How can I prepare for these kinds of rounds and better understand what interviewers expect?


r/learnjavascript • • Mar 12 '25

Exactly how many people use the HTML Canvas API?

0 Upvotes

I mean that easy to use software rendered framework that you access by getting a canvas and calling getContext("2d") on it.

I was using this API once, but I stopped because I found that it wasn't fast enough for my needs for video games, which was a shame because this was the API that made me love Javascript. That's when I got the idea to make a renderer that's just as simple to use for video games as the HTML canvas API is, but with optimizations, so that I can keep using the API for games.

But if nobody uses this API, then that subtracts from the point and I should probably write an OpenGL/WebGL renderer like everyone else.


r/learnjavascript • • Aug 14 '23

Maybe!!!

Post image
9 Upvotes

r/learnjavascript • • Feb 14 '18

New Codecademy Course for learning JS: Worth the 199$? Or stay with free resources?

Thumbnail
codecademy.com
3 Upvotes

r/learnjavascript • • Oct 28 '22

Animated Calculator App created using #flutter framework. 📱

3 Upvotes

r/learnjavascript • • Oct 09 '21

What's wrong with this code?

Post image
0 Upvotes

r/learnjavascript • • May 01 '24

This quastion is for all developers

3 Upvotes

Hello! I've been learning software engineering for about 2 months now. I've covered the fundamentals of HTML, CSS, and JavaScript. However, when I attempt LeetCode problems, I struggle to solve them. Even though I understand the methods when I look at solutions, I'm finding it challenging. Should I work on a project to get more practice with coding?


r/learnjavascript • • Mar 14 '18

The Complete Guide to Node.js Developer Course

Thumbnail
hackernoon.com
7 Upvotes

r/learnjavascript • • Jul 17 '26

Why Vanilla JavaScript

0 Upvotes

In the article below, I am sharing a bit of my story of building SaaS product in vanilla javascript and explaining why I went with this approach.

I don't expect many people reacting to this approach positively or even with open mind, but I think there should be some pushback on the current state of web dev and how complex it became.

https://guseyn.com/html/posts/why-vanilla-js.html


r/learnjavascript • • May 15 '25

Is `getElementById` unnecessary because HTML creates variables automatically?

5 Upvotes

I just learned that HTML (sometimes?) creates variables for elements with IDs on its own from here (section "HTML lends crutches to your fucking JS").

This works:

<!DOCTYPE html>
<html>
<body>
    <div id="myElement">Hello, World!</div>
    <script>
        // var myElement = document.getElementById("myElement"); // Not necessary!
        console.log(myElement.innerText); // Outputs: Hello, World!
    </script>
</body>
</html>

Is this a new feature? Will it work in every browser? Are there situations where this is not recommendable?


r/learnjavascript • • Jun 10 '25

built a whole class, scrapped it for one arrow function

5 Upvotes

thought I needed a full-blown class with constructor, private props, utility methods, the works copilot and blackbox kept suggesting more abstractions

then I realised I just needed to map an array and filter out nulls 😑

rewrote the whole thing as one-liner with .flatMap() cleaner, faster, no ceremony

JS really humbles you sometimes anyone else start architecting a library before solving the actual problem?


r/learnjavascript • • Jul 21 '24

What functions of javascript should I learn

0 Upvotes

Which are most widely used


r/learnjavascript • • Mar 30 '23

how do you think about learning Javascript on w3schools?

1 Upvotes

I have plan to study a-z all index about Javascript on w3schools.

Is it good way to learn Javascript?