Javascript variable setting values, trying to understand meaning [duplicate] - javascript

This question already has answers here:
Using comma in Javascript variable declaration [duplicate]
(2 answers)
Closed 1 year ago.
Can someone please explain the below code for me?
Is the line setting multiple variables at the same time? If so, what is are they?
If it is setting multiple variables, I would have expected all the items to be X=Y, but instead I get random variables within the line, like reevVal, mmareev, amareev, fvVal.
Any help is greatly appreciated.
var balance = $(".input-balance"), value = $(".balance-value"), reevVal, mmaVal = $(".mma-val span"), mmareev, amaVal = $(".ama-val span"), amareev, triggerPlus = "false", triggerMinus ="false", fvVal;

var x = 0, y, z = 1
is equivalent to
var x = 0;
var y; // undefined
var z = 1
There's also the similar, but different, comma operator that lets you "group" up multiple expressions into a single expression. The value of the last sub-expression is returned, but all sub-expressions are evaluated:
let x = (5, doSix(), 7); // x = 7
x = 8, doNine(), 10; // 10
Note the parens are necessary in the 1st line above to make it clear it's a single declaration and not a list of declarations like in the 1st example. The parens aren't necessary in the 2nd line, since there's not let|var|const so it's not a declaration, but an assignment.
In practice, it's most common in for loops where you're constrained to a single expression:
for (let i = 0, j = 10; i < j; i++, j--)
console.log(i, j);

Related

How to access a constant nested function's parameter in javascript?

I was asked this question in an assessment I took and was not able to figure it out. Would like to know possible solutions.
Question:
Write one Javascript statement on the indicated line that will make the printed number always be between 10 and 20.
let x = 2;
let y = 8;
const a = function(b) {
return function(c) {
return x + y + Math.abs(b) + c;
};
};
// Statement will go here
const fn = a(x);
x = 4;
console.log(fn(Math.random() * 10));
I've tried assigning different values to variable y. But I think the culprit is to know what variable c would be in the nested function. Note that c would always be a number between 0 and 10 (as Math.random() is between 0 and 1, then multiplied by 10).
You already concluded correctly that the argument passed to fn is a random number between 0 and 10, which is c in the expression that the call to fn will evaluate: x + y + Math.abs(b) + c
So if fn must return a number between 10 and 20, then x + y + Math.abs(b) must equal 10.
We also see that the global variable x is set to 4 at a time that we cannot change it any more, but still before the call to fn, so that means y + Math.abs(b) must equal 6.
Now this gives us already a hint: as it stands, y is 8, which makes the conclusion in the previous paragraph impossible. So we must alter y. It is not yet too late, since the value of y will only be read when fn is called.
So what is Math.abs(b)? The local variable b is set when a is called. a is called with x, which at the time of that call is still 2. So Math.abs(b) is 2, and so we can derive that y must be 4.
One obvious way to make y to be 4 in one line:
y = 4;
(Alternatively, y-=4, y>>=1, y/=2, y^=12, ...etc)
If you want to provide a creative answer, try:
Math.random = function() { return 1.345; };

Counter variable in for/loop. Why does one program work and the other fails? [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 7 years ago.
So, in writing a program - in javascript - that sums numbers from 1 to N (number given by user), I have written a working program, but I am still confused as to why one proposed solution that I wrote works, and the other doesn't.
This version works:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = 0;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
This one does not:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = theNum;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
Why doesn't the second one work? If I initially set var onwards as theNum (inputted by a user) and then have the function add onwards to the iterations of 'i' up until the counter reaches theNum, I will see a concatenation between theNum and all the iterations of i next to it, like it is a string. In my mind, setting a variable to the same value and then having that value change to add the counter's iteration should work! Why doesn't it work? Please share.
This is because prompt returns a string, not a number. And when you use "+" operation on a string, you get concatenation, not integer increment. Javascript will not magically convert your string into integer even if it looks like it.

Using the anonymous function in String.replace() method [duplicate]

This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 10 years ago.
I have an array of regular expressions, at the moment just one element in length, and a string which I want to search/replace by looping through the array:
var str = "i am*happy all the*time",
rex = [
/(\S)\s*\*\s*(\S)/g
],
i = 0,
r = rex.length;
This is how I'm trying to achieve this at the moment:
for (i; i < r; i += 1) {
str.replace(rex[i], function(star, p1, p2) {
console.log(i, star, p1, p2);
return p1 + '\\s*(.*)\\s*' + p2;
});
}
The result should be i am*\\s*(.*)\\s*happy all the\\s*(.*)\\s*time. But at the moment, str seems unaffected, even though when I check the console the relevant matches are being made. You can see this for yourself here.
So am I missing something simple, have I misunderstood something about using lambda expressions in String.replace(), or is there something more fundamentally wrong here?
...
EXTRA INFO:
I'm using Chrome 24 right now, in case that's of interest; I had read a while ago that anonymous functions in String.replace() weren't available to all browsers though I assumed that would be resolved by now (the option was introduced in ECMAScript v3).
String.replace() doesn't change the original string, but returns the new one. You should assign the result
for (i; i < r; i += 1) {
str = str.replace(rex[i], function(star, p1, p2) {...})
}

Can I declare the same variable twice in different for loops in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Variable Scope
I have a JavaScript function for HTML select options for days:
// Show and hide days according to the selected year and month.
function show_and_hide_days(fp_form) {
var select_year= $(fp_form).find("select.value_year");
var select_month= $(fp_form).find("select.value_month");
var select_day= $(fp_form).find("select.value_day");
var selected_year= $.parse_int($(select_year).val());
var selected_month= $.parse_int($(select_month).val());
var selected_day= $.parse_int($(select_day).val());
var days_in_month= new Date(selected_year, selected_month, 0).getDate();
// If the number of days in the selected month is less than 28, change it to 31.
if (!(days_in_month >= 28))
{
days_in_month= 31;
}
// If the selected day is bigger than the number of days in the selected month, reduce it to the last day in this month.
if (selected_day > days_in_month)
{
selected_day= days_in_month;
}
// Remove days 29 to 31, then append days 29 to days_in_month.
for (var day= 31; day >= 29; day--)
{
$(select_day).find("option[value='" + day + "']").remove();
}
for (var day= 29; day <= days_in_month; day++)
{
$(select_day).append("<option value=\"" + day + "\">" + day + "</option>");
}
// Restore the selected day.
$(select_day).val(selected_day);
}
My question is - can I declare "var day" twice in two different for loops and what is the scope of this variable? Is it legal and what happens if I declare the same variable twice in the same function? (inside for loops or outside for loops)? For example, what happens if I declare one of the variables again with "var"?
If I don't use "var" at all before variable day in for loops, what will happen?
Thanks,
Uri.
P.S. $.parse_int is a jQuery plugin which calls parseInt with radix 10 if not specified.
Any use of var foo in a function will scope foo to that function. It doesn't matter where in the function this takes place as var declarations are hoisted.
Additional uses of var foo in the same function are syntactically legal but will have no effect as the variable is already scoped to that function.
Since it has no effect, there is a school of thought that recommends against it (and in favour of a single var function at the very top of a function to perform all the scoping) to avoid implying that there is significance to it (to maintainers who are not entirely comfortable with this feature of JavaScript). JSLint will alert you to this usage.
No you shouldn't. Variables declared using var have function scope, not block scope!
Redeclaring a variable using var might suggest that the variable is local to the loop/block when it isn't.
You could, however use let to declare the variable, to ensure it is block-scoped.
for (let x = 1; x <= 3; x++) {
console.log(x)
}
for (let w = 65, x = String.fromCharCode(w); w <= 67; w++, x = String.fromCharCode(w)){
console.log(x)
}
console.log(typeof x) // undefined

Javascript: Comma operator, var, and scope - why does it work the way it does?

The comma operator evaluates each comma-separated operand (and returns the value of the last one).
(i = 1 + 2), (j = 3 + 4);
is functionally equivalent to
i = 1 + 2;
j = 3 + 4;
Also, as far as I know, a statement, such as var, is not considered an operator, but rather part of the operand. (See https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence )
So if each operand is being separately evaluated, why, then, does
function foobar () {
var i = 3, j = 7, z;
}
create 3 variables - i, j, and z - in foobar's scope?
I know that's what actually happens, but I've been wondering for a while why it is that this actually happens. It would seem that i should be in foobar's scope, but that j and z should end up in the global scope.
The commas used in a var statement are not actually comma operators.
Similarly, the commas you use to separate arguments in a function call are not comma operators either.

Categories