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

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Issue with capybara-webkit not sending data parameters in $.ajax delete request

When I use capybara-webkit to execute my ajax DELETE requests, I am noticing that the data parameters are not being sent to the controller. However, when I run the test suite with selenium, the data parameters do get sent and the test passes. Here is a sni ...

Error: Attempted to access 'embed' before it was initialized (hi)

module.exports = { name: "slowmode", description: "Set the slowmode of a channel.", execute(message, args, Discord) { if(!message.member.hasPermission("ADMINISTRATOR")) { return message.reply(&q ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

How to Identify and Print a Specific Property in a JSON Object using Node.js?

Hey there, I'm having trouble extracting the trackName from the JSON object provided here. I've tried accessing it using this code: console.log(res.text.results[0].trackName); but unfortunately, I keep getting this error message: TypeError: Cann ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

Exploring the functionality of Material-UI's TextField component through role-based testing with React

I currently have some components that contain mui TextFields, and there are two specific scenarios for these components: One TextField is meant for LicenseCode and does not require a label. Additionally, there are several TextFields generated using t ...

Exploring and Presenting Arrays using React JS

Recently, I have started working with react js and I am trying to add a search functionality to filter an array in React. My goal is to allow the user to enter a character in the textbox and only see the names that contain that specific character. So far, ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Learn how to mock asynchronous calls in JavaScript unit testing using Jest

I recently transitioned from Java to TypeScript and am trying to find the equivalent of java junit(Mockito) in TypeScript. In junit, we can define the behavior of dependencies and return responses based on test case demands. Is there a similar way to do t ...

Can a robust web application be developed using Kotlin in Node.js?

With the recent release of Kotlin 1.1, it is now possible to compile Kotlin projects into JavaScript as a target, allowing for full JavaScript compilation. Can a Node.js application, like an express webserver, be developed entirely using Kotlin code? As s ...

Combining AddClass and RemoveClass Functions in Mootools Event Handlers

I am currently in the process of creating a CSS animation, and one aspect involves changing the class name of the body at specific intervals. Since I am relatively new to Mootools (and JavaScript in general), my approach has been to add/remove classes to ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...