Can an inline try be implemented without including a catch block as demonstrated?

I have a scenario where I need to execute code that may result in an error without catching it.

If the response is not valid JSON, then the desired outcome should be 0:

Here is the code snippet I am considering:

var overallProgress = try {JSON.parse(text)} ? 0; 

Is there a way to achieve this?

Alternatively, could something like this work:

var overallProgress = try { JSON.parse(text)} catch(error) { 0 }; 
var overallProgress = try { JSON.parse(text)} catch(error) { overallProgress = 0 }; 

However, errors are encountered when using the above code.

I came across a similar post below but did not find any solution:

Is try {} without catch {} possible in JavaScript?

To make it easier on the eyes:

var overallProgress = 0; 
try { overallProgress = JSON.parse(text).overallProgress } 
catch(error) { overallProgress = 0 }; 

Answer №1

Indirectly, yes. One method is utilizing an IIFE:

const overallProgress = (() => { try { return JSON.parse(text) } catch { return 0 } })();

However, it is recommended to structure it over multiple lines for better readability:

const overallProgress = (() => {
  try {
    return JSON.parse(text);
  } catch {
    return 0;
  }
})();

While using const has its perks, there isn't a significant advantage compared to using separate assignments like this:

let overallProgress;
try {
  overallProgress = JSON.parse(text);
} catch {
  overallProgress = 0;
}

Alternatively, you could start with a default value and then attempt to update it through parsing:

let overallProgress = 0;
try {
  overallProgress = JSON.parse(text);
} catch {
  /* ignore: maintain the current `overallProgress` value */
}

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

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Check if array2 is partially ordered as array1 in JavaScript

Is there a more efficient way to achieve these conditions in JavaScript using vanilla or lodash? const array1 = [1, 2] const array2 = [1, 2, 3, 4] //true const array2 = [1, 3, 2, 4] //true const array2 = [4, 3, 2, 1] //false const array2 = [2, 3, 1, 4] / ...

Enhance your website with a dynamic dropdown feature using Javascript and Bootstrap 5, allowing buttons to respond

Currently, I am experimenting with Javascript to dynamically incorporate elements into a Bootstrap 5 dropdown. To guide me, I referred to the relevant documentation which can be found here (https://getbootstrap.com/docs/5.0/components/dropdowns/#menu-items ...

Access various results from a jQuery function

Is there a way to efficiently extract the values of petKeys and employeeKey using the jQuery functions provided below? var whenSelectDateFromCalendar = function () { initKeyValues(); petKeys = ? employeeKey = ? }; var initKeyValues = function ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Use ajax to dynamically update the contents of a textbox

As a newbie programmer, I recently created my own JavaScript update function for my program. However, the code is not updating as expected. Can someone please help me troubleshoot and get it working properly? What I want to achieve is that when I change t ...

a guide to structuring REST API requests with axios in Vue.js

In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places. // UserdataComponent.vue const anInstance = axio ...

The error message "AWS Lambda Node 18: fetch is not defined, please resolve or include global fetch" indicates that

Seeking assistance with calling the Pagespeed Insights API from an AWS Lambda using Node 18. Struggling to make fetch() function properly. Cloudwatch logs indicate the message "inside the try about to fetch," but then nothing else appears. The Lambda con ...

Adding a character at the current cursor position in VUE JS

My quest for inserting emojis in a textarea at the exact cursor position has led me to an extensive search on Vue JS techniques. However, most resources available online provide solutions using plain Javascript. Here is the code snippet I am working with: ...

How to use Angular 2 to communicate with JavaScript API whenever the router switches to

I am currently working on an Angular2 component that has a template which relies on JavaScript calls to load various components such as Facebook, Google Maps, and custom scripts. The necessary scripts are already loaded in the index.html file, so all I ne ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

Retrieve the size of an element without having to wait for the browser to "recalculate style"

I am currently focused on optimizing the performance of some code that heavily relies on graphics. One of the main issues I am encountering is the delay in obtaining the dimensions of a specific div element. Most of the time, this process runs smoothly, bu ...

Updating input value in Vue using JavaScript method

When using JavaScript to set the value of an input in my Vue method, it initially appears to work. However, when I try to save the data, it only saves what was typed before the value was updated by the method. For example, if I type new yor and select "New ...

Express fails to handle the POST request

Using ejs, express, nodeJS and mySQL has been great so far. However, I'm facing an error with this code: Cannot POST /search. I believe the index.ejs and app.js files are okay, but I suspect there's a problem with the searchRouter... app.js cons ...

Automating web pages with the power of Node.js

I have developed an API in PHP that accepts a 10-digit number as a variable and provides data in JSON format. For instance, the URL structure is like this: www.exampletest.com/index.php?number=8000000000. The succeeding variable will be the current number ...

jQuery - Wait for the completion of one UI change before initiating another UI change

Is there a way to implement the functionality where $("#login").toggle("drop", {direction: "left"}); is executed first and upon completion, $("#register").toggle("drop", {direction: "right"}); is then carried out? The issue arises from the fact that the ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Tips for including a permanent button at the bottom of a material ui dialog box

I want to implement a dialog popup in my react js application. When the user clicks on a button, the dialog should open up. Inside the dialog, there is a form with input fields. After the user fills out all the inputs, they can submit the information by cl ...