Do we need to use parseInt for the '*' operator in JavaScript?

I have an array where I am mapping it at some point to calculate the sum and percentages. However, when I tried implementing the logic, I noticed that using '*' directly works fine but using '+' adds the two strings together.

For example:

const a = '100';
const b = '10';

const c = a * b;

const d = a + b;

console.log(d)

When I checked the value of d, it returned '10010' while c gave '1000'. This confusion led me to wonder why this is happening.

But then, trying parseInt(a) + parseInt(b) worked perfectly with output as 110.

Answer №1

When it comes to JavaScript, primitive datatypes such as int and float do not exist. Instead, variables can be initialized with any type of data. Take for example:

const a = 100;
const b = 10;

const c = a * b;

const d = a + b;

console.log(d);

This code should function correctly without the need for quotes around the numbers. By excluding the quotes, we ensure that the constants are storing numeric values rather than strings. In your original example, using the plus operator (+) would result in concatenation rather than addition because the constants were being treated as strings due to the presence of quotes.

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

What is the Vercel equivalent to .netlify/functions?

I'm in the process of deploying this repository: https://github.com/DataStax-Examples/astra-tik-tok using Vercel instead of Netlify. I've converted vanilla React to Next.js, but I'm unsure how to transition the code in the Home.js file to w ...

Verify whether a document retrieved from mongoDB contains a certain property

Dealing with user accounts in Mongoose, I have set it up so that the user can use their phone number to sign in: const account = await db.Account.findOne({ phone: req.body.phone }) : Now, I need to confirm if there is a property named verified in the acco ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Tips for making jQuery DataTables switch between multiple DOM tables?

I am working on a project where I need to display different jQuery Datatables based on the selected option in a <select> element. The data for each Datatable is stored in hidden DOM <table> elements: <!-- Make sure jquery.dataTables.css and ...

The template failed to load on AngularJS post-compilation

Following the build of my Angular app, I encountered this error message: [$compile:tpload] Failed to load template: app/app.html (HTTP status: 404 Not Found). Seeking assistance from you all!!!!! app.html <div class="root"> <div ui-view> ...

Difficulty encountered when positioning a container using BootStrap 4

As a newcomer to the world of web development, I encountered an issue while trying to align a container on my webpage. Despite my efforts to center the container using (line 30), the page seems to update but there is no visible change. Can anyone help me ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Is there a way to populate fields on a hidden input using Mechanize?

When I try to use the form to navigate to a different page, I realize that the input field is hidden. Below is the HTML code for reference: <form id="form_pager" method="post" action=""> <input type="hidden" id="txtPage" name="page"> ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Removing an element from the parent/master array after splicing the copied array

My array setup includes a master array called the parent array. When the page loads, a PHP array encoded in JSON with information about every user on the site is assigned to a JavaScript variable - var all_users = <?php echo $users;?>;. Upon logging ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

A function that retrieves the empty values from an array and returns undefined if there

After undergoing a time-consuming process, the sample below shows that the array values are returned empty. function myFunction() { let myArray = []; let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0] pastArray.forEach(item =>{ setTimeout(function(){ myA ...

What is the best way to streamline the creation of a "products filter" using Node.js and Angular?

I have decided to build an angular application for an online computer store, and I am using a node/express backend. One of the key features of the application is the products page, where users can view all the products available in our database. Each produ ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

Submitting a JavaScript array to MongoDB using a React application: A guide to success!

As a beginner delving into the world of React and MongoDB, I'm encountering difficulties in establishing communication between the two technologies. Recently, I've been following a detailed tutorial on Medium that focuses on utilizing the Plaid A ...

Testing components in React Native using asynchronous Jest methods

I have a component that triggers a fetch request when it mounts and then displays the results. I've been struggling to create a test snapshot of this component after the request is completed. I've searched on various forums like SO but haven&apo ...

What is the best way to retrieve the column that comes after a specific column?

I have a specific column and I want to extract the subsequent column in the dataset. nhood,column,variablecolumn Treasure Island,3,5 McLaren Park,1,2 Tenderloin,28,112 Lakeshore,14,8 Chinatown,15,103 Although I know the name of the second column, the na ...

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...