patternjavascriptMinor
A very basic JavaScript calculator
Viewed 0 times
javascriptcalculatorbasicvery
Problem
I'm just starting out with code. I created a very basic JavaScript calculator.
While writing, I couldn't help but think that there must be easier, faster and less redundant ways to write this. For example, when I have to update the display, I have to call the refreshScreen function, which then takes the previous HTML, adds the new stuff to it, and then sets it as the new HTML.
I guess what I'm trying to say is, how can I make the following code less redundant, and are there any libraries that can help me accomplish the same thing in an easier/better/more appreciated way?
It would also be great if I could get some comments on the style of the code. I really want to know what the best coding practices are.
`var ans = "0"; // current answer
var pressed = "0"; // keeps track of everything that has been pressed
var resultsScreen = $("#results");
var needsNumber = true; // keeps track of whether or not an operation was selected previously
var allButtons = $("button");
var decimalUsed = false; // makes sure that the user uses the decimal only once
$(document).ready(function(){
allButtons.on("click", function(){
var content = $(this).html();
// special cases
switch (content) {
case "=":
computeAnswer();
break;
case "AC":
pressed = "0";
break;
case "CE":
removeLastPressed();
break;
case "Ans":
if (lastPressedOperation()) {
pressed += ans;
}
if (pressed == "0") { // if refreshed by pressing AC
pressed = ans;
}
break;
default:
var val = $(this).attr("value");
console.log("You pressed " + val);
if (val == null) { // if its an operation
if (!lastPressedOperation()) { // if allowed to press operation agai
While writing, I couldn't help but think that there must be easier, faster and less redundant ways to write this. For example, when I have to update the display, I have to call the refreshScreen function, which then takes the previous HTML, adds the new stuff to it, and then sets it as the new HTML.
I guess what I'm trying to say is, how can I make the following code less redundant, and are there any libraries that can help me accomplish the same thing in an easier/better/more appreciated way?
It would also be great if I could get some comments on the style of the code. I really want to know what the best coding practices are.
`var ans = "0"; // current answer
var pressed = "0"; // keeps track of everything that has been pressed
var resultsScreen = $("#results");
var needsNumber = true; // keeps track of whether or not an operation was selected previously
var allButtons = $("button");
var decimalUsed = false; // makes sure that the user uses the decimal only once
$(document).ready(function(){
allButtons.on("click", function(){
var content = $(this).html();
// special cases
switch (content) {
case "=":
computeAnswer();
break;
case "AC":
pressed = "0";
break;
case "CE":
removeLastPressed();
break;
case "Ans":
if (lastPressedOperation()) {
pressed += ans;
}
if (pressed == "0") { // if refreshed by pressing AC
pressed = ans;
}
break;
default:
var val = $(this).attr("value");
console.log("You pressed " + val);
if (val == null) { // if its an operation
if (!lastPressedOperation()) { // if allowed to press operation agai
Solution
Edit: you should wrap it in this:
The
The
You should use strict mode all the time, in development and production, unless you need a 0.01% edge case where part of your file has to be non-strict. If you use Babel it outputs code in strict mode.
HTML structure. The usual way is:
But the `
;(function () {
'use strict'
// all your code goes here
}())The
;(function () { }()) bit is known as an IIFE (immediately-invoked function expression). It stops variables from leaking into global scope. This is only a problem in browser JavaScript; in Node.js top-level variables don't leak into global scope.The
'use strict' directive tells the engine to run the code in strict mode. In a nutshell, strict mode throws more errors, prohibits the dreaded with statement, and throws an error if you try to assign to an undeclared variable. It's useful for finding mistyped variables:;(function () {
let foo = 42
fooo = 43
console.log('foo is', foo) // foo is 42
}())
;(function () {
'use strict'
let foo = 42
fooo = 43 // Throws an error
console.log('foo is', foo)
}())You should use strict mode all the time, in development and production, unless you need a 0.01% edge case where part of your file has to be non-strict. If you use Babel it outputs code in strict mode.
HTML structure. The usual way is:
Blah blah blah
But the `
, , and tags are optional, so you cam leave them out if you want.
.buttons:hover {
cursor: pointer;
background: #CBE32D; !important
}
The !important goes before the semicolon. But try to avoid using !important, as it can make things messy.
Also, you can set cursor: pointer on .buttons instead of on .buttons:hover. There's no visual difference, except for the specificity of the selectors.
#equals {
border: solid;
border-color: #092352;
border-width: 7px;
}
can be written with the shorthand border property:
#equals {
border: 7px solid #092352;
}
return lastPressed == "x" || lastPressed == "+" || lastPressed == "-" || lastPressed == "/" || lastPressed == "%";
can be written as:
return ["x", "+", "-", "/", "%"].indexOf(lastPressed) > 0
or (ES2016 and newer):
return ["x", "+", "-", "/", "%"].includes(lastPressed)
Some people prefer not to indent switch statements, so instead of this:
switch (foo) {
case 1:
doSomething()
break
case 2:
doSomethingElse()
break
}
do this:
switch (foo) {
case 1:
doSomething()
break
case 2:
doSomethingElse()
break
}
It can avoid over-indentation. It's just a matter of style.
Avoid the == operator most of the time, use === instead. == does loose equality, which means it converts things between different types, and it can do the opposite of what you expect. === does strict equality, which means it returns true if the two things are the same (except for NaN). It does what you think it'll do.
There is one good reason for using ==: foo == null is a shorter way of writing foo === null || foo === undefined`.Code Snippets
;(function () {
'use strict'
// all your code goes here
}());(function () {
let foo = 42
fooo = 43
console.log('foo is', foo) // foo is 42
}())
;(function () {
'use strict'
let foo = 42
fooo = 43 // Throws an error
console.log('foo is', foo)
}())<html>
<head>
<link rel="stylesheet" href="foo.css">
<title>Blah blah blah</title>
</head>
<body>
<!-- main page content goes here -->
<script src="foo.js"></script>
</body>
</html>.buttons:hover {
cursor: pointer;
background: #CBE32D; !important
}#equals {
border: solid;
border-color: #092352;
border-width: 7px;
}Context
StackExchange Code Review Q#129809, answer score: 2
Revisions (0)
No revisions yet.