Comparing the value of a variable inside a class with a global variable declared as let is not possible

I am facing an issue while trying to compare a variable named 'let hours' within my class. The comparison needs to be done in a separate function called 'utcChange' after clicking a button. I initially declared this variable at the beginning as let, assuming it would be accessible anywhere. However, the if statement inside the utcChange function is not functioning as expected. Any idea why?

let hours;

class Clock {
  el: Element;
  constructor(element) {
    this.el = element;
    setInterval(() => this.run(), 1000)
  }

  run() {
    var time = new Date();
    let hours = time.getHours()+utcValue;
    var hoursChanged = hours.toString();
    var minutes = time.getMinutes().toString();
    var seconds = time.getSeconds().toString();

    if (hoursChanged.length < 2) {
      hoursChanged = '0' + hoursChanged;
    }

    if (minutes.length < 2) {
      minutes = '0' + minutes;
    }

    if (seconds.length < 2) {
      seconds = '0' + seconds;
    }

    var clockStr = hours + ' : ' + minutes + ' : ' + seconds;

    this.el.textContent = clockStr;
  }
}

var clock = new Clock(document.getElementById('tsClock')); 
var utcButton = document.getElementById('button');
utcButton.addEventListener("click", utcChange);
var utcValue = 0

function utcChange(){

    if (hours < 23) {
        utcValue += 1
    }
}

Answer №1

The variable declared locally within the run function of the class is covering up the outer variable. Remove the use of let in the declaration.

run() {
    var time = new Date();
    hours = time.getHours()+utcValue;
    var hoursChanged = hours.toString(); // Use without `let`
    var minutes = time.getMinutes().toString();
    var seconds = time.getSeconds().toString()
    ...
}

Avoid relying on a global variable. Instead, make the variable a field and access it through the object's field to get the value for hours.

Answer №2

let hours indicates that the variable can only be accessed within the function where it is declared.

If you want to use it in another function, you should declare it as a field.

For example:

class Clock {
    hours: number;
    run() {
        this.hours = ...;
    }
}

function utcChange() {
    if (clock.hours < 23)
         // ...
}

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

Is there a way for me to verify that the key of one object is a subset of the keys of another object?

export const masterKeysObject = { MAIN: 'main', REDIRECT: 'redirect', DASHBOARD: 'dashboard', USER_ID_PARAM: ':userId', CREATE_NEW: 'create_new' } as const; type MasterKeys = keyof type ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

Effective approach to exchange information among controllers in AngularJS

There are numerous techniques available to share data between controllers in Angular, such as accessing prototypical data from a parent scope, utilizing scope events for controller communication, or implementing shared services. However, what is considere ...

What is the best way to retrieve a state variable within the getServerSideProps() function in NextJS?

Introduction Greetings everyone, I am a newcomer to NextJS. Currently, I am in the process of developing a weather application that utilizes external APIs. My main task involves fetching data from an API and displaying it on the frontend. Desired Function ...

Get the color at a specific index in a JavaScript array

When I click a button, a pie chart is generated using chartjs. The results are displayed based on the filters applied, showing (Name | Value%): Service_1 | 10 Service_2 | 15 Service_3 | 75 Sometimes, certain results may not appear: Service_1 | 20 S ...

Why does the 401 error continue to persist while attempting to log in using Google Identity service on my Laravel application?

Trying to implement Google authentication services for user authentication. I've already integrated Laravel sanctum to allow users to log in and register successfully. This time, I want to add Google Identity services as an additional authentication ...

Run the script within the Angular scope

Hey there! I'm having an issue passing a JavaScript code through Angular scope, but when it renders on the view page, it's displayed as text. I even attempted using ng-Sanitize, but unfortunately, that didn't solve the problem. &lt;div ...

Exploring the wonders of nested object destructuring in ES6

How have you been? I want to remove the property "isCorrect" from a nested object. Original List id: 1, questionText: 'This is a test question for tests', answerOptions: [ { answerText: 'A', isCorrect: ...

The comparison between importing and requiring mutable values for export

I'm exploring the distinction between import and require in relation to exporting and importing mutable values. Picture a file a.ts: export let a = 1; export function f() { a = 2; } Next, we have three versions of a main file, index1.ts: import { ...

When viewing my project on GitHub pages, the images within the card are not appearing

After running my project page link at https://nayaksofia.github.io/RestaurantReviewTest1/, I've noticed that the images inside the card are not displaying. However, when I run the same project on my local server localhost:8000, the images appear just ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured: dir main -server.js dir subMain dir routing -routes.js ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

Press the Javascript URL submission button

Currently utilizing the Free Bootstrap Wizard tool, found at The wizard code can be accessed at In my current project, I am attempting to redirect users to the register-success.html page once they click on the "finish" button. Below is a snippet of the ...

Guide to using the useState hook in ReactJS to dynamically change views

Currently, I am delving into the realm of React and learning how to construct a single-page application without using a redirect page. I want every UI change to be triggered solely by a button click. However, I'm encountering difficulties in implement ...

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

Filtering a user list array in JavaScript based on tags using regular expressions

I have a user list array that needs to be filtered by tags. I attempted to filter the array using the filter and match methods with a RegExp for matching the tag, but the results were not as expected. let users=[{id:1,name:'john',tags:' ...

To effectively run the Angular Compiler, it is necessary to have TypeScript version greater than or equal to 2.7.2 but less than 2.8.0. However, the system detected

I am encountering an error in my Angular application that reads: The Angular Compiler is asking for TypeScript version >=2.7.2 and <2.8.0, but it found 2.8.3 instead. When I attempt to downgrade TypeScript to the correct version by running: npm ...

Why is it that the "await" keyword lacks the ability to truly await?

I created this code to access the google calendar API and retrieve information. To make it easier to understand, I added the variable x to the function. Initially, I expected x to be displayed as 1, however, it consistently shows up as 1. The main issue ...