-1

I do not really have any knowledge about Javascript other than trial-and-error experience according to the functions I needed. However I'm stuck with my math calculations now, as I need to be able to do calculations that contain unknown variables i.e. var z="z".

Is there any way it would be possible to do the calculation with unknown variables like a normal calculator can?

A simple example of what I need:

var a="a";

var c="c"; 

//a and c should not necessarily be a string

c=50+a-100;

//  output: c=a-50, instead of c= NaN

Any help is much appreciated.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
katrinejc
  • 21
  • 3
  • 2
    Not built into Javascript, however something like [nerdamer](https://github.com/jiggzson/nerdamer) may be somewhat like what you're looking for. – Joachim Isaksson Feb 07 '16 at 16:03
  • 1
    You are using smart quotes: `“ ”` instead of `" "`, which may be causing the errors. – AMACB Feb 07 '16 at 16:04
  • 1
    By "unknown variable" here, do you mean that you want to be able to write an expression involving a variable that *refers to* another variable? If so, then no, you can't do that; that's what functions are for. – Pointy Feb 07 '16 at 16:06
  • 3
    what you're looking for is a way to do symbolic math. This is not a feature in native javascript or really in any major programming language--you need a 3rd party library like Isaksson's link. – Matthew Feb 07 '16 at 16:13

1 Answers1

2

As suggested by others it's not possible to execute the algebraic expression in plain JavaScript but probably you can use algebra.js for this purpose if it fits your requirements. They are providing many features to evaluate algebraic expressions in JavaScript code.

Example output of your expression:

var x1 = algebra.parse("50+a-100");
x1.toString();

Output >> "a - 50"

Check the "Parser" section.

To do experiments visit http://algebra.js.org/ and start writing code in chrome developer console because all required libraries will be present in their own website.

A Google search for "javascript algebraic expression evaluator" can give you more options.

saurav
  • 972
  • 11
  • 24