Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifying the rxUartBuffer

Code Section

console.log(this.toHexString(rxUartBuffer));
this.write_ACK_ONLY(rxUartBuffer)
console.log(this.toHexString(rxUartBuffer));

Log Output

aa|02|00|01|00|00|0b|00|00|00|00|00|00|00|00|00|00|01|1d|d5|
aa|02|00|01|00|40|0b|00|00|00|00|00|00|00|00|00|00|01|1d|d5|

Code

import {Module} from './module';
import {PCP} from './pcp';
import {Logic} from "./logic";
...

const SerialPort = require('serialport');
const Ready = require('@serialport/parser-ready');
const CRC = require('crc-full').CRC;
var gpio = require('rpi-gpio')
var gpiop = gpio.promise;

gpiop.setup(7, gpio.DIR_OUT);

export class RsBUS{
/*SERIAL*/
private port = new SerialPort('/dev/ttyS0', {
baudRate: 19200, dataBits: 8
});
...
}

Answer №1

Typically, a global variable is susceptible to modification by any function.

To address this issue, the let keyword offers a solution to restrict the alteration of global variables outside of their designated function scope.

For instance:

myVariable = 10

function fx() {

let myVariable = 5

console.log("myVariable inside fx: " + myVariable)

}

console.log("myVariable outside fx: " + myVariable)

In the provided example, employing the let keyword permits temporary overriding of myVariable solely within the confines of the fx() function. This mechanism ensures that the global variable remains unaltered by the function's operations.

Answer №2

Understood! Instead of simply copying an array with A = B, I should use the slice() method.

A = B.slice();

Check out this resource on modifying original arrays when pushing to a cloned array in JavaScript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting RXjs problems on Heroku deployment

I've encountered an issue with my NodeJS/Angular2 website. It functions smoothly on my local Windows 10 setup, but when I attempt to deploy it on Heroku and access the site, the front-end console in Chrome displays an error message and the site fails ...

Steps for generating a unique division element for every javascript response

How can I dynamically create a new div for each response in JavaScript? The message is in JSON format containing all the messages sent and received. This is my JavaScript code: $.get("MessageServlet", function (responseJson) { $.each(responseJ ...

Make sure to save your data prior to using req.session.destroy() in Express

Before destroying the session in the logout route, I need to save the session value "image location" into the database. Here is the solution I have implemented: app.get('/logout',function(req,res){ Person.update({ username: req.session.use ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

Utilizing Pipes within a Method in Angular 2 along with Dependency Injection triggers an "Insufficient Number of Arguments" error

I am searching for a solution to incorporate a custom pipe into my class. The custom pipe itself ( referenced from this source, many thanks ) involves injecting a dependency (the DomSanitizationService). import { Pipe, Inject, Injectable } from '@ang ...

Using regular expressions in JavaScript, we can separate a paragraph into individual sentences

Hey there! I'm currently working on a project that requires extracting sentences from a paragraph using regex in JavaScript. Unfortunately, my attempts to achieve this have resulted in syntax errors as I have tried methods used in other programming la ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

The Bootstrap dropdown vanishes before I can even click on it

I recently encountered an issue with my Bootstrap dropdown menu on my website. After making some changes, the dropdown disappears after 1-2 seconds when viewed on a mobile phone. Interestingly, the original Bootstrap menu works fine, but not my customized ...

The form data is being passed as null to HttpContext.Current.Request

My file upload module is working well with Postman without any content type. However, in the code, the file count always shows as 0 in the backend API. If anyone has any insights into what I might be doing wrong, please help me out. Thank you. Below is my ...

Transitioning a NPM project to the Apache server

Recently, I successfully managed to run a simple example project by following these steps: I downloaded and installed Node.js for windows x64. I then used Git to clone the project from https://github.com/BretCameron/three-js-sample.git Next, I ran t ...

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Exploring the Bookmarking Capabilities of Firefox

Is there a way to access the users' bookmarks using Firefox API and javascript? Appreciate any help, Bruno ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...