/r/learnjavascript

Photograph via snooOG

This subreddit is for anyone who wants to learn JavaScript or help others do so.

Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend.

This subreddit is a place for people to learn JavaScript together. Everyone should feel comfortable asking any and all JavaScript questions they have here.

With a nod to practicality, questions and posts about HTML, CSS, and web developer tools are also encouraged.


Posting and Commenting Guidelines

  1. Be Welcoming. n00bs are welcome here. Negativity is not.
  2. Include Context. If you’re asking for help, include enough information for others to recreate your problem.
  3. No Self-Promotion. The following are not allowed: Requests for subscribers, asking for "test users" for your new JS course, offering paid mentorships, and/or premium courses. Even if there is a coupon discount, no. If you're in doubt, message the mods first.

  4. Good Titles - Write a descriptive title. Titles that begin with "hey guys" will be removed.


Related Subreddits


If you want to post something self-promotional, please message the mods first. Personal blog posts that are relevant to the subreddit's stated subject matter don't need prior approval (and are encouraged!).

/r/learnjavascript

248,513 Subscribers

1

CS vs Finance Degree

So I have been in college for two years now (going into next year I will be a junior). Right now I am at a crossroads. I have studied Finance for two years, but have recently taken an interest in learning to code. I started learning JS a few months ago completely on my own and picked it up really fast. I like coding a lot and am really good at math so it wasn’t too hard to learn. If I switch majors to computer science, I would take a concentration on Machine learning and AI. Given those two degrees, which is more useful, and pays better, in the job market today? I don’t want to switch majors and then realize a year later that the job market is saturated and it’s impossible to get a job or I would’ve made more money where I’m at. Would love to hear opinions from people in both industries.

0 Comments
2024/05/03
21:51 UTC

0

Stuck on ODIN Project Todo List for 2 weeks

I'm currently trying to make todo list from TOP. this is the page link https://www.theodinproject.com/lessons/node-path-javascript-todo-list

i know to create projects and todo and load into DOM and save to local storage and all. but i really can't figure out how to link the projects and todo. like this, https://lakeebs.github.io/taskr/
it's code https://github.com/lakeebs/taskr

we should be able to create projects and then create todo inside that specific project. whenever we click on the project it should load the todo in it.

I can't find any tutorials. tried reading code but i can't understand.

Guide Me Please🙏

4 Comments
2024/05/03
18:22 UTC

1

Building my Fitness Journey App with JavaScript Updates

Hey fellow coders! I wanted to share my progress on building a fitness journey app using JavaScript. Today, I successfully implemented a feature that tracks daily workout routines and displays them in a user-friendly calendar format. It's been a challenging but rewarding experience, and I can't wait to see how this project evolves. Stay tuned for more updates and let me know if you have any suggestions or feedback!

0 Comments
2024/05/03
17:03 UTC

2

Trying to understand the Javascript Global Object Model , Inheritance and the prototype chain

Hi there,

I have been using Javascript for quite some years for scripting here and there, and as the need for doing deeper functionalities and out of curiosity brings me to a big in-depth review of basic concepts of the language fundamentals

Something I see difficult to wrap my head around is the Inheritance model and Prototype Chain. My main documentation sources for this matter are

mdnjs - Global objects mdnjs - Inheritance and the prototype chain mdnjs - Object

I get that the global namespace is addreaseable by globalThis

console.log(Object.getOwnPropertyDescriptors(globalThis));

In a more simplyfied way, just seeing the keys by using Object.keys(obj) would be

console.log(Object.keys(Object.getOwnPropertyDescriptors(globalThis)));

We can see all the Standard built-in Objects from here. They are all 'aliased' to the global namespace so that

console.log(globalThis.Array === Array);  // True

Ok now we can access all the Global Objects to see their properties and methods by (lets say in the case of Array)

// Static methods
console.log(Object.keys(Object.getOwnPropertyDescriptors(Array)));
// Instance methods
console.log(Object.keys(Object.getOwnPropertyDescriptors(Array.prototype)));
// Prototype the constructor function
console.log(Object.keys(Object.getOwnPropertyDescriptors(Object.getPrototypeOf(Array))));

We can do this also with Object, and with the rest Global Objects.

What I fail to see , is:

- 1st) The hierarchy:

    - Knowing that Object is parent of all the Objects

    - How can I manually demonstrate that Array an other Standard Objects are descendant of Object?

- 2nd) Why Array would list Static methods of Array , while Array.prototype are the Instance methods ?

- 3rd) What does exactly the Prototype of the Constructor function means?

How could I create my own object say Popcorn, that will be direct descendant of Object ?

It is a nice trip on understanding, and hopefully I will end up figuring out, but anyone helping pave the way will be so much appreciated.

Thank you.

4 Comments
2024/05/03
16:31 UTC

1

I was making my own live code editor that uses chatgpt, does one already exist?

You push a button you talk, translates to text, gpt writes some code, reads that code and updates your live view. you can also edit the code yourself.

0 Comments
2024/05/03
15:19 UTC

1

How does Excalidraw use Local Storage securely?

There is a website called excalidraw which is a sort of drawing/note board. It uses Local Storage to store all the data, such as drawing a line is represented as an Object with coordinates, width, height etc.

My question is how is this secure? I see a lot of advise online against using Local Storage to store user data. I know its just text notes and geometric shapes so its not like its storing plain text passwords, but couldn't someone potentially gain access to your notes? Or does using Local Storage only generally apply for very sensitive data like passwords, emails etc (as the likelihood of someone going out of their way to steal text notes instead of something like passwords being very low)?

3 Comments
2024/05/03
15:23 UTC

1

Making a quiz in Javascript

Hi ! So I've got this project on trinket.io in html that I need to turn in on monday.

I need to create a quiz that concerns the lesson in class. So I created the quiz, but I can't manage to show to correction/right answers, and I can't seem to be able to randomize the binary numbers in the last question.

I've looked on the internet, but the commands are "too complicated" for a student my age, so my teacher probably won't allow me using them

This is what my code looks like :

<p>Quiz de NSI, première</p>

<form name="quiz"> 

<!-- Question 1-->
<p>1.Quel est le chemin absolu du fichier travaildegroupe.txt ?</p>
<input id="q1">
<!-- Question 2-->
<p>2.Quelle instruction Linux permet de créer un fichier ?</p>
<input id="q2">


<!-- Question 3-->
<p>3.Quand est apparu le premier algorithme ?</p>
<div>
    <input type="radio" value="300av.JC" name="q3" />
    <label for="300av.JC">300 av. J.C</label>
  </div>
<div>
    <input type="radio" value="1826" name="q3" />
    <label for="1826">1826</label>
  </div>
<div>
    <input type="radio" value="IXe" name="q3" />
    <label for="IXe">IXe siècle</label>
  </div>

  
<!-- Question 4-->
<p>4.En quelle année Graham-Bell a-t-il inventé le téléphone ?</p>
<div>
    <input type="radio" value="1910" name="q4" />
    <label for="1910">1910</label>
  </div>
<div>
    <input type="radio" value="1816" name="q4" />
    <label for="1816">1816</label>
  </div>
<div>
    <input type="radio" value="1876" name="q4" />
    <label for="1876">1876</label>
  </div>


<!-- Question 5-->
<p>5.Que veut dire l'abbreviation CPU ?</p>
<input id="q5">


<!-- Question 6-->
<p>6.Quel est le système d'exploitation le plus répandu dans le monde ?</p>
<div>
    <input type="radio" value="MacOS" name="q6" />
    <label for="MacOS">MacOS</label>
  </div>
<div>
    <input type="radio" value="Windows" name="q6" />
    <label for="Windows">Windows</label>
  </div>
<div>
    <input type="radio" value="Linux" name="q6" />
    <label for="Linux">Linux</label>
  </div>

  
<!-- Question 7-->
<p>7.Trois processus arrivent en même temps:</p>
    <p>A ; peu important, en 2 cycles</p>
    <p>B ; très important, en 1 cycle</p>
    <p>C ; important, en 3 cycles</p>
<p>On choisi de les exécuter en tourniquet, cela donne:</p>
<input id="q7">


<!-- Question 8-->
<p>8.Convertir (1101,011) en base 10:</p>
<div>
    <input type="radio" value="14,375" name="q8" />
    <label for="14,375">14,375</label>
  </div>
<div>
    <input type="radio" value="13,150" name="q8" />
    <label for="13,150">13,150</label>
  </div>
<div>
    <input type="radio" value="13,375" name="q8" />
    <label for="13,375">13,375</label>
  </div>
  
</form>

<!-- Valider-->
<button onclick="valider()">Valider</button>

<p id="score">...</p>
<p id="commentaire">...</p>

<button onclick="reinitialiser()">Recommencer</button>

<!-- Script-->
<script>
function reinitialiser() {location.reload();}
function valider() {
  
var sco=0;
var q1 = document.quiz.q1.value;
var q2 = document.quiz.q2.value;
var q3 = document.quiz.q3.value;
var q4 = document.quiz.q4.value;
var q5 = document.quiz.q5.value;
var q6 = document.quiz.q6.value;
var q7 = document.quiz.q7.value;
var q8 = document.quiz.q8.value;

if (q1.toLowerCase() == "home/aude/perso/travaildegroupe.txt") {sco+=1;}
if (q2.toLowerCase() == "mkdir") {sco+=1;}
if (q3 == "300av.JC") {sco+=1;}
if (q4 == "1876") {sco+=1;}
if (q5.toLowerCase() == "central processing unit") {sco+=1;}
if (q6 == "Windows") {sco+=1;}
if (q7.toLowerCase() == "a-b-c-a-c-c") {sco+=1;}
if (q8 == "13,375") {sco+=1;}

if (sco < 4) {commentaire.textContent = "Mauvais score";}
if (sco > 4) {commentaire.textContent = "Bon score";}
if (sco == 4) {commentaire.textContent = "Score moyen";}
score.textContent = "Votre score est : " + sco  + "/8";

}
</script>

Any help or tip is appreciated ! And apologies for the results being in french, if you have any questions let me know !

Thanks a lot

0 Comments
2024/05/03
12:11 UTC

3

When using javascript I have to use some utility called "yarn", which apparently installs a lot of javascript dependencies, but, it keeps throwing an error, and, i tried install/uninstalling it via npm and bash, but, it keeps throwing this error?

when you run yarn in a directory it says-

[2/4] Fetching packages...

error SyntaxError: C:\Users\--\AppData\Local\Yarn\Cache\v6\npm-@babel-core-7.22.11-8033acaa2aa24c3f814edaaa057f3ce0ba559c24-integrity\node_modules\@babel\core\.yarn-metadata.json: Unexpected token '', ""... is not valid JSON

12 Comments
2024/05/03
11:31 UTC

1

Help me Master :\

I quit marketing to develop indie apps, like how they do it in indiehacker.com

I initially thought of going no-code route but later felt like it'd be better if I just learn to build it from scratch.

I learn python and few of its frameworks, recently got a hang of html and css as well.

But Javascript, I just can't seem to get a grasp of this thing. I follow along couple of YT tutorials, projects and build a clone of web apps but all these libraries (I prefer Vue) and this annoying ways of this language is messing with my confidence to continue down this path.

I understand bits and pieces of the code but I can't get a hang of this language like it did for python, html, and css.

----------------------

What do I do?

- Should I follow along and build a solid foundation with more tutorials and stay in tutorial hell?

- Should I screw it all and build my app (A chatbot platform) using trial and error with chatGPT and learn along the way?

- Or as how YT experts tell me, will it take me years to know enough JS and its libraries and this and that? In that case, should I go back to my day job and learn this thing on the side?

I see people on X saying they learned to code in 2-3 months and went full on down that path. Then how is it so hard for me to learn this thing?

Please help............

17 Comments
2024/05/03
11:01 UTC

1

The Scrum Master's Apprentice

Hi, I would like to practice running scrum. I'm a software engineer with 4 years of experience. I've been take part in scrum activities for work. I have taken some courses as part of my masters program on project management with some analysis for error data, project velocity, etc.

How can I practice this?

Would people be interested in coming together for a short project that I could run?

Should I be trying to get some certification if I want to start running scrum?

0 Comments
2024/05/03
02:51 UTC

1

Library for developing seat organizer

I am currently developing up a seat management system where a user can select a seat to sit to reserve.I and am in the process of choosing a good library to achive that goal.
Its mainly editing/adding seats like dragging and control buttons.

Something like: seats.io(Not that advanced ofcourse)

I am testing fabric.js at the moment but i am curious if there are other libraries that can do this job and are more flexible maybe?

0 Comments
2024/05/03
02:09 UTC

2

basic question on imports and exports

How do you have more than one module or function in a file?

In a file called util_procs.js I am trying to include two modules. (or a module with two functions or two functions, I cant get any of them working) If I have only one module in a file, it seems to work.

in main I can access sourceInfo.countOnSource(), but I cant access utils.collect()

I cant seem to export anything other than "module.exports = sourceInfo". If I try: module.exports = {sourceInfo, eutils} then it all stops working. What is the syntax to export and import two functions from the same file?

thanks!

main.js:

var sourceInfo = require('util_procs')

var collect = require('util_procs')

var x = sourceInfo.countOnSource(source);
var y = eutils.collect(workder);                     <- collect not found

util_procs.js

var sourceInfo = {
    countOnSource: function(source) {
        <code>
        return(count)
    }
};

var eutils = {
    collect: function(worker) {
        <code>
    }
}

module.exports = sourceInfo;
//function.exports = collectEnergy;
// export function collectEnergy();
1 Comment
2024/05/03
00:05 UTC

1

Leetcode Counter Question

Question:

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (nn + 1n + 2, etc).

Code That Worked:

var createCounter = function(n) {
    let c = -1;
    return function() {
        c++;
        return n + c;
    };
};

Returns:

[-2,-1,0,1,2]

Code That Did Not:

let c = -1;
var createCounter = function(n) {

    return function() {
        c++;
        return n + c;
    };
};

Returns:

[1,2,3,4,5]

Can anyone explain the significance of declaring my variable inside the function as opposed to outside. If you could explain why the second one returns those values that would also help. Please go easy I literally just started learning javascript 30min ago. My coding experience is in C, MIPS, and ARM assembly only.

1 Comment
2024/05/02
23:56 UTC

7

How to code this text game

I'm trying to code a text based game where the user has three variables (say money, health, food), the game consists of showing the user a text and three options to choose from, the options are always related to the text that is shown. When the user chooses one of the options it has to have impact on one of the variables I mentioned earlier.

So the first problem is how do I relate the text to show and the options together, I don't understand how storing them in a relation, like maybe a big object where the key is the text and the value an array with the three options, but if the options are Strings then how do I make them have an impact on the variables.

Any guidance on how to go about this please.

9 Comments
2024/05/02
21:32 UTC

9

A Discord group for coding newbies.

I've seen many posts asking for study buddies of some sort, so.. here is CodingPals! Its a group where everyone and anything coding related can be found, help & more information can be requested.

I've been looking for one personally too, so I decided to create one, you're all welcome.

https://discord.gg/BTWVYpFe

4 Comments
2024/05/02
20:34 UTC

8

I have been learning JavaScript for months and I know all the theory but when it comes to projects I feel like I don't even know what to do. Is it normal? Or I am going about learning the wrong way

Plz do tell it'll help me a lot

22 Comments
2024/05/02
19:37 UTC

1

tiptap editor to docx styling not being added.

I'm trying to create a download button that make a docx file with the contents of the tiptap editor. I got some styling working but not everything like bold, strikethrough, code block,... and some more. Does anyone know the correct method to serialize the tiptap styling content? This is the code I have right now.

import React, {useState, useEffect, useCallback} from 'react';
import {useEditor, EditorContent, Editor} from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import FormatBoldIcon from '@mui/icons-material/FormatBold';
import FormatItalicIcon from '@mui/icons-material/FormatItalic';
import FormatUnderlinedIcon from '@mui/icons-material/FormatUnderlined';
import StrikethroughIcon from '@mui/icons-material/StrikethroughS';
import FormatListBulletedIcon from '@mui/icons-material/FormatListBulleted';
import CodeIcon from '@mui/icons-material/Code';
import UndoIcon from '@mui/icons-material/Undo';
import RedoIcon from '@mui/icons-material/Redo';
import DeleteIcon from '@mui/icons-material/Delete';
import { Color } from '@tiptap/extension-color';
import Text from '@tiptap/extension-text';
import TextStyle from '@tiptap/extension-text-style';
import { doc, updateDoc, deleteDoc } from 'firebase/firestore';
import { firestoreDB } from '../../services/firebase';
import { writeDocx, DocxSerializer, defaultNodes, defaultMarks } from "prosemirror-docx";
import { saveAs } from 'file-saver';
interface TiptapEditorProps {
  content?: string;
  documentId?: string;
  fetchDB?: () => void;
  title?: string;
  color?: string;
  onClose?: () => void;
}
interface Node {
  type: string;
  content?: string;
  children?: Node[];
}
const nodeSerializer = {
  ...defaultNodes,
  hardBreak: defaultNodes.hard_break,
  codeBlock: defaultNodes.code_block,
  orderedList: defaultNodes.ordered_list,
  listItem: defaultNodes.list_item,
  bulletList: defaultNodes.bullet_list,
  horizontalRule: defaultNodes.horizontal_rule,
  strong: defaultNodes.strong,
  strikethrough: defaultNodes.strikethrough,
  image(state: any, node: any) {
    // No image serialization logic is provided here, which means the default behavior will be used
    state.renderInline(node); // Render the image node inline
    state.closeBlock(node); // Close the block containing the image
  },
};
const docxSerializer = new DocxSerializer(nodeSerializer, defaultMarks);
// Define write function outside of the component conditionally
const write = async (editor: Editor | null) => {
  if (!editor?.state.doc) return; // Handle the case when editor.state.doc is not available
  const opts = {
    getImageBuffer(src: string): Buffer { // Type annotation for src
      return Buffer.from("Real buffer here");
    },
  };
  const wordDocument = docxSerializer.serialize(editor.state.doc, opts);
  await writeDocx(wordDocument, (buffer: any) => {
    saveAs(new Blob([buffer]), "example.docx");
  });
};
const Tiptap: React.FC<TiptapEditorProps> = ({ content = '', documentId, fetchDB, title, color, onClose }) => {
  const [noteTitle, setNoteTitle] = useState(title || '');
  const [noteColor, setNoteColor] = useState(color || '#ffffff');
  const editor = useEditor({
    extensions: [
      StarterKit,
      Underline,
      Color,
      Text,
      TextStyle,
    ],
    content: content,
    editorProps: {
      attributes: {
        class: 'prose p-4 outline-none',
      }
    }
  });
  if (!editor) return null;
  const handleColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const color = event.target.value;
    editor.chain().focus().setColor(color).run();
  };
  const handleNoteColorChange = (color: string) => {
    setNoteColor(color);
  };
  const handleSave = async () => {
    const newContent = editor.getHTML();
    try {
      if (documentId) {
        const currentDate = new Date();
        const formattedTime = `${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;
        const formattedDate = `${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getFullYear()}`;
                const noteRef = doc(firestoreDB, 'notes', documentId);
        await updateDoc(noteRef, { content: newContent, date: formattedDate, time: formattedTime, title: noteTitle, color: noteColor });
        console.log('Content updated successfully!');
        if (fetchDB) fetchDB();
      } else {
        console.error('Document ID is missing.');
      }
    } catch (error) {
      console.error('Error updating content:', error);
    }
  };
  const handleDelete = async () => {
    try {
      if (documentId) {
        const noteRef = doc(firestoreDB, 'notes', documentId);
        await deleteDoc(noteRef);
        console.log('Note deleted successfully!');
        if (fetchDB) fetchDB();
        if (onClose) onClose();
      } else {
        console.error('Document ID is missing.');
      }
    } catch (error) {
      console.error('Error deleting note:', error);
    }
  };
  const handleWrite = async () => {
    await write(editor);
  };
  return (
    <div className="space-y-4">
      <div className="bg-zinc-800 p-4 rounded-lg shadow-lg mt-4">
      <label htmlFor="noteColor" className="mr-4 text-white">Note Color:</label>
          <input
            id="noteColor"
            type="color"
            value={noteColor}
            onChange={(e) => handleNoteColorChange(e.target.value)}
            className="mr-4"
          />
        <input
          type="text"
          value={noteTitle}
          onChange={(e) => setNoteTitle(e.target.value)}
          className="px-4 py-2 rounded-lg mr-4 bg-zinc-700"
        />
        <input
          type="color"
          onInput={handleColorChange}
          value={editor?.getAttributes('textStyle').color || '#ffffff'}
          data-testid="setColor"
          className="align-middle"
        />
        <button
          onClick={() => editor.chain().focus().toggleBold().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('bold') ? 'bg-zinc-700' : ''}`}
        >
          <FormatBoldIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().toggleItalic().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('italic') ? 'bg-zinc-700' : ''}`}
        >
          <FormatItalicIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().toggleUnderline().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('underline') ? 'bg-zinc-700' : ''}`}
        >
          <FormatUnderlinedIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().toggleStrike().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('strike') ? 'bg-zinc-700' : ''}`}
        >
          <StrikethroughIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().toggleBulletList().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('bulletList') ? 'bg-zinc-700' : ''}`}
        >
          <FormatListBulletedIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().toggleCodeBlock().run()}
          className={`px-4 py-2 rounded hover:bg-zinc-700 ${editor.isActive('code') ? 'bg-zinc-700' : ''}`}
        >
          <CodeIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().undo().run()}
          className="px-4 py-2 rounded hover:bg-zinc-700"
        >
          <UndoIcon />
        </button>
        <button
          onClick={() => editor.chain().focus().redo().run()}
          className="px-4 py-2 rounded hover:bg-zinc-700"
        >
          <RedoIcon />
        </button>
        <button
          onClick={handleSave}
          className="px-4 py-2 rounded hover:bg-zinc-700"
        >
          Save
        </button>
        <button
          onClick={handleDelete}
          className="px-4 py-2 rounded hover:bg-zinc-700"
        >
          <DeleteIcon />
        </button>
      </div>
      <div>
        <EditorContent editor={editor}/>
        <button onClick={handleWrite}>Download Word</button>
      </div>
    </div>
  )
}
export default Tiptap;
0 Comments
2024/05/02
19:22 UTC

2

Vitest - TypeError: Cannot read properties of undefined (reading 'test')

Upon trying to run tests with npm run test an error is being raised as follows:

  • TypeError: Cannot read properties of undefined (reading 'test')

What would be causing this error to be raised?

import { test } from "vitest";

test ("Test", () => undefined );

vite.config.js

/// <reference types="vitest" />

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/

export default defineConfig({
  plugins: [react()],  test: {
    coverage: {
      provider: "v8",
      reporter: ["json", "html", "text"]
    },
    environment: "happy-dom"
  }
})

package.json

{
  "name": "markdown_previewer",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "test": "vitest",
    "coverage": "vitest run --coverage"
  },
  "dependencies": {
    "marked": "^12.0.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^6.4.2",
    "@testing-library/react": "^15.0.5",
    "@testing-library/user-event": "^14.5.2",
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^4.2.1",
    "@vitest/coverage-v8": "^1.5.3",
    "@vitest/ui": "^1.5.3",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "happy-dom": "^14.7.1",
    "vite": "^5.2.0",
    "vitest": "^1.5.3"
  }
}
0 Comments
2024/05/02
18:55 UTC

6

Is my approach to projects wrong?

I'm going through the Odin project and I'm just starting the calculator project. The instructions want me to start in js and then go to html and css to style it. I seem to like building the UI then using it as I build my js so I can see the result as I go.

I also took this approach for the rock, paper, scissors project. I struggled with reformatting my original code to go from control to UI. So I started from scratch, got the UI out of the way, and then made it work.

I'm happy with the results but my main concern is that this may be a bad approach or a bad habit to start as a beginner.

8 Comments
2024/05/02
18:35 UTC

1

JS Challenges - using resources?

I'm taking an intro to JS course to get accepted into a JS bootcamp ; and I have a question about challenges. How do I do challenges? Am I supposed to know how to do challenges by memory? Or is it something I should be looking up on Google or a JS cheat sheet?

For example, we went over basics in the course like functions, arrays, objects, strings, if's etc; then we were given a few dozen challenges to try and solve with only knowing what we were taught. And I was dumbfounded because I didn't know how to solve them with only using only what I know. But after looking over examples I found on js guide websites I was able to solve given challenges. Am I doing things right? Or is this "cheating"? Im a new beginner and don't have any JS experience. But after completing a few challenges on my own I felt like I knew much more from just reading and watching the course videos.

1 Comment
2024/05/02
17:41 UTC

1

Here's My Tutorial for Coding a Chess Game

I created a tutorial where I coded a chess game from scratch. Additionally, there's an option to play against the computer using the Stockfish REST API. Let me know your impressions.

https://youtu.be/fJIsqZmQVZQ

0 Comments
2024/05/02
16:04 UTC

1

Need help with Adobe InDesign script

My programming knowledge is limited to seeing what others have done and editing/fumbling through to make it do what I need it to do. I'm trying to create a script in InDesign that will make two text boxes on the page with some dummy text and apply specific styles. I can get the code to make the text boxes where i need them to and put the dummy text in, but the styles arent applying. You'll see below that the first text box is trying to apply a paragraph style that's in a Style Group and the second is just a style ungrouped in the Paragraph Style palette. The first text box code will make the script fail. But if i comment it out, the script works but doesnt apply the paragraph style to the second text box.

var doc = app.activeDocument;

var page = doc.layoutWindows[0].activePage;

var textFrame = page.textFrames.add({

geometricBounds: [36, 36, 117, 923.998], // [top, left, bottom, right]

contents: "headline copy",

applyParagraphStyle: paragraphStyleGroups.itemByName("Main Styles").paragraphStyles.itemByName("Headline")

});

var textFrame = page.textFrames.add({

geometricBounds: [117, 36, 468, 923.998], // [top, left, bottom, right]

applyParagraphStyle: doc.paragraphStyles.itemByName("Headline"),

contents: "body copy"

});

0 Comments
2024/05/02
14:58 UTC

0

Javascript30 doesn't give any ressource to do the exercice ?

Hi i'm doing javascript 30 to learn js but for the first exercice about the touch that make sounds, he don't give any assets ? how am i supposed to do the exercice ? am i missing something ?

8 Comments
2024/05/02
14:17 UTC

2

New perspective needed on data structure alternatives and best practices.

tl;dr: what other data structures would be suitable for a rigid runtime object, which also helps with consistency in keys and data?

Background:

I work on an app for my company on a low-code platform, where I heavily used javascript to implement the logic we needed.

The aim of the app is to help employees pack orders. For example, it shows where in the warehouse the next item is located so that you can then pack it into the package and then scan it. In principle, it is a browser app that is then accessed by employees on tablets.

The data is synchronized with SAP when the order is loaded and left.

I decided on the following solution: a JSON object in which all the required data is stored and updated at runtime.

Why JSON? The latencies when communicating with SAP are long and so I can make the client side more performant.

This works, but I'm not entirely satisfied with the solution. Inconsistency. I know, probably mostly my fault if I misspell the keys or something or other things happen. It also bothers me that in an array in json the objects never stay in an order.

What alternative data structures or options do I have in JavaScript to create a runtime object that helps with consistency?

What would be the best practices? Anything particular I should look in to?

In this scenario I would like to have a more solid data structure. I was thinking about using `new Map()` instead of JSON, but I would first like to know if such a thing makes sense.

I need a new perspective. Maybe I need to go back to the drawing board.

Thank you in advance for suggestions!

Example data structure from my code. Modified so it shows not all keys there are.

{
  "head":{
    "DocNum": 11111111,
    [...]
    "percentCompleted":60
  },
  "pos":[
    {
      "LineNum":2,
      [...]
    },
    {
      "LineNum":0,
      [...]
    },
    {
      "LineNum":1,
      [...]
    }
  ],
  "nveHead":{
    "Code":7026,
    [...]
  },
  "nvePos":[
    {
      "Code":106085,
      [...]
    },
    {
      "Code":106086,
      [...]
    },
    {
      "Code":3,
      [...]
    }
  ],
  "nveList":[
    {
      "pkgType":1,
      [...]
    }
  ]
}
6 Comments
2024/05/02
12:28 UTC

7

Better way to push/pop from javascript list.

I way doing a leetcode question of backtracking.
Now, if i use,
array.push(something)

do something on array
array.pop()

It is slower in comparison of-
array[array.length] = something
do something on array

array.length--;

Can anyone explain why this is happening.

7 Comments
2024/05/02
12:22 UTC

2

A variable containing an API key periodically fails to be declared.

Hi There,

I have been making a short adventure game in JavaScript. One of the features is using the OpenWeatherMap API to get weather information about the player's location to use as part of the flavour text.

As this game will run on a publicly available website, I had to obfuscate the OpenWeatherMap API key by declaring it in a variable in a PHP page outside the website's public folder. The secret PHP file is then called by another PHP file inside the include folder of the website public folder and loaded into the JavaScript file via some jQuery and AJAX.

Most of the time, everything works perfectly; other times, the variable in the JavaScript meant to hold the API key does not get declared, preventing the script from accessing the API.

I've tried everything I can to resolve this issue, but I've reached a point where I need another set of eyes to review my code. I've included the JavaScript code below and a copy of the console output from Firefox.

JS File

https://drive.google.com/file/d/1pDHF3eyU5Rrt1kf7yaGtXwnZ71H9jp2X/view?usp=sharing

Console Error Image.

https://imgur.com/a/Bl1a3xw

4 Comments
2024/05/02
10:28 UTC

2

JSON Schema: How to require a value to be one of another properties array values

So, I'm struggling to figure out how to word this, so apologies if this is confusing/unclear.

I have a (simplified) schema like so:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "fields/checkbox-multiple.json",
    "title": "...",
    "description": "...",
    "type": "object",
    "required": ["choices"],
    "properties": {
        "default": {
            "description": "Default value of the field (optional)"
        },
        "choices": {
            "description": "Choices for any type which has a multiple settings e.g. checkbox, radio, select etc",
            "type": "array",
            "minItems": 1,
            "items": {
                "required": ["value", "text"],
                "properties": {
                    "value": {
                        "description": "Value to be used in the field. This will be the setting value e.g. true, false for a radio field"
                    },
                    "text": {
                        "description": "Text displayed on the field in the Customizer",
                        "type": "string"
                    }
                }
            }
        }
    }
}

So the schema essentially creates a HTML Select field.

choices.value is the value of option tag, choices.text is the displayed text, fairly straight forward.
The default, is simply what the value of the input should be by default (again, sorry for stating the obvious).

Here's some React psuedo-code to make this clearer:

<select name="...">
  {props.choices.map((choice) => {
    return (props.default === props.value)
      ? <option value={choice.value} selected>{choice.text}</option>
      : <option value={choices.value}>{choice.text}</option>
  });
</select>

Get to the question already!

So you may have already gotten it...The value of default MUST BE one of the choices.value ...errr...values.

Something like this in my head, but Googling is giving me everything but what I'm looking for...

{
    "default": {
        "enum": {
            "oneOf": #choices.values.items.value
        }
    }
}

Also, default is not required, but if it is given it has to be one of the choices.

Hope that makes sense! Thank in advance

14 Comments
2024/05/02
10:05 UTC

1

Something isn't right in the code

// Function to toggle monthly salary tables function toggleMonthlySalary(month) { let tables = document.getElementById("monthly_salary").getElementsByTagName("table"); for (let i = 0; i < tables.length; i++) { if (i === month) { tables[i].style.display = tables[i].style.display === "none" ? "table" : "none"; // Toggle display } else { tables[i].style.display = "none"; // Hide other tables } } }

// Attach onclick event to month buttons let buttons = document.getElementById("month-buttons").getElementsByTagName("button"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function() { toggleMonthlySalary(i); }; }

6 Comments
2024/05/02
09:29 UTC

1

How to prevent clicking while dragging a slide?

2 Comments
2024/05/02
09:01 UTC

2

Generate the same page with different videos

Hello, I would like to create a youtube like website with a few pages full of videos and i would like to generate the videos with javascript.

I generate the first page with:

let videosHTML = "";



for (let i = 1; i < 25; i++) {
  videosHTML += `<div class="video">
<a href="videos/${i}.mp4" type="video" target="_blank">
  <video src="videos/${i}.mp4" muted controls></video>
</a>
</div>`
};


document.querySelector('.js-video-container').innerHTML = videosHTML;

But now i dont know how to continue, the second page should be 25 - 50 etc... is there a way to get page number in javascript or how would you approach this?

The only way i could think of, as a beginner is making a different script for each page on my website, but that seems like a very clunky solution.

6 Comments
2024/05/02
08:50 UTC

Back To Top