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

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.

Related

Strange js eval/template strings behaviour

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})`);});

How to understand Javascript in deep with var scope & closure? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 6 years ago.
I just can't understand why the the a1 = function ?
and where is my value 1 that was passed to the fn(),
whether it was overrwrited by var a ?
the problem look like caused by the same names( var & function) !
function fn(a) {
console.log("a1 = " + a);
var a = 2;
function a() { }
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
function fnx(ax) {
console.log("a1 = " + ax);
var ax = 2;
function b() { }
console.log("a2 = " + ax);
}
fnx(1);
// a1 = 1
// a2 = 2
/* it equal to the final version */
function fn(a) {
var a;
a = function() { }
// function hoisting > variable hoisting
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
I just can't understand why the the a1 = function ?
Function declarations are:
Hoisted to the top of the function they appear in
Declare a local variable (with the same name as the function) in the scope of the function they appear in (this isn't relevant because argument definitions do that too)
Assign themselves as the value of that variable
and where is my value 1 that was passed to the fn(),
Overwritten by the function declaration
whether it was overrwrited by var a ?
The var is ignored because there is already a local variable named a.
The assignment overwrites the function between the two console.log statements.
Your code is effectively the same as:
function fn(a) {
a = function a() { };
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);

about a javascript scope issues. why the result is undifined

I want to know why alert x is a 'undifined', why is not 10.
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
var x = 20;
foo.call(); //10
})();
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
// var x = 20; // Comment this variable
foo.call(); //10
})();
when you define variable name x and assign some value then this function is call and in all other alert you define as like window, this but when you give alert only x then in jquery it will not able to which x you want alert
and in jquery window.x it will take that first x value same in first function "foo" but in second function where x is define after alert so alert is undefined
if you give alert on x then it will give undefined because you also define same variable after alert in that function
This caused because of a feature of javascript called variable hoisting link.
So when the interpreter is interpreting your code, this occurs at runtime.
var x = 10;
function foo(){
alert("foo---" + x);
};
(function(){
var x;
alert("this === window---" + (this === window));
alert("window.x---" + window.x);
alert("this.x---" + this.x)
alert("x---" + x); //undifined ? why
x = 20;
foo.call(); //10
})();
As you can see from above, the variable declaration var x is moved to the top leaving the assignment. Therefore, when you call alert("x---" + x) the variable x is not yet defined.

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.

Passing value from inside of function to a parameter in JavaScript

I have a function that replaces characters from a string
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/\./g, ', ');
var final = "[[" + s + "]]";
alert(final);
}
What I need is to get the value of final outside the function like this:
var outsideValue = final;
EDIT!!! --
function ratko() gets it's value from ajax
success: function (data) {
if (data.success) {
alert("Note: This month has " + data.holidays.length + " holidays.");
praznici = data.holidays;
ratko(praznici);
}
else {
alert(data.ErrorMessage);
}
Possibility 1:
function ratko (a) {
...
return final;
}
var outsideValue = ratko (...);
Possibility 2:
var final;
function ratko (a) {
// no var final declaration here
...
}
...
ratko (...);
// now final has the value assigned to it in the function
You can access variables declared in an outer scope in an inner scope, which is what you do in Possibility 2.
One option would be to use a global variable, just declare it outside of the function.
var myvar = 1;
function myFunction()
alert(myvar); // 1
}
You can read more on javascript variables here.
You declare it outside the function scope:
var finalVar;
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
finalVar= "[[" + s + "]]";
alert(finalVar);
}
var outsideValue = finalVar;
Beware final is a reserved keyword in Javascript. I changed its name.
Besides that, keep in mind that Javascript is always parsed from top to bottom. So using a variable before declaring it will definitely give you an undefined.
you must be modify your function code like this
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
var final = "[[" + s + "]]";
//alert(final); comment this code line and replace this with the code above
return final;
}
after you can call your function ratko with this simple code
var inputValue = 'simple message';
var parsedValue = ratko(inputValue);
you find the final value into a new variable parsedValue

Categories

Resources