I am experiencing an issue with the arrow function in ECMAScript 6, it seems to not be working even though I have declared it

I am currently learning ES6 and trying to implement a new function that displays the date on a website when hovering over it with the mouse. However, I have encountered an issue where the function is not working as expected. I would greatly appreciate any help in understanding why it's not functioning properly. Additionally, I received the error message "Uncaught ReferenceError: Cannot access 'Time' before initialization." Unfortunately, I am unsure how to resolve this error.

//Time script
        const question = document.querySelector(`.timeleftstyle`);

        question.addEventListener(`mouseover`, Time);
        question.addEventListener(`mouseout`, hide);

        const Time = () => {
            const clock = document.querySelector(`.thetime`);
            clock.innerHTML = Date();
        }

        const hide = () => {
            const clock = document.querySelector(`.thetime`);
            clock.innerHTML = ``;
        }
    

Answer №1

To ensure your code runs correctly, make sure to position your functions above the "using" section:

//Time script

    const question = document.querySelector(`.timeleftstyle`)
    
    const Time = () => {
        const clock = document.querySelector(`.thetime`);
        clock.innerHTML=Date();
        
    }
    
    const hide = () => {
        const clock = document.querySelector(`.thetime`);
        clock.innerHTML=``;
    }
    
    question.addEventListener(`mouseover`,Time);
    question.addEventListener(`mouseout`,hide);

Answer №2

The issue is associated with hoisting. Both Time and hide variables are defined after the event listeners, causing them to be hoisted to the top of the code but remaining uninitialized. This results in them having no value when the addEventListener function is called. As Ester suggested, the solution is to declare Time and hide before adding the event listener.

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

Trouble with implementing Ajax in Express and jquery

My app has a browse page where users can add items as owned or wanted. Currently, when adding an item it redirects back to the general /browse page. However, I want the page to not refresh at all. I'm attempting to achieve this with ajax, but as a beg ...

Attaching a synchronous event listener to a form's submit button using JavaScript

I am currently tackling a security project in Javascript, a language I am not very familiar with, and I seem to be encountering some difficulties with EventListeners. Here is an excerpt of my code: function prevclick(evt) { evt.preventDefault(); document. ...

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

Use JavaScript to Generate a hash Table

Take a look at my code below, it's supposed to extract data results and display them in an HTML Table. However, I can't seem to get it working: <html> <head> <script type="text/javascript"> data = { d : { resu ...

"Exploring the world of Angular JS through testing controllers with jasmine

I'm currently facing an issue with my test in the controllersSpec.coffee Angular App code: describe 'Controllers', -> beforeEach -> angular.module 'app' describe 'MainCtrl', -> beforeEach inject ($co ...

Tips for effectively changing Observable data into an Array

I am currently attempting to transform an Observable into an Array in order to loop through the Array in HTML using ngFor. The Typescript code I have now is causing some issues. When I check the testArray Array in the console, it shows up as undefined. it ...

Avoid allowing users to copy text by dragging and dropping it from the browser

I am looking for effective ways to prevent users from easily copying text from my website. After doing some research, I came across a useful solution here This method successfully prevents copy/paste/cut actions when using ctrl key combinations and the r ...

In vue, pagination links are displayed as dots instead of numbers

Struggling to integrate pagination in vue. Facing an issue where the pagination links are appearing as dots, depicted in the attached image. The correct number of pagination links display and I can navigate through different pages using the side navigation ...

Showcase the link to the npm package within the Packages category on the GitHub repository

Exciting news - I just finished creating and releasing my very first npm package. https://i.sstatic.net/GL1Q6.png I'm eager to connect this package to my GitHub repository. When I look under packages, it says Publish your first package. However, I&a ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...

What is the most effective way to retrieve both grouped data and all data from mongodb?

I have successfully retrieved totalAccount and totalBalance using the code snippet above. However, I am facing an issue where no other field or data besides those two are showing up. How can I modify this code to also fetch all the data from my collectio ...

Utilizing the .finally method on a promise that is already being handled with try/catch statements elsewhere may lead to an UnhandledPromiseRejection

Recently, I've come across an unexpected behavior while working with nodejs. To illustrate this strange occurrence, let's consider the following example: Imagine we have two functions, foo and bar. The foo function creates a promise, attaches a ...

What steps can I take to modify an onclick function to incorporate multiple functions?

I need help modifying a button's onclick behavior to replace one function with two new functions. Here is the code I currently have: var random; function number(){ var random =Math.floor(Math.random()*Math.floor(Math.random()*20)) ...

What is the best way to communicate between the Browser and WebDriver using Protractor?

As I work on integrating Protractor for running tests on my Angular web application, I leverage a custom Angular service called ApiClient for making API calls. To mock this service, I utilize browser.addMockModule along with angular.module().factory(). Thi ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

Building a table using a JSON object in a React component

I have been dynamically creating a table in React based on the API response received. data = {"name":"tom", "age":23, "group":null, "phone":xxx} Everything was working fine until I encountered a scenario w ...

Denied the execution of the inline script due to a violation of the CSP by the Chrome extension

We've been working on integrating Google Analytics into our Chrome extension, and here are the steps we've taken: We updated our manifest.json with the following line: "Content-Security-Policy": "default-src 'self'; script-src 'n ...

The live video feed from getUserMedia is not displayed on the three.js plane as expected

I am trying to incorporate a video from getUserMedia into a plane using three.js. However, the video does not appear as expected. When I deny access to the webcam, an image is loaded and displayed instead of the video. Loading and displaying the image po ...