Error in Typescript: Function declarations are not allowed in blocks while in strict mode

When attempting to run a script, I encountered the following error message:

Function declarations are not permitted in blocks in strict mode during targeting of the 'ES3' or 'ES5' version. The modules are automatically in strict mode.

The script I am working on is in TypeScript and it looks like this:

export default () => {

  if(document.getElementById("myRange")){
    //slider 
    var slider = document.getElementById("myRange") as HTMLInputElement;
    var output = document.getElementById("demo");
    var gainTimeOutput = document.getElementById("time");
    var sliderEco = document.getElementById("myRange-eco") as HTMLInputElement;
    var outputEco = document.getElementById('demo-eco');
    var eco = document.getElementById('eco');
    outputEco.innerHTML = sliderEco.value;
    output.innerHTML = slider.value;

    function movingSlider(){ <-- Error occurs here 
      output.innerHTML = slider.value;
      var convertSlider = parseInt(slider.value); 
      var convertSliderEco = parseInt(sliderEco.value);

      var gainTime = Math.round(convertSlider).toString();
      var gainMoney = (Math.round(convertSlider* 2).toString();

      gainTimeOutput.innerHTML = gainTime + "h"; 
      outputEco.innerHTML = sliderEco.value;
      eco.innerHTML = gainMoney + "€";
    }

    slider.oninput = e => {
      movingSlider()
    };

I am puzzled by the fact that removing the line

if(document.getElementById("myRange"))
allows the code to work properly. Can anyone explain why this error is happening and suggest how to resolve it?

Answer №1

It appears that the error message is quite straightforward. The issue lies in having a function declaration inside a block, which can behave strangely across different environments and may lead to unpredictable results before being specified in ES6. Your current setup does not permit this, so it's recommended to assign a function expression to a variable name instead. Consider changing

function movingSlider(){

to

const movingSlider = function movingSlider(){

If you have shared the complete code of the exported function, you could potentially improve its clarity by handling the scenario where myRange does not exist. In such cases, an early return statement can be beneficial:

export default () => {
  const slider = document.getElementById<HTMLInputElement>("myRange");
  if (!slider) {
    return;
  }
  // continue with the remaining code

This approach helps in avoiding unnecessary indentation levels throughout the function.

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

Smooth Slide Show Scrolling with Mouse Wheel Within a Container

My slick carousel with vertical scroll is causing issues as it scrolls the entire page. I am specifically looking to have it scroll within a particular div, such as the product section div. Any suggestions on how to achieve this? Html Code: <s ...

A guide on changing a plus sign into a minus sign with CSS transition

Is there a way to create a toggle button that changes from a plus sign to a minus sign using only CSS, without the need for pseudo-elements? The desired effect is to have the vertical line in the "+" sign shrink into the horizontal line. While I know it& ...

Upon returning to the website homepage from another page, the JavaScript animation ceases

I implemented a unique typewriter animation on my homepage by utilizing code from this source and making minor HTML edits to customize the content. https://codepen.io/hi-im-si/pen/DHoup. <h5> <body>Hello! I am Jane.</body> < ...

in AngularJS, check for object attributes existence before proceeding to use them

Currently, I have a filter function that is designed to check the latitude and longitude distance of objects within an array against the range selected by the user. However, there is a problem in which some objects within the array do not possess latitude ...

Somehow, my array only manages to traverse exactly half of its elements

Something odd is happening with my input tag in the HTML file where only half of my array elements are being processed. The input collects numbers/letters and assigns a line of code, like this: let result = Object.fromEntries( Object.entries(answers2).m ...

Initialization of Angular provider $get is missing

Within my 'app.js' file, I have the following code that is used in my config to set up $navigationProvider.doSomething(). When running this code, Test1 and Test3 are alerted correctly, but I'm having trouble with getting my this.$get method ...

Generating exclusion filter based on user input

I am attempting to create a search string that can identify a specific character during the search process. I want to utilize it as an exclusion marker if the text includes the symbol -. The exclusion should only apply when the - character is preceded by ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

Using the Javascript function getElementById to retrieve user input for passing a RSS FeedURL

I've been working on creating a basic form where users can input a Feed URL and see the contents displayed on the HTML page. For testing purposes, I have used "https://jquery-plugins.net/rss" as the feedUrl, and it has been functioning normally. This ...

Download CSV file directly in Internet Explorer 10 by choosing to open the file instead of saving it on your device

On my server, I have a link available to download a file: <a id="downloadCSVFile" runat="server" href="javascript:void(0)" onclick="parent.document.location = 'CSVFile.csv';">Download</a> I attempted this method as well: <a id=" ...

Ways to determine the height of a row within a flexbox

Is it possible to obtain the height of each row within a flexbox container using JavaScript? For instance, if there are 3 rows in the container, can I retrieve the height of the second row specifically? ...

Improving the functionality of multiple range slider inputs in JavaScript codeLet me

Is it possible to have multiple range sliders on the same page? Currently, all inputs only affect the first output on the page. Check out an example here: http://codepen.io/andreruffert/pen/jEOOYN $(function() { var output = document.querySelectorAl ...

Spring MVC applications might experience slow loading times when loading RequireJS libraries

Recently, I integrated RequireJS into my Spring MVC application to manage dependencies for various libraries, including jQuery and jQuery UI. Although I have successfully implemented it, I am facing an issue whenever the page is loaded or refreshed. Initia ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

Issue with accessing undefined property in Angular 2+ using Typescript

In my Angular 7 project, I am retrieving data from a service which looks like this: {name: "peter", datetime: 1557996975991} I have a method that is supposed to retrieve this data: myMethod() { this.myService.getdata().subscribe((res) = ...

Leveraging useEffect and useContext during data retrieval

I'm currently in the process of learning how to utilize React's Context API and Hooks while working on a project that involves using fetch(). Although I am able to make the request successfully, I encounter an issue where I can't retrieve t ...

What is the best way to retrieve the value of an object based on its key?

I'm working on a function that returns another function, and I need some guidance: fn: <T extends Object>(key: keyof T) => (value: ???) => void I want the type of ??? to be determined by the type of instanceOfT[key]. For instance, in the ...