Issue with defining a variable in TypeScript

While TypeScript is supposed to generate JavaScript files with equivalent code, there can be instances where this is not the case.

For example, in the demonstration below:

demo.ts

function foo()
{
    if(1)
    {
        let myName = "Raktim";
    }
    console.log(myName);
}
foo();

demo.js

function foo() {
    if (1) {
        var myName = "Raktim";
    }
    console.log(myName);
}
foo();

In the above code snippet, a local variable myName is declared in the demo.ts file. However, when we look at the compiled JavaScript code, it declares myName as a global variable instead.

This inconsistency can lead to unintended consequences, such as changing the meaning of the code. So why does this happen?

Answer №1

It appears that you are utilizing a tool like webpack with babel for code transpilation.

https://babeljs.io/docs/en/babel-preset-env

Make sure to specify your target browser for babel.

For example, if your target browser is the latest version of Chrome that supports let and const, the compiled code will not change.

UPDATE: The issue has been resolved in the comments section. You can use the --target option, for instance: tsc --target ES2016 file.ts

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

I need assistance improving my poor JavaScript patterns and practices. Where should I turn for help?

After focusing primarily on back-end tasks for the past few years, it's become apparent to me that JavaScript (and CoffeeScript) projects have evolved significantly in my absence. Working mainly in a rails environment, my previous JavaScript/jQuery i ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Troubleshooting a problem with jQuery child items

Could someone help me understand why the second div is affected by the last part of the code and not the first? It's puzzling to see all the content disappear, especially when I expected the first div to be impacted as it seems like the immediate pare ...

Is the issue with AJAX and a global variable a result of my misunderstanding?

My goal is to use AJAX to load client data onto a page and then replace a company ID with the corresponding name from a different company table in the same database. However, I am facing an issue where the global JavaScript variable is not being updated wi ...

Guide on sending a POST request with Protractor

Attempting to hit an endpoint with a POST request using Protractor has been quite challenging for me. I have tried various versions of the code, utilizing different HTTP clients like 'request' and exploring other options as well. In addition to ...

What is the most efficient way to transfer substantial data from a route to a view in Node.js when using the render method

Currently, I have a routing system set up in my application. Whenever a user navigates to site.com/page, the route triggers a call to an SQL database to retrieve data which is then parsed and returned as JSON. The retrieved data is then passed to the view ...

Implementing an event listener within a knockoutjs custom directive

I have extensive experience as a knockout user, but I am currently struggling to achieve a specific scenario. For the past few days, I have been trying to create a system within a knockout component that allows observables to translate themselves into diff ...

When attempting to loop through an Observable that is of type array using *ngFor, the error message "Cannot read property 'subscribe' of undefined

I can't figure out why this isn't working, even though it seems straightforward. I'm using a service that gives me an observable. There are a few rxjs streams connected to it in the following way: search(searchTerm: string { this.search ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

"Displaying 'undefined' in an array of objects during the ngOnInit lifecycle hook in Angular 5

When attempting to access the HTML content, no value is being returned <mat-nav-list> <a mat-list-item href="" *ngFor="let link of products"> {{ link.name }} </a> </mat-nav-list> Below is the JSON data: [{"id":215,"nam ...

Organizing month and year in angularjs: A step-by-step guide

I have a table with a column for month and year. I need to sort the dates by year. Can someone please help me with this? You can view the code in the provided fiddle. In my case, the date format is "MMMM yyyy". For example, if I have "August 2016", "Septe ...

Setting a default value for an HTML select menu in Angular 6

I am accustomed to the traditional way of creating select menus and setting default values in angularJS, but I'm struggling to understand how to do this in Angular (6). Here is an array of menu items: fontChoices = [ { label: 'Trebu ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...

Saving current class information in the browser's localStorage

Is there a way to store the active class of a clicked link in localStorage so it remains even when navigating to another page? <div id="collapse2" class="panel-collapse collapse"> <ul class="list-group"> <li class="list-group-it ...

The next.js Head component that is imported from next/head is not functioning correctly when used on share pages

I recently switched my website from create-react-app to create-next-app, but I'm having issues with the Head(app/head) component. Let's say I have a blog section with pages structured as follows: pages/blog/index.js and pages/blog/[slug].js. In ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...

I would like to retrieve my data using my personal API and have them displayed as checkboxes

https://i.sstatic.net/qPSqe.jpgHere is an excerpt of the progress I have made main.html (it's actually a form) <div class="form-group form-check-inline"> <input class="form-check-input" type="radio" name=& ...