Need lexical context in eval for Javascript - 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?

Related

Adding numbers within a function

So what i'm trying to do is to call a function using onclick and when that function activates the total will add 5 on to itself e.g. 0+ 5 = 10, then when called again it will remain at 5 and do 5 + 5 = 10, 10 + 5 = 15 etc.
var total = 0;
function addFive(){
var a = 0;
var b = 5;
var c = a + b;
alert(c)
var total = total + c;
alert(total)
}
<input type="button" value="£5" onClick="addFive()" id="butFive">
var total = total + c;
Using var declares a new variable (with the same name) in the current scope. It masks the total in the wider name.
Don't use var here.
var total = 0;
function addFive() {
var a = 0;
var b = 5;
var c = a + b;
total = total + c;
console.log(total)
}
<input type="button" value="£5" onClick="addFive()" id="butFive">
Variables in javascript has function scope. It means, that defining variable inside function hides global definition. In your case, first declared total variable has global scope and then you hide it inside your function.
In fact, you are assigning value to local, each time created variable.
To solve your problem, try:
total = total + c;

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 + "`"));

why do i have to declare javascript variable with an empty value?

why must i declare the var msg = ' '; and not just var msg; and also why msg += 'Round ' + roundNumber + ':';' and not just msg = 'Round ' + roundNumber + ':';.... why should i add + sign before equals ?
var score = [24, 32, 17];
var arrayLength = score.length;
var roundNumber = 0;
var i;
var msg = '';
for (i = 0; i < arrayLength; i++) {
roundNumber = (i + 1);
msg += 'Round ' + roundNumber + ':';
msg += score[i] + '</br>'
}
document.getElementById('answer').innerHTML = msg;
output of the above code:
Test 1:24
Test 2:32
Test 3:17
output of the code when msg is declared only rather than giving an empty value and assigning msg without the plus (+) sign:
Test 3:17
You have confused a number of Javascript concepts.
Firstly, Javascript variables must be declared but do not have to be initialised. To declare a Javascript variable, you use the var keyword. For example, var msg; is valid Javascript code. As well as declaring a variable, you can optionally initialise it using an = sign. So, for example, var msg = ''; declares the msg variable and initialises it to an empty string. Importantly for you, if you do not initialise a Javascript variable, it is set to a special type of variable called undefined.
The second Javascript concept you have confused is assignment and calculation. In Javascript, you use the = sign to assign a value to a variable. So, for example x = 1; sets the value of the x variable to 1. The += operator is a shorthand operator. So, x += y; is exactly the same as x = x + y;. The crucial difference is that the = operator overwrites the existing value of the variable, whereas += uses the existing value to calculate a new value.
So, in the specific case of your code, you have used the += operator on the msg variable. As explained, the += operator performs a calculation on the existing value of the variable. So, this is why you had to initialise your variable when you declared it - otherwise you would have been performing a += on an undefined variable - which, in your case, does not perform the string concatenation that you expected.
The specific instances on when you should use what very much depends upon what the goal of your code is.

Can eval() Do Calculus?

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

What happens if a JavaScript variable is re-initialized?

I'm new to javascript and I'm not sure if there is anything called re-initialization in javascript, so please excuse if there is no such concept.
What happens if a javascript variable is re-initialized?
Ex:
function foo()
{
var x = 10;
.... //do something
.... //do something
.... //do something
var x = 20;
console.log("x: " + x);
}
What would be the value of x here?
x will be 20. var is "hoisted" (more below), which means that the variable gets declared as of the beginning of the function, before any step-by-step code is run. Any initializer on a var statement is actually just an assignment statement.
So your code:
function foo() {
var x = 10;
//do something
var x = 20;
console.log("x: " + x);
}
is treated as though it were like this:
function foo() {
var x;
x = 10;
//do something
x = 20;
console.log("x: " + x);
}
When you call a function, the JavaScript engine does several things before it starts executing the step-by-step code in the question. one of the things it does is look through the code and process any var statements. (Although it's called the var statement, var is more of a declaration.)
It's quite fun, your code could also be written this way:
function foo() {
x = 10;
//do something
x = 20;
console.log("x: " + x);
return;
var x;
}
It would still be valid, and it would do exactly the same thing.
More (on my blog): Poor, misunderstood var
ES6 will introduce let, which behaves differently (amongst other things, it is scoped to the block it's in, whereas var is scoped to the function as a whole even if declared within a block); details on MDN.
The var keyword essentially just determines the scope of the variable and is handled before any of the code is actually executed (look up "hoisting"). Using var twice for the variable is redundant, but doesn't really do anything in particular. In the end you're just assigning 10 to x and later you assign 20 to x; nothing more, nothing less.
You can always run simple test to check that. var means it's this variable is in current scope. So in your example x will be equal to 20
var x = 10;
var x = 20;
var y = 10;
function Test() {
var x = 30;
y = 20;
alert('X in function: ' + x);
alert('Y is global, so it\'s ' + y);
}
Test();
alert('X outside of function: ' + x + ', also Y = ' + y);

Categories

Resources