Best way to debug javascript while there is no error message for reading non-existing field from an object

const ball = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    size: 10,
    speed: 4,
    dx: 4,
    dy: -4
}

// draw ball on canvas 
function drawBall() {
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.xize, 0, Math.PI * 2);
    ctx.fillStyle = '#0095dd';
    ctx.fill();
    ctx.closePath();
}

I’m trying to draw a ball using canvas.

ctx.arc(ball.x, ball.y, ball.xize, 0, Math.PI * 2);

This line calls arc() and tries to read ball.size by access ball.xize. It’s a typo.
In languages I’m familiar with, typos like this result in error messages that can help quickly identify the cause. There is none with javascript. What is the canonical way to debug javascript in such cases? Do we have to read and verify each and every line like what I did here?

Why is ReactDOM.render() not rendering

I am trying to create a webpage with React however when I use ReactDOM.render(), it fails to render the element.Here is my HTML :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>
    <body>
        <div id="root"> </div>
        <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
        <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
        <script src ="ReactTest.js" type="text/babel">
        </script>
    </body>
</html>

Now here is my JavaScript code:

ReactDOM.render(
     <h1> Hello 1</h1>,
     document.getElementById("root")
)

Why does it fail to render?

Dragable div does not work in touch screen

I have a dragable div that works in computer very well but today I checked in touch screen and knew that it does not move !!! In my java script code I have onmousemove , is there any alternative for that in touchscreen? Can any body tell me what to do to solve this ? BTW I want this work in both touch screen and computer, not just in touch screen
My dragable div code is blow.

<div id="wrapper" style="border: 0.1vw solid gray;">
    <div id="mydiv">
        <img src="image/cs.png">
    </div>
</div>
<script>
dragElement(document.getElementById("mydiv"));

        function dragElement(elmnt) {
          var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
          if (document.getElementById(elmnt.id + "header")) {
            /* if present, the header is where you move the DIV from:*/
            document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
          } else {
            /* otherwise, move the DIV from anywhere inside the DIV:*/
            elmnt.onmousedown = dragMouseDown;
          }

          function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            // get the mouse cursor position at startup:
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // call a function whenever the cursor moves:
            document.onmousemove = elementDrag;
          }

          function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // calculate the new cursor position:
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            
            let parentElement = elmnt.parentElement;
            if(elmnt.offsetTop < 0){elmnt.style.top = "0px"; return;}
            if(elmnt.offsetTop > (parentElement.offsetHeight - elmnt.offsetHeight)-2)     {
                elmnt.style.top = (parentElement.offsetHeight - elmnt.offsetHeight-2) + "px"; 
                return;
              }
            if(elmnt.offsetLeft < 0){elmnt.style.left = "0px";return}
            if(elmnt.offsetLeft > (parentElement.offsetWidth - elmnt.offsetWidth)-2){
                elmnt.style.left = (parentElement.offsetWidth - elmnt.offsetWidth-2) + "px";
                return;
            }
            
            // set the element's new position:
            elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
            elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
          }

          function closeDragElement() {
            /* stop moving when mouse button is released:*/
            document.onmouseup = null;
            document.onmousemove = null;
          }
        }
</script>

read/write JSON file in a simply web application with node.js

I have an HTML file (index.html) where I put a form and I want to see a list of elements that are inside a JSON file (elements.json).
I want to create a server with node.js, so I create app.js in this way:

const express = require('express')
const app = express()
const port = 3000
var config = require('./public/js/elements.json');

//static file
app.use(express.static('public'))
app.use('/css', express.static(__dirname+'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))


//set view
app.set('views', './views')
app.set('view engine', 'ejs')

app.get('', (req, res) => {
    res.sendFile(__dirname+'/views/index.html')
})

//listen
app.listen(port, () => console.info(`Listening on port ${port}`) )

1. How can I do in my script.js file (that is in the same directory of elements.json) to show the elements in a table on my index.html?

2. When I fill the form in the HTML page, I want to add that element on my JSON file, in order to see it in my list of elements on HTML page. How can I do it?

Do While loop – Simply add numbers

I need to prompt the user to enter a series of numbers, or the word “quit”.
Then, If the user enters a number, add the new number to a running total.
And, If the user enters the word “quit” the loop should stop execution.
I cant figure what should I do here. Im a beginner. i don’t know how to make it work when user enter a word quit

let total = 0;
let number = 0;
    do {
        total += number;
        number = parseInt(prompt('Enter a number: '));
        if(number >= 0) {
            document.writeln("<p>You entered " + number + "!</p>");
        } else {
            if(isNaN(number))  {
            number = parseInt(prompt('Enter a number: '));
            document.writeln("<p>Try again. We are looking for a number!</p>");
            } 
        }
    } while(number >= 0)
    document.writeln("<p>The total is " + total + "</p>")

Update data in Barchart from API in Vue

Calling an Api to get the values and putting them in the List but the list in data function is not being updated.

created(){

  // API CALL FOR BARCHAR
var getStandardBarchart = async() => {
  //var currentarray =[]

   // API CALL TO KEIKAI for BARCGARTS
   var myHeaders = new Headers();
   myHeaders.append("Content-Type", "application/json");
   //var raw = JSON.stringify({"input_values": input_values, "output_values": output_values});
   var raw = JSON.stringify({"input_values": {},"output_values": [ "barchart1","barchart2","barchart3","barchart4","barchart5","barchart6","barchart7","barchart8"  ]});

   var requestOptions = {
     method: 'POST',
     headers: myHeaders,
     body: raw,
     redirect: 'follow'
   };


   await fetch("/api", requestOptions)
     .then(response => response.json())
     .then(result => {
        var barChart = [];

        //var value
        Object.keys(result).forEach(function(key) {
        let specificValue = parseInt(result[key])
          barChart.push(specificValue) 
        })
        console.log(barChart)
        console.log(this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0][2])
       // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0][1]=15

        // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0] = barChart.splice(0, 4);
        // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[1] = barChart.splice(0, 4);


      })
     .catch(error => console.log('error', error));



 }

getStandardBarchart()







},

What I want is that the values in the data function should be updated by the barchart[] list. But if I push something in list before api or give some default value to the list it is not undefined
in Values:[barchart[0]] gives undefined

data:function(){
{imagecontent:

   {barchart1:{barid: "bar_Agricultural_production_Animal_production_Cattle",names:["sdjhfb", "derfgas", "Pdft", "dfdfs", "dfsdfat"],
   values:[[barchart[0], 10, 5, 150],[87, 80, 25, 35]],
   textxaxis:["future", "present"] }}
   }]
}

}

Understand why an else command is in a different position

I’m studing Javascript with FreeCodeCamp, till now everything is clear but I’ve a stupid question that I’ven’t understood:

function lookUpProfile(name, prop) {
  for (let x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}

Why return "No such contact"; is after the for cycle and not the if that control the contact name?!

Vue Metamask Login App Can’t Interact with Metamask Because The Store Components Won’t Interact with The Frontend

I followed this tutorial to try to create a Metamask login app with Vue https://duartefdias.medium.com/authenticating-users-to-your-web-app-using-metamask-and-nodejs-e920e45e358. The code is described in individual files but there isn’t a defined project structure. I made my own github repo to try to organize the structure in terms of where each file should go in the project https://github.com/ChristianOConnor/metamask-vue-for-debug. The app compiles but the button to connect/install Metamask doesn’t do anything.

This is the actual code that displays the connect to Metamask functionality:

<template>
  <div>
    <button
      color="primary"
      large
      :disabled="buttonDisabled"
      v-on:click="performAction"
    >
      <img src="../assets/metamaskloginbutton.png" class="metamask-logo" />
      <span v-if="isMetaMaskInstalled()">Login with Metamask</span>
      <span v-if="!isMetaMaskInstalled()">{{ buttonInstallText }}</span>
    </button>
  </div>
</template>

This is the function that’s supposed to determine whether Metamask is installed:

isMetaMaskInstalled() {
      //Have to check the ethereum binding on the window object to see if it's installed
      if (process.client) {
        return Boolean(
          this.$store.getters["metamask/ethereum"] &&
            this.$store.getters["metamask/ethereum"].isMetaMask
        );
      }
      return false;
    },

This function always returns false even though Metamask IS installed in the browser through which I am accessing the site.

I spoke with the author of the code and he said that my problem is that I’m not accounting for the vue store and I need to add the code ethereum: state => { if(process.client) { return window.ethereum } } but he never specified where. I read up on the vue store with articles like this one https://www.digitalocean.com/community/tutorials/how-to-manage-state-in-a-vue-js-application-with-vuex. This article didn’t help though. I tried to get the store to work by altering the store/index.js file like this

store/index.js

import { createStore } from "vuex";

export default createStore({
  state: {},
  getters: {
    ethereum: () => {
      if (process.client) {
        return window.ethereum;
      }
    },
  },
  mutations: {},
  actions: {},
  modules: {},
});

Btw I had to remove state from ethereum: state => { if(process.client) { return window.ethereum } } because prettier wouldn’t allow the code to compile with an unused parameter.

Why does isMetaMaskInstalled() always return false even when I add ethereum: state => { if(process.client) { return window.ethereum } } to the store/index.js file?

I’m assuming this code is failing because I’m putting ethereum: state => { if(process.client) { return window.ethereum } } in the wrong spot. Where am I supposed to put this code?

why this javascript code only works once? [duplicate]

Can someone tell me what’s wrong with this js code? it only works once, i want it to work every time i hit the document.querySelector(“.icon-right”);

const background = document.querySelector(".mainimage");
const right = document.querySelector(".icon-right");
right.addEventListener("click", () => {
  if (background.style.backgroundImage = "url(../img/1.jpg)") {
    background.style.backgroundImage = "url(../img/2.jpg)";
  } else if (background.style.backgroundImage = "url(../img/2.jpg)") {
    background.style.backgroundImage = "url(../img/3.jpg)";
  } else {
    background.style.backgroundImage = "url(../img/1.jpg)";
  }
});

How to add properties to a JSON in TypeScript?

I have the following code:

type DailySummaryEntrry = {date: string, summary: ParsedSummary};

function parseDailySummaries (summaries: DailyRawSummaries): DailySummaryEntrry[] {
  const entries: DailySummaryEntrry[] = [];

  for (const date in summaries) {
    const rawSummary = summaries[date];
    if (!rawSummary) continue;
    entries.date = date ;
    entries.summary= parseRawSummary(rawSummary);
  }
  return entries.sort().reverse(); // sort by newest date first
}

I don’t know why do I get

Property 'date' does not exist on type 'DailySummaryEntrry[]'.deno-ts(2339)

at this line
entries.date = date ;

and:

Property 'summary' does not exist on type 'DailySummaryEntrry[]'.deno-ts(2339)

At this line

entries.summary= parseRawSummary(rawSummary);

How to get browser certificate to digitally sign a payload using Chrome Extension

I am working on a chrome extension to get access to the list of certificates on my browser (Including the class 3 certificate I purchased).

This is the manifest.json

 {
"manifest_version": 2,
"name": "Coding Train Extension 2",
"version": "0.001",
"permissions": ["storage", "activeTab", "scripting"],
"content_scripts": [
    {
        "matches":["<all_urls>"],
        "js": ["content.js"]
    }
],
 "background":{
   "scripts": ["background.js"]
 },
 "browser_action":{
   "default_icon": "logo.png"

 }
} 

This is the background.js

 console.log("This is inside background...");
 chrome.browserAction.onClicked.addListener(collectAvailableCertificates);

 function collectAvailableCertificates() {
   // Return all certificates that this Extension can currently provide.
   // For example:
   return [{
     certificateChain: [new Uint8Array()],
     supportedAlgorithms: ['RSASSA_PKCS1_v1_5_SHA256']
    }];
   }

In this test, the content.js is not being used much. I have an icon of the extension on browser and on its click I am triggering the background.js.
I am trying to emulate the APIs provided in the Chrome API documentation https://developer.chrome.com/docs/extensions/reference/certificateProvider/

How to call the methods like collectAvailableCertificates(), handleSignatureRequest(request) as seen in the document is what I am pursuing. My aim is to use this purchased certificate to digitally sign an xml payload.

Issue with sending FormData from backend

I have a component which processes and uploads images. Currently I process the image on my backend and then send it to my frontend and then upload it from there. I would like to do everything on my backend. The only issue is that the upload endpoint requires FormData() object. I found an npm package form-data which I’m using on my backend now, but I’m still getting error.

This is how my frontend does it:

const data = await uploadImage(img) // I would like to move logic bellow to this backend function.
const file = new File([Buffer.from(data)], `img-${i}.webp`, {
  type: "image/webp",
});
const formData = new FormData();
formData.append("path", "images");
formData.append("files", file, file.name);
await axios
  .post("http://localhost:1338/api/upload", formData, {
    headers: { authorization: `Bearer ${jwtToken}` },
  })
  .then(({ data }) => {
    console.log(data);
  })
  .catch(console.log);

This is what im trying to do on my backend:

const data = await processImage(img.url)
const formData = new FormData();
formData.append("path", "images");
formData.append("files", data, "file.name");
await axios
  .post("http://localhost:1338/api/upload", formData, {
    headers: { authorization: `Bearer ${process.env.JWT_TOKEN}` },
  })
  .then(({ data }) => {
    console.log(data);
  })
  .catch(console.log);
// I get error: 413 Payload Too Large

I’m trying to do it with the same image which works with the frontend method. Perhaps I need to create a new File(), but I couldn’t find any npm packages which worked for that. What should I do to get this working?

i want to recreate this python function in JS so i can use it in an HTML file. i am not familiar with JS

def printit():
  threading.Timer(1.0, printit).start()
  session = HTTP("https://api-testnet.bybit.com/",api_key="", api_secret="")

  positionBuy = session.my_position(symbol="BTCUSDT")['result'][0]['unrealised_pnl']
  positionSell = session.my_position(symbol="BTCUSDT")['result'][1]['unrealised_pnl']
  print (positionBuy)
  print (positionSell)

printit()

The idea is to fetch data every second but if i do it in python i will hit rate limit if many users are using this , so if i do it in JS then it will reduce rate limit since it will load on the frontend with users ip(so i’ve heard)

is this possible?

How to change color of a specific feature (building) with setFeatureState Mapbox GL

My use case : Fill the color on building/address based on user’s searched building/address in Mapbox GL.

What I have achieved till now : I am able to get the searched building’s details by using GeoCoder event “result” and I am getting feature ID in response along with coordinates of the searched address. And I am changing it’s color by using setFeatureState method but it’s filling the color on whole state/country. Please checkout my JS code.


const bounds = [
        [-97.846976993, 30.167105159], // Southwest coordinates
        [-97.751211018, 30.242129961], // Northeast coordinates
      ];

      const map = new mapboxgl.Map({
        container: "map",
        style: "mapbox://styles/smallcrowd/cl07a4926001b15pnu5we767g",
        center: [-79.4512, 43.6568],
        zoom: 13,
        maxBounds: bounds,
      });

      // Add the control to the map.
      const geocoder = new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        mapboxgl: mapboxgl,
      });

      geocoder.on("result", (e) => {
        map.addSource("states", {
          type: "geojson",
          data: "https://docs.mapbox.com/mapbox-gl-js/assets/us_states.geojson",
        });
        map.addLayer({
          id: "state-fills",
          type: "fill",
          source: "states",
          layout: {},
          paint: {
            "fill-color": "#FFA500",
          },
        });
        console.log(e);
        map.setFeatureState({
          id: e.result.id, //feature id
          source: "states",
        });
      });

      document.getElementById("geocoder").appendChild(geocoder.onAdd(map));

This is geocoder result response:


result: {
center: (2) [-97.791161, 30.229803]
context: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
geometry: {coordinates: Array(2), type: 'Point'}
id: "poi.412316930875"
place_name: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_name_en-US: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_type: ['poi']
properties: {foursquare: '53d16d13498ea4ebec82bc78', landmark: true, address: '2101 W Ben White Blvd', category: 'hardware, shop'}
relevance: 1
text: "Texas Tool Traders"
text_en-US: "Texas Tool Traders"
type: "Feature"
}