Test your knowledge with this quiz on Typescript's AddOrSubtract functions

Just starting out with learning Typescript and tackling this challenge from Execute Program:

Create a function that either adds or subtracts 1 from a given number. The first argument is the number, and the second argument is a boolean. If the boolean is true, add 1; otherwise, subtract 1.

I've attempted various versions of the code below:

function addOrSubtract(x: number, y: boolean): any {
  if (y = true) {
    return x+1;
  } else {
    return x-1;
  }
  return x;
}
addOrSubtract(5, true);
addOrSubtract(5, false);

The problem I'm facing is that the test only recognizes the first condition. Even adding an additional else if (y = false) statement yields the same outcome.

Results of four tests: addOrSubtract(5, true); Expected: 6 OK! addOrSubtract(5, false); Expected: 4 but received: 6 addOrSubtract('5', true); Expected: type error OK! addOrSubtract('5', null); Expected: type error OK!

Thank you in advance

Answer №1

Your current if statement is incorrect because you are using the assignment operator = instead of the equality check operator ==.

Here's the corrected code snippet -

function addOrSubtract(x: number, y: boolean): any {
  if (y == true) {
    return x+1;
  } else {
    return x-1;
  }
  return x;
}

Additionally, since variable y is of type boolean, you can directly use it in the if condition.

function addOrSubtract(x: number, y: boolean): any {
  if (y) {
    return x+1;
  } else {
    return x-1;
  }
  return x;
}

Answer №2

Building upon Aman's response, you have the option to streamline this process further by implementing ternary statements.

function addOrSubtract(x: number, y: boolean): number {
  x = y ? x + 1 : x - 1;
  return x;
}

Ternary statements can be a valuable tool in TypeScript and JavaScript, offering efficiency and time-saving benefits if utilized correctly. Unless of course, your compensation is based on lines of code.

In TypeScript specifically, it is recommended to use === over == for type-safe comparisons with strict type checking.

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

Unveiling the method of retrieving a targeted value from JWT in React

I'm struggling to retrieve a specific value from my JWT token in React. I am using the react-jwt library to decode the token, and when I log it, I receive this output: Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

When working with environment variables in Node.js, everything runs smoothly within the console log. However, an error occurs when attempting to pass a parameter to

In my current project setup with nx monorepo and TypeScript for handling environment variables in Node.js, I encountered a peculiar issue. I am able to access the variables using console.log, but when I pass the variable as a parameter to the mongoose.conn ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

What causes the 'this' to be undefined in React event handlers?

It is common knowledge that in the React code provided, this will be undefined. Various approaches such as binding and arrow functions can solve this issue. What I am interested in is understanding the rationale behind this behavior. Kindly elucidate on ...

The property or method 'startsWith' is not supported by this object

Regarding my webpack configuration: { "presets": [ ["env", { "targets": { "browsers": [">0.1%", "last 4 versions", "not ie <= 9"] } }] ] } However, I encountered a problem specifically in Internet Explorer: Ther ...

Using Django forms within a modal: dynamically redirecting and managing errors

My current project involves integrating a login form within a modal window using Django. I found a helpful guide at this link which has been working effectively so far. However, I am now aiming to enhance the user experience by redirecting them to their pe ...

Why isn't the PHP snack bar working when clicking on an href <a> using onClick?

How can I dismiss this snackbar when the add to cart <a href> is clicked? I've tried but nothing seems to work. Can anyone provide some assistance? Here is my code: SNACKBAR CODE <div id="snackbar">Some text some message..</div> A ...

Foundation 6 Websites - Dropdown Automatically Close When Clicked

I am currently using foundation 6.2 to create the registration page for my website. So far, everything is functioning as expected. However, I am now looking to have a dropdown pane open when an input field is focused on and close when the focus is removed. ...

No GraphQL type definitions were discovered for the specified pointers: src/**/*.graphql

I am utilizing the @graphql-codegen/cli tool to automatically generate TypeScript types from my GraphQL server. Below is the content of my codegen.yml: overwrite: true schema: "http://localhost:3001/graphql" documents: "src/**/*.graphql" generates: src/ ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

Algorithm for Filling Tiles in a Gaming Environment

Background: In my current project, I'm developing a unique tile-based game in Javascript. The game involves a character who can freely move around the map without taking diagonal paths - only left, right, up, or down movements are allowed. As the cha ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Sending Multiple Checkbox Values to PHP Using jQuery's Ajax Function

Using jQuery to retrieve values from multiple checkboxes is simple and effective. To see a demonstration, check out this link The jQuery function works well; when a checkbox is checked, we can see the selection based on the data-id after clicking btnUpda ...

Having trouble retrieving the pathname of a nested route within middleware.js in next js version 14

I am currently referring to the official App Router documentation for Authentication on this page My goal is to extract the pathname from the next URL export function middleware(request) { console.log('now we are in middleware'); const { ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

Is there a way to automatically transfer the store's order value to my payment gateway's checkout process during the checkout process?

I am facing an issue with integrating the Razorpay payment gateway into my online store built on ecwid. The process involves decrypting order details from the store, sending them to the payment gateway for processing, and redirecting the customer back to t ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

Steps for creating a JavaScript session expiry notification:

Ensuring user session continuity is essential, especially before it expires. In a recent quest on Stack Overflow, I inquired about detecting a dead session and alerting the user. A solution involving AJAX/JSON was proposed, but it inadvertently kept the s ...

MongoDB can track an index in a collection using a case-insensitive regex pattern

Utilizing different indexed collections in MongoDB for queries from a straightforward search engine has been my practice. I am facing a challenge with Regex queries that need to be case insensitive, as the queried collection is not adhering to the index. ...