Strange js eval/template strings behaviour - javascript

Trying to answer a question in stackoverflow, I was doing some tests in my chrome console, and found the following case I am not able to understand.
var vals = ['x','y','z'];
vals.forEach(val => { eval(`var ${val} = 1; console.log('${val} = ', ${val})`);});
How can javascript know when I am refering to ${val} as the val defined in "vals" array, and when I am refering to the value it has stored each value in that array?
I mean, why it does not log:
x = x;
y = y;
z = z;
or
1 = 1;
1 = 1;
1 = 1;

The template string is evaluated first, outside of the context of your eval. So you've effectively done:
eval("var x = 1; console.log('x = ', x)");
eval("var y = 1; console.log('y = ', y)");
eval("var z = 1; console.log('z = ', z)");
Which of course is just printing each variable, along with it's value.
When using eval like that, it would be useful to replace it with a console.log to see what string is actually being sent through to the call:
var vals = ['x','y','z'];
vals.forEach(val => { console.log('eval string:', `var ${val} = 1; console.log('${val} = ', ${val})`);});

Related

Is there a way to add 1 to a variable using "+="? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
I am trying to add a value to a variable using the += function. This is the code I am using:
function getAnswer() {
var num1 = Number(document.getElementById('numone').value);
var num2 = Number(document.getElementById('numtwo').value);
var oper = document.getElementById('oper').value;
var numberOfEquation = 0;
numberOfEquation += 1;
if (oper == '+') {
var p = document.createElement('p');
var txt = document.createTextNode(num1+num2 + ' - Equation ' + numberOfEquation);
p.appendChild(txt);
document.body.appendChild(p);
} else if (oper == '-') {
var p2 = document.createElement('p');
var txt2 = document.createTextNode(num1-num2 + ' - Equation ' + numberOfEquation);
p2.appendChild(txt2);
document.body.appendChild(p2);
}
console.log('You did an equation!');
}
I don't know what went wrong.
It appears to be a misunderstanding of how local variables work.
Local variable:
function x() {
var y = 0;
++y;
return y;
}
x(); // => 1
x(); // => 1
x(); // => 1
This returns 1 each time since var y explicitly declares a local variable. It will only exist during the execution of that function. As soon as the function terminates that variable ceases to exist. When the function starts up again it makes a brand new one.
Here's a different approach with a persistent variable:
var y = 0;
function x() {
++y;
return y;
}
x(); // => 1
x(); // => 2
x(); // => 3
This is because y exists outside the scope of the function. It lives as long as your program does.

What's the best way to allocate the variables with multiple combinations

I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.

FOR LOOP in Angular Service NOT Working - While Loop Works

I've worked around this problem with a while loop
but thought I'd explain it here - because it seems odd
I tried iterating through a string in a service using a for loop, but cannot get it to work
When service defined like this
.service('xtratxt', function()
{
var x = 0;
var a = "";
this.convert = function(srctxt)
{
this.a = "";
this.x = 0;
for (this.x=0; this.x++; this.x<srctxt.length)
{
this.a = ans + "X";
}
return ans;
};
})
if I call this in my controller with
$scope.newvalu = xtratxt.convert("Hello");
I should get back a string of X's Eg XXXXX
Instead I get an empty string ""
If I change to a while loop - no problems works a treat
Anyone know why ?
I get no errors in the console either.
AFAIK it doesn't seem to enter the for loop at all
this.convert = function (srctxt) {
var a = "", x = 0, ans = '';
for (x = 0; x < srctxt.length; x++) {
ans += "X";
}
return ans;
};
Shorter version
var str = 'abcde';
str.replace(/\w/gi, 'X');

For Loop won't exit in Javascript, looping infinitely

My script is causing the browser to freeze and asking me to stop the script. Using firebug I can see the for loop is endlessly looping and not making any progress. Here's the loop:
for (var x = 1; x < 7; x++) {
var y = x; //to stop the value of x being altered in the concat further down
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(y); // mcq_question_id$ctr the question number
console.log("2 = " + questionid);
var mcqid = form[questionid].value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(y); // mcq_question$ctr the questions chosen answer
var chosenanswer = form[answer].value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer, equal); // "&mcq_question$ctr="
if (x = 1) {
send.push(questionide, mcqid, answere, chosenanswer);
}
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
}
Update - Fixed! Silly mistakes are the worst
if (x = 1) {
should be
if (x === 1) {
The === operator compares while the assignment operator = assigns. Many people make this mistake. :)
When the first loop runs, it sets x to zero, and does so infinitely until the process is terminated. That's why the loop doesn't stop.
if (x = 1) { should be if (x === 1) {
Consider switching to an IDE that catches simple programming errors like this.
Looks like you should have "if (x == 1)" instead of "if (x = 1)".
Your code repeatedly sets x to the value 1, rather than checking that it is equivalent to 1.

var x, y = 'foo'; Can this be accomplished?

Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;

Categories

Resources