Variable initialization using increments - javascript

is it possible to initialize a variable by incrementing it? Here's an example of what i mean:
In this example, x has not been initialized yet
>x += 1
>print(x)
1

No, that code is not guaranteed to work in all ECMAScript (JavaScript) interpreters.
Most engines should throw a ReferenceError, saying "x is not defined". Even a permissive interpreter that might declare x automatically for you would define it as "undefined" and undefined + 1 is NaN, not 1.

No. That's not possible in JavaScript. Variables must be declared before they can be used / incremented.

var x = ++x || 1;
On the initial run, x is undefined, first part of the OR will be false, though the second one will be used.
On any consecutive run the first part of OR will be used, while the second one will be ignored.

Related

Why does this expression result in `ReferenceError`?

Why does incrementing the same thing behave differently when I reference it via a variable?
function f() {
return {};
}
let x = {};
x++; // OK
(f())++ // ReferenceError
The difference is due to that when js is evaluating the expression it starts by checking if the left hand side is convertible to a number and by quirkyness an object is converted to Nan whereas a function is is not and js throws an exception when trying to convert it before it is evaluated.
See also here:
https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-postfix-increment-operator
This whole code doesn't make any sense. You cannot increment a object.

Javascript while command failed

I'm really new to JavaScript, so I tried to make a super simple until command, but it didn't work.
var sunSize = sunSize;
while(sunSize<300) {sunSize+1};
You have 3 mistakes:
You initialize sunSize incorrectly. It needs to be set to some value; if you just do sunSize = sunSize it will result in it being undefined.
Instead of sunzize+1, you need to do sunSize = sunSize + 1 or sunSize += 1 or sunSize++. This will increase sunSize by 1 which is what I assume you were trying to do.
A while loop doesn't require a semicolon at the end, but a declaration does. Therefore I just moved the semicolon inside the while loop.
Below is working Javascript code:
var sunSize = 1;
while(sunSize<300) {sunSize++;}
console.log(sunSize);
// Logs 300
so for starters you are trying to initialize sunSize to sunSize, which you can't do because it doesn't exist yet. So first initialize it to a number, say 0 or whatever. Also, try not to use the 'var' keyword, use 'let' (if the variable is going to be changed) or 'const' (if the variable is not going to change). In this case you're updating the variable inside your loop so use 'let' like this:
let sunSize = 0;
Second, 'sunSize+1' is not proper syntax; what you want is either +=1, or ++:
while (sunSize < 300) { sunSize++; }
Hope this was helpful! Welcome to javascript!

Ternary operator doesn't handle post-increments as expected

So this may be a silly question, but I've been running into this syntax mistake every now and again and can't seem to learn my lesson - because I simply don't understand why this doesn't work.
For some reason the ternary operator won't handle increments or decrements.
In the console, I found these results:
// Firstly
var iteration = undefined;
// Expected increment, unexpected result
iteration = iteration == undefined ? 0 : iteration++; //returns 0 every time
// Then I thought maybe ternary doesn't return assignments
iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration
// Works as expected
iteration = iteration == undefined ? 0 : iteration+1; //increments iteration
While searching for answers I found another user had the same experience with the unexpected behavior.
After more searching I found that the pre-increment works fine:
iteration = iteration == undefined ? 0 : ++iteration; //increments iteration
And came across this answer when trying to determine why the pre-increment works.
It does make sense to me why it works and post-increment doesn't - kinda. I suppose at some point the incremented value could be overwritten by the initial value if the ternary order of operations works that way, but that's all I can think of.
But really the expected behavior that I would have from the post-increment would be for iteration to be returned, and then for it to be iterated...after.
For example, this bit of code:
var bar = undefined;
//foo is set immediately and bar is incremented after it is returned
foo = bar == undefined ? bar=0 : bar++; //sets foo to be what bar was before the increment
Hopefully you have been able to bear with me here. I do understand that at this point after finding many reliable and straight forward ways to get the job done that I don't need an answer, but I'm just stumped why it works this way.
Question:
Why does the ternary operator not update the post-increment (or postfix) value returned - after it has been returned?
A comment on this answer states that
counter++ evaluates to the current value of counter, then increments it. You would be assigning the old value of counter back to counter after you've incremented.
but I still don't why the order of operations behaves this way.
Another helpful Pre-increment vs Post-increment for C++ (ironically hilarious answer)
Whether the interpreter runs across an expression invoking pre- or post-increment, the variable is reassigned immediately, before the expression is resolved. For example:
iteration = iteration == undefined ? 0 : iteration++;
is like
function doPostIncrement() {
const preIncrementValue = increment;
increment = increment + 1;
return preIncrementValue;
}
iteration = iteration == undefined ? 0 : doPostIncrement();
Also, assignments resolve to values, so
iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration
is like
function addOneToIncrementAndReturnIncrement() {
increment = increment + 1;
return increment;
}
iteration = iteration == undefined ? 0 : addOneToIncrementAndReturnIncrement();
It's not actually a function call, but it's not that dissimilar, in that the reassignment is done before the function resolves, or before the pre / post-increment expression resolves.
In an assignment expression, the entire right hand side gets evaluated first, and its resulting value is assigned to the left hand side. That means the post increment expression needs to be evaluated and turned into a value first, which will be assigned to the left hand side afterwards. The post increment operator doesn't know what larger expression it's a part of. It will be evaluated atomically. I.e., it won't first return its value, then complete the assignment operation, and then complete the post increment operation. When evaluating the expression iteration++, the value of iteration will be incremented and the expression results in the original value of iteration, all at once.

Why is it that Javascript variables are created undefined even if they don't pass if statement?

Take this for example.
if (b) b = 1;
Reference Error. b is not defined. Makes sense but if I do this...
if (b) var b = 1;
I get undefined in console. and now when I look up what b is it shows as undefined.
If I try to do the same if statement again, it doesn't pass because b is neither true or false, it is undefined, but I guess my question is why does it show up as undefined? Does Javascript go through the if statement regardless if the if statement passes or fails? Thanks.
All vars gets hoisted to the beginning of the scope they are in, initialising their values to undefined. The value is then set when execution reaches the line the var was in originally.
In your second example, b gets initialised as undefined before the if is encountered, due to the var. Think of it as the same as writing the following
var b;
if (b) b = 1;
After this code is executed, b will still be undefined because it will never run into the if block as the initial value is falsy.
As mentioned by pst, this is a language specific feature of JavaScript, so don't expect the same behaviour when writing code in other languages.
JS is not going thru the if statement, but rather it's reading the if part of the statement, and since b is not defined anywhere but within the if statement, you get undefined.

"var variable" returns undefined?

When I run "var variable = true;" in chrome console I get "undefined" returned:
> var variable = true;
undefined
But when I run without "var" it returns true:
> variable = true;
true
Why is it returning "undefined" with "var"?
It's confusing cause I expected it would return true.
The first is a statement, while the second is an expression. While not quite the same, it is similar to C's rules:
// A statement that has no value.
int x = 5;
// An expression...
x = 10;
// ...that can be passed around.
printf("%d\n", x = 15);
var x = y; is a statement which returns no value. In the WebKit JS console, a statement that returns no value will show undefined as the result, e.g.
> if(1){}
undefined
> ;
undefined
> if(1){4} // this statement returns values!
4
The assignment is an expression which returns the value of the LHS. That means, this expression statement has a return value, and this will be shown.
An assignation returns the assignation's value, but with var this return is "consumed" (?)
Statements always return undefined.
var color = "red";
undefined
Expressions always return a value.
color = "orange";
"orange"
I'd like to point out, that the answer provided by kennytm should be the accepted answer, at least for pedagogical purposes. The accepted answer doesn't answer why this is the case or provide deeper understanding.
Like the null value in JavaScript, undefined indicates absence of value, but in a much deeper way. The following should be taken as complimentary to the above-mentioned answers:
undefined is the value of variables that haven't been initialized and the
value you get when you query the value of an object property or
array element that doesn't exist. This value is also returned by
functions that have no return value, and the value of function
parameters for which no argument is supplied. undefined is a predefined
global variable (not a language keyword like null) that is initialized
to the undefined value.
You might consider undefined to represent a system-level, unexpected,
or error-like absence of value and null to represent program-level,
normal, or expected absence of value.
-- Flanagan, David. JavaScript: The Definitive Guide: Activate Your Web
Pages (Definitive Guides) . O'Reilly Media. Kindle Edition.
Also, makes sure to check out both the accepted and the second most voted answer for further reference:
Chrome/Firefox console.log always appends a line saying undefined

Categories

Resources