Can eval() Do Calculus? - javascript

I'm making a calculator, and I was just wondering if you could have eval() do calculus. I just thought that it would be cool if it could. Thanks in advance!

Try,
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:- 200 4 27
Thanks,
Abhilash

eval function evaluates javascript so yes, it will do what you are asking. However, you are most likely do not even need to use it.
Do not call eval() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
reference

Related

Unexpected result (NaN) when using parenthesis in a Javascript calculation

I am trying to do a very simple calculation of 11.000 + 5.000 expecting to have 16.000 then dividing it by 2 expecting to get a final result of 8.000. It was working ok in another language (ahk) but I'm having unexpected results trying it in javascript (Not a Number, 5.5 and 5.50025)
How should I write this calculation to get the expected result of 8.000?
var A = "11.000";
var B = "5.000";
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000
Here A + B is doing actually string concationation not simple addition. you need to change them to number first
var A = "11.000";
var B = "5.000";
var resultA = ((+A) + (+B)) / 2;
console.log(resultA);
// You can use toFixed if you three decimal digit
console.log(resultA.toFixed(3));
Here A and B are in string format and Once you do A + B the result will be "11.000" + "5.000" = "11.0005.000" (string concatenation). So to get expected result you should parse each string value to Float/Int then do the addition operation.
Try, var resultD = (parseFloat(A) + parseFloat(B)) /2
Just remove the quotation marks and the vars will be recognized as number not as string so you'll get the expected result.
var A = 11.000;
var B = 5.000;
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000

Execute string comma character ',' as code

I have this code block:
var comma_decoded = window.btoa(',');
var comma_encoded = window.atob(comma_decoded);
var log = eval(comma_encoded);
var x = 1 log y = 2;
console.log(x + ' ' + y);
but, I can't execute ',' character as code.
I need '1 2' output, so log variable must work like comma (,)
Thank you.
In javascript, you cannot use variables as operators or language-specific tokens.

Converting Strings to Template Literals in ES6

Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));

How can I create a random math statement and have the computer solve it? [duplicate]

This question already has answers here:
How to take plus sign in variable
(4 answers)
Closed 7 years ago.
a = Math.random();
b= Math.random();
az = Math.round(a);
bz = Math.round(b);
var chooseoperator = ['+','-','*','/'];
var operator = chooseoperator[Math.floor(Math.random() *chooseoperator.length)];
var final=az+operator+bz;
alert(final);
So the computer alerts,"1-0" or something similar.
How can I make the computer solve it?
You should use eval:
alert(eval(final));
If you do not want to use eval because it runs the whole parser for such simple task you can use a simple switch.
BTW: final is a reserved word, do not use it as a variable name.
a = Math.random();
b = Math.random();
az = Math.round(a);
// to avoid division by zero
bz = Math.round(b) + 1;
var chooseoperator = ['+','-','*','/'];
var operator = chooseoperator[Math.floor(Math.random() *chooseoperator.length)];
var Final=az+operator+bz;
alert(Final);
var result;
switch(operator){
case '+' : result = az + bz;
break;
case '-' : result = az - bz;
break;
case '*' : result = az * bz;
break;
case '/' : result = az / bz;
// if you do not want the addition of 1 above
// check the result for "Infinity" and(!) "NaN" here, e.g.:
// if(Math.abs(result) === Infinity || isNaN(result)){
// alert("Division by zero")
// }
// "isNaN" checks for "0/0" and "Infinity" checks for x/0
break;
default: alert("something unexpected happend");
break;
}
// the result is now in the aptly named variable "result"
alert("result = " + result);
Oh, I am too slow, it seems.

Need lexical context in eval for Javascript

I am writing a string parser that takes input like "{x} + 20" and evaluates the lexical value of x with the sum of 20 and returns. So
var x = 10;
var new = eval("{x} + 20".replace("/\{(\w+\}/g", "$1"));
and here "new" should equal 30.
How can this be done?
I believe you just do this:
var x = 10
var y = eval("x + 20")
No?

Categories

Resources