Javascript while command failed - javascript

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!

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.

Change the value of an evaluated var in JavaScript

I have a var containing a JSON string. (Here I won't parse it because it is not the main problem)
var variable = '{"name":"Johnny Appleseed"}';
var string = "variable";
I evaluate the string.
var evaluatedstring = eval(string);
Now I would like to delete the value of the var variable.
variable = undefined;
If I do:
console.log(evaluatedstring)
It works fine and returns me the JSON string as:
{"name":"Johnny Appleseed"}
But if I do:
evaluatedstring = undefined;
Of course it doesn't work.
eval(string) = undefined;
doesn't work either. (Returns the error Uncaught ReferenceError: Invalid left-hand side in assignment)
How can I delete the content that via the evaluated var?
No jQuery, please.
On Chrome 50+ so not a problem with the browser.
If you're working in the browser: Global variables in JavaScript are created as properties of the window object. Therefore, what you're trying to do can be done like this:
var variable = 'some variable';
var variableName = 'variable';
window[variableName] = undefined;
variable === undefined // Will now be true
However, just the fact that this is possible doesn't mean it's a good idea - in fact, it's just the opposite, it's bad style and will probably confuse anyone looking at your program to no end. If this is really necessary for your algorithm to work, you might want to rethink your data architecture. If this is just a scoping issue (you don't want that variable to pollute your global namespace), an IIFE will likely solve your problem.

Why is `s.len` undefined (and not 4) while `s` has the value `test`? - JavaScript

I am puzzled with this one. I have the following code.
var s = "test";
s.len = 4;
var t = s.len;
The question is why the variable t has a value of undefined.
If you check the s.len after that code it is undefined.
If you check s the value is test. Not sure what is going on here. I am sure there is an explanation, but can't get my head around that and don't know how to search that.
For those who consider to vote down. This is a question we got in a course, and we are expected to prepare for the next session with this riddle.
I am not new to programming, but I fail to research how JavaScripts treats this code. It is valid code really, execute it in your Dev Tools and you will see.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
but I fail to research how JavaScripts treats this code.
That is easy: strings are primitive types in JS, which means they don't have properties by themselves.
For . operator to work with them (e.g. for .length call) javascript defines such a thing called "wrapper objects".
So when you try to access a property of a primitive object - a temporary wrapper object is created that does behave as an object, hence you can access and assign properties to it.
The problem is that the wrapper object is temporary, so after it's used to access a property the object is discarded with all its state.
That's why when you assign a .len property you cannot access it on the next line: it's lost.
So a pseudo code for what actually happens behind the scenes for your code is
var s = "test";
(new String(s)).len = 4; // here you add an attribute for a new object
// and `s` is left untouched
var t = s.len;
The question is why the variable t has a value of undefined.
Because you have defined s as a string not as an object. so s.len should be undefined!
I am not sure what are you trying to do. But if you want to get the length of s then t = s.length will simply work.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
You can find the answer from this question
run :
var s1 = "test";
console.log(typeof s1)//string
var s2 = {}
console.log(typeof s2)//object
s1.len = 4;
s2.len = 4;
console.log(s1.len);//undefine
console.log(s2.len);//4

Declare variable based on object value in javascript

Simple issue I ran up against today and can't seem to find a way around it, whatever the solution is it's something I've never learned so leaving me stumped.
For reasons I won't get into, I need to get a value from an object and use it as the name of a new variable. Will be looping through a ton of these so needs to be repeatable. For example from an object like so,
obj = {
"name": "object101"
};
What I want to get out of that is a var declaration in such a way that object101 is the name of the new var,
"var object101 = // stuff"
But "var obj.name = // stuff" is not working, the dot is not valid it seems.
I also tried putting the object101 into it's own var like, var name = obj.name;.
Which holds the content fine. But then I immediately saw the hilarious problem with going, var name = // stuff
It just redefines "name" and is not placing the content of name. It does render right when in a console log like console.log("var "+name+" = stuff"); which is pretty much exactly how I want it to write to the code, but having this issue in the real code with the var being redefined in this case.
So I feel like I am missing something very basic in how you can provide the name to declare a var. Maybe some very simple syntax thing I am missing, or perhaps there is a process out there which will dynamically make a var declaration name based on some other object. I've done my fair share of js and never seen var [complex syntax resulting in name] =, it's always quite simple.
But my searching has drawn a blank so far on this exact issue. Anyone able to enlighten me?
Wow, you really don't want to do what you think you want to do, but here goes.
If you are operating in a browser and you want the variables to be in global scope, fortunately the global scope has a name: window.
You can just do this:
window[obj.name] = 'stuff';
If you want it in in local scope, you can use the almost-forbidden keyword with:
var f = function(obj, b) {
var fake_scope = {};
with (fake_scope) {
fake_scope[obj.name] = b;
console.log(d);
}
}
f( { name : 'd' } , 3 )
will print out 3.
If you need local scope and you don't want to use with, you will have to screw around with eval.
But seriously, if you do this, remember.
Well, in the interest of science:
(function() {
var dynaVarName = 'testName';
eval('var ' + dynaVarName + ';');
eval(dynaVarName + ' = 5;');
eval('console.log(' + dynaVarName + ');'); // => 5
}());
testName // => ReferenceError
So yes, you actually can create a local variable with a name based on an expression. I can't imagine the benefits of doing this though.

Variable initialization using increments

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.

Categories

Resources