Hi all, just a curious question (code passed fine).
In part of the suggested code when entering the Slalom level I see that the var keyword is not used to define the first gem for the first time. Even though the code worked fine, I was wondering why var was not used, is this because it’s within the scope of a while loop? Or the var keyword is just to make code easier to read and JS doesn’t care either way?
gems = this.findItems();
while (this.pos.x < 20) {
// move() takes objects with x and y properties, not just numbers.
this.move({'x': 20, 'y': 35});
}
while (this.pos.x < 25) {
// A gem's position is an object with x and y properties.
gem0 = gems[0];
this.move(gem0.pos);
}
With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables.
By simply assigning it a value. For example, x = 42. This always declares a global variable and cannot be changed at the local level. It generates a strict JavaScript warning. You shouldn’t use this variant.
With the keyword let. For example, let y = 13. This syntax can be used to declare a block scope local variable. [Note: let doesn’t yet work in CodeCombat, I think.]
The main point is that declaring a variable without the var keyword in JS is discouraged.
If points 1 and 2 are unclear, here’s an example:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
function x() {
y = 1; // global, can be seen throughout the code
var z = 2; // local to the function, can only be seen inside x()
}
x();
console.log(y); // logs "1"
console.log(z); // Throws a ReferenceError: z is not defined outside x