Imroving the javascript code - javascript

I have a piece of code to calculate power of a number, The code is working fine for me but i am not sure if it is good performance wise.
<html>
<head>
<SCRIPT>
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
var newNumber = number;
for(var i=0; i<(power-1);i++){
newNumber *= number;
}
document.getElementById("output").innerHTML= newNumber;
}
</SCRIPT>
</head>
<body>
<input type="text" id ="number" placeholder="Enter number">
<input type="text" id ="power" placeholder="Enter power">
<input type="submit" onclick = "power()">
<p id ="output"></p>
</body>
</html>
I have changed my code to this -
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
number = Math.pow(number,power)
document.getElementById("output").innerHTML= number;
}

You can use Math.pow(base, exponent):
The Math.pow() function returns the base to the exponent Power, that
is, baseexponent.

I have to point out, that your solution using the for-loop only works when power is a positive integer. It returns a wrong value for all non-integer powers and when power < 1. That is why using Math.pow() is a wise choice.

Your code, if you dont want to use Math.pow is "optimized" you can't get better performance without using Math.pow.

Related

Js String of a minus sign into a minus sign

I want to have a program that turns "-" into an actual minus sign the computer will recognize.
Here is my code:
document.getElementById("answer").innerHTML = (Number(input.substr(Number(input.indexOf("+"))).slice(1)) + Number(input.substr(0, Number(input.indexOf("+")))));
I take it you're trying to build a calculator. I'd personally create different functions for adding, subtracting, etc. You could use eval(), but that's prone to XSS.
Here's a simple calculator showcasing the minus pre-built into the JavaScript calculation, so that you don't have to worry about extracting it from the input:
function add() {
document.getElementById('answer').innerHTML = Number(document.getElementById('input1').value) + Number(document.getElementById('input2').value);
}
function subtract() {
document.getElementById('answer').innerHTML = document.getElementById('input1').value - document.getElementById('input2').value;
}
<input id="input1">
<input id="input2">
<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<div id="answer"></div>
Hope this helps! :)

Javascript Exponents in HTML

I need to create a JavaScript function that uses input=number to pass it to a JavaScript function to raise it to 2nd, 3rd, 4th, and 5th powers. So far I can pass a number to it and out put that number, but can not seem to grasp the math.pow and also how to get all the other powers. Here is what I have so far.
<!DOCTYPE html>
<html>
<body>
<h1>Opponents!? More Like Ex-Ponents</h1>
<input type="number" id="myNumber" value="0">
<p>Click the button to get the exponents of the number field.</p>
<button onclick="myFunction()">Calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
I'm not able to just input values. I need to be able to take a value that was input by the user and do the calculations on it. I've tried this with little results.
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
var y = math.pow(x,2);
document.getElementById("demo").innerHTML = y;
}
</script>
Math.pow works like so:
Math.pow(value, exponent)
so if I wanted to raise 5 by 11 I would do:
Math.pow(5,11)
Just replace the numbers with the variables you're using for value and exponent

Javascript: Add or Subtract to running total

I am very new to Javascript, only a few weeks, and am stuck on something I assume to be simple. I have searched for hours, but cant find an example to point me in the right direction. Im basically wanting to create a simple "Running Balance" calculator. One textbox has the input (added by using add button) and the other textbox has the output. The output should change depending on what I put into the input textbox and keep adding to the value in the output textbox.
Here is my code in Javascript:
var accountBalance = 0;
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
total = parseInt(inPrice += accountBalance);
document.getElementById("outBalance").value = total;
}
and the HTML:
<form id="form2" name="form2" method="post" action="">
<p>
Enter an amount:
<input type="text" name="inAmt" id="inAmt" />
</p>
<p>
Display Balance::
<input type="text" name="outBalance" id="outBalance" />
</p>
</form>
<p><input type="button" id="addBal" value="Add the amount to the balance" onclick="addBalance()"/></p>
I have a feeling my total variable in my function is what I am screwing up. Thanks in advance for the help!!
This part doesn’t really make sense:
total = parseInt(inPrice += accountBalance);
It takes accountBalance (0), appends it to inPrice (since inPrice is a string), stores the value back in inPrice, parses the result as an integer, and sets total to that integer. What you seem to need is pretty much the reverse, that is:
Parse inPrice so that it’s a number instead of a string
Add it to accountBalance and store the result in accountBalance
Put the new accountBalance in total (or just use accountBalance in the first place)
Or, in JavaScript:
var accountBalance = 0;
function addBalance() {
var inPrice = parseInt(document.getElementById("inAmt").value, 10);
accountBalance += inPrice;
document.getElementById("outBalance").value = accountBalance;
}
You've confused a few variables - the problem was you were never reading the current balance and you were resetting the total variable every time (aside from mixing ints and strings). Here is a version without the total variable:
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
accountBalance += parseInt(inPrice, 10);
document.getElementById("outBalance").value = accountBalance;
}
See it here: http://jsfiddle.net/fdureo1s/

JavaScript input text box adding plus number

I have a question regarding the add sign in JavaScript I'm a bit confused on this. I have this input text box which I will be input as 50 and it will add plus 50 . My result in adding the numbers which for example I input 50 the result is 5050 which is totally wrong. Can someone help me on this?
<!DOCTYPE html>
<html>
<head>
<title>activity 2</title>
<script type="text/javascript">
function computeSalary(){
var salaryData = document.form1.salary.value;
var salary1 = salaryData + 50;
document.form1.newSalary.value = salary1;
}
</script>
</head>
<body>
<form name="form1">
Enter the daily salary:
<input type="text" name="salary" /><br />
<input type="button" value="Compute" onClick="computeSalary();" /><br />
<br />
The new salary: <input type="text" name="newSalary" />
</form>
</body>
</html>
You can convert the string value you're getting, which is being concatenated to your value, to a number by simply adding a plus sign:
var salary1 = +salaryData + 50;
jsFiddle example
You have to convert the value you got from the input control to float or integer before adding it using the + operator. The + operator will convert both operands to a same type before adding both operands. This is the primary reason why you got 5050 because the 50 of type int got converted to string.
use this code:
function computeSalary(){
var salaryData = document.form1.salary.value;
var salary1 = parseFloat(salaryData) + 50;
document.form1.newSalary.value = salary1;
}
Change the following line:
var salary1 = parseInt(salaryData) + 50; // Use parseInt or parseFloat
The reason is that JavaScript will coerce strings and integers into strings. So your integer 50 is converted to a string and then concatenated.

Javascript calculation letters and numbers

<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.

Categories