Variable changes by itself [duplicate] - javascript

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 5 years ago.
I have a small problem trying to code a snake game in js.
I have this function:
function move() {
var aux = [];
aux = snake.position[snake.position.length - 1];
console.log(aux);
if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
};
console.log(aux);
//updateSnake();
snake.position[snake.position.length - 2] = aux;
updatePosition(snake.position);
};
The problem is that aux is changing itself without me doing anything to it, as you can see. The value from the first console.log is different from the second one! It's not like I'm changing its prototype.
Can you guys help me?

if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
}
The above line is what changes the array aux. The first console.log() returns [10,12] as stated in the above comments. After that, the if statement is incrementing snake.position[snake.position.length - 1][1], which is the value of the variable. When calling console.log() for the second time, the variable aux is evaluated as [10,12+1], equivalent to [10,13], which is the expected result.

Related

Sorting Object Arrays With JavaScript [duplicate]

This question already has answers here:
Why is one string greater than the other when comparing strings in JavaScript?
(5 answers)
How does sort function work in JavaScript, along with compare function
(7 answers)
Closed 4 years ago.
I have an array:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]
and I want to sort cars object on type using this code
function myFunction() {
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayCars(); // a function to output the result
}
x and y in this function is either saab, bww or volvo. How is it possible to compare (saab < bmw). I mean they are not numbers to be compared and return another number.
How does if conditional statements compares two strings rather than comparing numbers? and why does it has to return -1, 1 and zero?
Are you asking why this works?
If so, it works because JavaScript has some awareness of lexicographical order. B comes before S and S comes before V and so on.
-1 means that variable a should be moved one index lower than variable b.
1 means that variable a should be moved one index higher than variable b.
0 means that variable a should not be moved.

Postfix operator in JavaScript [duplicate]

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 4 years ago.
This is a basic JS question I think, but I just couldn't find an answer that I was satisfied with. I'm learning operators in JavaScript and I can't understand this following postfix example and how it works:
var x = 4;
var y = x++;
For example, when I alert x, it gives me 5. But when I alert y, it gives me 4. And I can't understand the logic behind it.
I understand that, because it's a postfix, x is assigned to y. And y reads just x, without the postfix. But why does then the original x read the postfix instead if I'm applying it to a different var?
If I just did var y = x + 1, the original x would stay unchanged. But that's not the case when I use postfix. Why would I even change the x with this method? Couldn't I just go then var x = 4; x++; ? And not bother changing it via another var?
I apologize if this is too basic and thanks in advance!
It's easier to think of the increment operators as little functions that return something. So x++ is a functions that increments x and returns the original value of x, whereas ++x does the same thing but returns the new value.
This comes in handy from time to time especially in loops where you want precise control of the stopping point. For example, compare:
let i = 0, j = 0;
while (++i < 5) {
console.log(i) // stops at 4
}
while (j++ < 5) {
console.log(j) // stops at 5
}
The difference is because the while loop evaluates one before the increment and the other after.
Similarly in recursive functions you'll often see things like:
function recurse(i) {
if (i == 5) return i
console.log(i)
return recurse(++i)
}
console.log("final: ", recurse(0))
But if you use the postfix return recurse(i++) you get infinite recursion.
Why would I even change the x with this method?
For some funny shortforms like:
const array = [1, 2, 3];
let i = 0;
while(i < array.length) console.log(array[ i++ ]);
Couldn't I just go then var x = 4; x++; ?
Yeah or just prefix, like ++x or just x += 1 which is more appropriate in most cases.

This Javascript if statement won't run when using not operator? [duplicate]

This question already has answers here:
Is there a “not in” operator in JavaScript for checking object properties?
(6 answers)
Closed 5 years ago.
I'm trying to return an object with each letter from a string as a key, and each key's value being the amount of times that letter appears.
The if statement doesn't seem to execute, I think it's a problem with the not operator because I can get it to execute if I remove it and put the letter in the object so that it evaluates to true.
function multipleLetterCount(str){
var countObj = {};
for(var i = 0; i < str.length; i++){
//Why won't this if statement run???
if(!str[i] in countObj){
countObj[str[i]] = 1;
} else {
countObj[str[i]]++;
}
}
return countObj;
}
multipleLetterCount("aaa")
It returns {a: NaN}
You need to wrap your condition with the negation operator (!)
if(!(str[i] in countObj))
Or even better, invert your condition:
if (str[i] in countObj) {
countObj[str[i]]++;
} else {
countObj[str[i]] = 1;
}

Why is the argument passed in to my recursive function not updating its value? [duplicate]

This question already has answers here:
What does x++ in JavaScript do?
(4 answers)
Closed 5 years ago.
I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
var recursive = function adder (x) {
x = ++x
if (x < 10) {
console.log('x is now: ' + x)
adder(x)
}
return x
}
console.log(recursive(5))
This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?
x=++x;
x+=1;
x++;
++x;
You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1
Some ongoing explanations:
var recursive = function adder (x) {
++x;
if (x < 10) {
console.log('x is now: ' + x)
return adder(x); //lets return our added result
}
return x;//if x=10 lets return 10
}
console.log(recursive(5))//will log 10
It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
obj.x++;
if(obj.x<10){
adder(obj);
}
}
var test={x:1};
adder(test);
console.log(test.x);

difference between a++ and ++a in while loop [duplicate]

This question already has answers here:
Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?
(3 answers)
Closed 6 years ago.
i am trying to figure out, why do i end up with different outcome, when i use a++ versus ++a in a while loop? i know that they are postfix and prefix operations but still do not get why i am getting the results i get
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
i ger results: 1, 2, 2 , when using ++a instead of a++ i get different outcome.
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
in this case i get 1,2,3.
can someone explain operations order step by step and why do i get the output i get?
You'll only get 1,2,2 or 1,2,3 if you run this in the console - outside the console both will only output 1,2 - check the console when running this fiddle
When running in the console, the last number you see in the console is the "result" of the last operation ... so, 2 (because of post increment) in the first case, and 3 (because of pre increment) in the second -
if you add ONE line after the } with just a; - both will show 1,2,3 - like so
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
a;
and
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
a;
shows that a is the same after the while loop finishes

Categories

Resources