JavaScript Calculator

Hi Devs,
Could someone help me out on this? I,m preventing two consecutive dots from being entered. The code is working but it prevents dot even after others values has been entered. It’s like a permanent prevention.

decimal.addEventListener('click', () => {
	display = document.getElementById("display");
	let decimal = document.getElementById("decimal");
	const curValue = event.target.value;
	if (preValue === curValue) {
		return false;
	}
	display.textContent += '.';
	preValue = event.target.value;
	

});

Have you logged out curValue and preValue to see what is happening?

I don’t understand what you mean by ‘loggedout’.

Sent the data to the console/terminal so it can be read, commonly done with a console.log.

I did and realized that ‘preValue’ and ‘curValue’ are always the same even when other buttons have been pressed. That’s the reason the condition is always true. I then make both variables global and put ‘curVar’ in each event listener of the other buttons so it value could differ from preValue. But it gets more complicated and I’m kind of confused now.

What I want to achieve is the part of the JavaScript Calculator that says multiple dots should not be allowed in a number. I’m confused now and I’m not sure I’m heading in the right direction. Any hints or help will be appreciated. Thanks

Hmm, I was under the assumption that it was because curValue would be a string a characters and not a single character. It’s really hard to say without seeing your code.

I definitely don’t like global variables. But sometimes when you’re learning it’s just what you do.

I would keep logging things out and try to figure out what is going on. A big part of being a good developer is being a good debugger. And a lot of that is being a good detective/investigator.

curValue refers to the number right?

If curValue is a string, could you check to see if there’s a dot in there already like so?

if(curValue.includes(".")){
     return false
}else{
    return curValue += "."
}

No. curValue refers to the current value being entered which I needed to compare with the number. if curValue already exist, then it shouldn’t allow that the current curValue to be written to the number.

Anyways, Thanks for your help. I figured it out with @kevinSmith’s advice. I kept debugging and correcting and doing that back and forth until it worked but code has completely changed.

Thanks @kevinSmith. I figured it out. Your advice helped.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.