How is it possible to equating a variable to the variable itself? - javascript

I came over a JS somewhere in google documentation:
function doGet() {
var feed = UrlFetchApp.fetch('http://xkcd.com/rss.xml').getContentText();
feed = feed.replace(
/(<img.*?alt="(.*?)".*?>)/g,
'$1' + new Array(10).join('<br />') + '$2');
return ContentService.createTextOutput(feed)
.setMimeType(ContentService.MimeType.RSS);
}
First line declares the function. Second line declares the variable "feed". BUT thrid line is equating the "feed" with something "happening with feed".
How is it possible? It's something like declaring, 2 = 2 + 1.
Note: I just know the basics of JS.

At the first line you assign the text that is returned from a call to an API to the variable called feed.
At the second line you assign at the same variable, feed the result of applying a replace in the result you have taken above.
It's just this, nothing more or less.
By the way the operator = is the assignment operator. It is not related with the equality operator.
For further info about the latter, please have a look here.

You can set a variable to a manipulated value of the variable. A simpler example than what you posted would be like this:
var myNumber = 20;
myNumber = myNumber + 20; //returns 40

Related

chrome development console only gives me undefined

I am testing some JS and when I try to get the output in the console I only get "Undefined" Can anyone assist?
enter image description here
There are a few improvements that can be made before your code works.
var upperCaseFirstChar = firstChar.toUpperCase is wrong. It should be .toUpperCase(). The difference is that your code assigns the variable to a function while the new one assigns it to the return value of the function, in this case an uppercase character.
name.slice(1, name.length) is redundant. The slice function will automatically use the full string length in a second parameter is not supplied. Use this: name.slice(1).
After that is done, let's get to your question. The reason it doesn't return anything is because you don't tell it to! All that happens in that code block is the definition of variables. What you actually want is to place capitaliseName at the end of your code, like this:
var name = prompt("Whats your name?");
var firstChar = name.slice(0,1);
var upperCaseFirstChar = firstChar.toUpperCase();
var restOfName = name.slice(1);
var capitaliseName = upperCaseFirstChar + restOfName;
capitaliseName;
That should return the value that you want.
Resources:
Array.prototype.slice on MDN.

trying to understand the concept of being unable to mutate strings/numbers in javascript

In Javascript, you can reassign a variable like:
var x = 10;
x+=10;
console.log(x);
//prints 20 to the console
But if I take another example of a seemingly similar activity I get an unexpected result:
var originalVar = 1;
changeMyVar(originalVar);
function changeMyVar(myVar) {
myVar += 1000;
return myVar;
}
console.log(originalVar);
//prints 1 to the console
I see this as one in the same. I am passing my variable as an argument into a function. I'm reassigning the value within that function. And then I'm returning and printing that variable. Where is the mutation?
Primitives as function parameters are passed by value in javascript. Therefore myVar in changeMyVar function is not reference to originalVar but new variable with value of originalVar.
I hope it will solve your problem :
According to your question
Code :
var originalVar = 1;
changeMyVar(originalVar);
function changeMyVar(myVar) {
myVar += 1000;
return myVar;
}
console.log(originalVar);
Output :
1 // prints 1 to the console
Explanation :
If it was pure pass by reference, then everything would have changed. originalVar would be 1001.
In practical terms, this means that if you change the parameter itself (as with originalVar), that won't affect the item that was fed into the parameter. But if you change the INTERNALS of the parameter, that will propagate back up (as with objects properties).
The operator += reasssigns the variable. It does not reassign the number that the variable represents.
Let's say 'originalVar' is a box with one ball in it. Then calling changeMyVar(originalVar) calls the changeMyVar function with myVar equal to the value of originalVar, so myVar is a box with 1 ball in it. The line myVar += 1000 adds 1000 balls to the myVar box. It does not change the concept of 1 ball into the concept of 1001 balls. So now originalVar still equals 1, but myVar equals 1001.

Give eval a value in JavaScript

very basic JavaScript programmer here!
I was busy on some code with variables that look like this:
blocktype1;
blocktype2;
blocktype3;
blocktype4;
... //everything between blocktype4 and blocktype70, the three dots are not actual code!
blocktype70;
Now I was using eval() in a function where a value was given to one of the blocktype variables. The blocktype depended on the variable "number".
This is what I had for that part:
eval("blocktype" + number) = 3
What I want is, say "number" is 27, then I want the variable blocktype27 to get a value of 3.
When I check the console it says:
ReferenceError: Invalid left-hand side in assignment
Could anyone possibly help me?
I would prefer just vanilla JavaScript and still the use of eval.
Thank you for your time!
The 'correct' solution would probably be to use an Array which is ideal for sequences and are accessible by index.
var number = 1;
var val = 3;
var blocktype = []; // so clean
blocktype[number] = val;
However, properties can be accessed as with the bracket notation as well. This assumes the variables are in global scope and are thus properties of the global (window) object.
var blocktype1; // .. etc
window["blocktype" + number] = val;
The problem with the eval is that is effectively the same as doing f() = 3 which does not make sense: only variables/properties can be assigned to1.
However eval is a built-in function and the results of a function cannot be assigned to, per the error message. It could be written as
var blocktype1; // .. etc (see dandavis' comment)
eval("blocktype" + number + " = " + val);
// What is actually eval'd is:
// eval("blocktype1 = 3")
which quickly exposes a flaw with eval. If val was the string "Hello world!" with would result in eval("blocktype1 = Hello world!") which is clearly invalid.
1 For the gritty: the left-hand side of an assignment has to be a Reference Specification Type, which is a more wordy way of describining the above behavior. (It is not possible for a JavaScript function to return a RST, although it could technically be done for vendor host objects.)
Feel free not to accept this, since it's specifically not using eval(), but:
You can allocate an array of size 71 like so:
var blocktype = new Array(71);
(your number values apparently start at 1, so we'll have to ignore the first element, blocktype[0], and leave room for blocktype[70], the 71st)
You can now assign elements like this:
blocktype[number] = 3;
and use them like so:
alert( blocktype[number] );

creating variable names from parameters in javascript

I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.

Calculation returns NaN

I'm trying to create a page that allows for the multiple upload of images, this requires different name attributes. To achieve this, I'm using JS to add one the variable i giving a number.
The below code returns NaN, I'm not too sure why?
$('document').ready(function() {
var i = 1;
$('#new-dialogue').click(function() {
var i = i + 1;
$('.create-upload').append('<div class="upload"><input type="file" name="image' + i + '"/></div>');
});
});
Remove the second var.
What your current code is saying, is what when new-dialogue is clicked, it should create a variable called i and set it to i+1... but because i hasn't been defined yet in this scope you are doing undefined + 1, which is NaN.
Removing the second var will cause the click function to get the i variable from the containing scope, which is what you want it to do. You can then just have i++ to increment it as needed.
That said, you could just make your life easier by using:
<input type="file" name="image[]" />
Because on the server side, you will then have an array of uploaded files ;)
Instead of
var i = i + 1;
Just do
i++;
You need to increment already declared variable, not re-declare it again.
When you redeclared i local to the callback, your function got its own local copy of i that had yet to receive a value. So var i = i + 1; is basically var i = undefined + 1;, which evaluates to NaN.
Get rid of the var to fix this.

Categories