chrome development console only gives me undefined - javascript

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.

Related

When assigning the result of an addition to a variable, calculator doesn't work. Why?

I'm experimenting with my very basic Javascript and I found a nice Tutorial on how to make a very basic calculator in JS.
I tried following along with the video but I didn't want to just "copy-paste" what he was writing so I stopped and tried to do what I thought was the logic code...WRONG!
Here the problem
Why this doesn't work?
function addNum() {
let first = document.querySelector('.first').value;
let second = document.querySelector('.second').value;
let result = document.querySelector('.resultt').value;
return result = first + second
}
I tried to assign the input related to the result to a variable but it doesn't work.
But when I do this: (as it was done in the tutorial)
function addNum() {
let first = parseInt(document.querySelector('.first').value);
let second = parseInt(document.querySelector('.second').value);
document.querySelector('.resultt').value=first + second;
}
So without assigning the result to a variable, it works.
Why?
When you do
let result = document.querySelector('.resultt').value;
you're copying the value from the value property to the result variable. There's no ongoing link between them after that, they each just contain the same string. That means later, when you do result = first + second, all you're doing is updating result; that has no effect at all on value.
So you have to assign back to value as you do in your second code block.

How to eval string function and return value in javascript?

I have a method in string like:
var str = "function evalTest(param){if(param)return '<div>hello</div>'}else return '<div>world</div>'"
I am replacing param like:
var res = str.replace("param", "param=false");
Now if I do eval like:
var final = eval(res);
I am expecting final should contain result "world" because passed param = false.
How to achieve this result "world"?
First a caveat: There's almost certainly a better solution to whatever problem you're trying to solve by having that function in a string.
And another one: Never eval code supplied by an end user except for that same end user. For instance, never let user A supply the code, then eval it in user B's browser. (Without user B knowing that you're doing that and expressly consenting to it.)
Really, almost any time you're reaching for eval (or its cousin new Function), it's worth stepping back to see if there's another approach you can use.
But answering the question asked:
eval is just creating the function. You don't have anything in that string that calls it.
Because eval works magically in the current scope, evaling your string creates the function in the current scope. You could then call your function to get the result you're looking for:
var str = "function evalTest(param){if(param){return '<div>hello</div>'}else {return '<div>world</div>'}}";
var res = str.replace("param", "param=false");
eval(res);
var final = evalTest();
console.log(final);
Note that I fixed a couple of syntax errors in the function's text (curly brace issues, mostly).
If you don't want the function defined in the current scope, you can modify the string to make it a function expression and call it immediately:
var str = "function evalTest(param){if(param){return '<div>hello</div>'}else {return '<div>world</div>'}}";
var res = str.replace("param", "param=false");
var final = eval("(" + res + ")()");
console.log(final);

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

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

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] );

Calling javascript function with an objectstring in dot notation

Suppose I have the string:
var string = "function";
With
window[string];
I can call a function with the name of "function".
But, when I have:
var string2 = "function.method.weHaveTogoDeeper";
it should call
window["function"]["method"]["weHaveTogoDeeper"]
I can't do:
window[string2]
in this case. I dont know the number of "." in the string, so I need some kind of routine.
you can split the string across . by using the String.split method:
var string2 = "function.method.weHaveTogoDeeper";
var methods = string2.split(".");
In this examples, methods will be the array ["function","method","weHaveTogoDeeper"]. You should now be able to do a simple iteration over this array, calling each function on the result of the previous one.
Edit
The iteration I had in mind was something like this:
var result = window;
for(var i in methods) {
result = result[methods[i]];
}
In your example, result should now hold the same output as
window["function"]["method"]["weHaveTogoDeeper"]
function index(x,i) {return x[i]}
string2.split('.').reduce(index, window);
edit: Of course if you are calling functions from strings of their names, you are likely doing something inelegant which would be frowned upon, especially in a collaborative coding settings. The only use case I can think of that is sane is writing a testing framework, though there are probably a few more cases. So please use caution when following this answer; one should instead use arrays, or ideally direct references.
I wrote one a while back:
function RecursiveMapper(handlerName, stack) {
// check if empty string
if(!handlerName || handlerName === '' || (handlerName.replace(/\s/g,'') === '')) return null;
var buf = handlerName.split('.');
stack = stack || window;
return (buf.length === 1) ? stack[buf[0]] : this.RecursiveMapper(buf.slice(1).join('.'), stack[buf[0]]);
}
Call it like this: RecursiveMapper(window[string2]);
This one also checks if the function is defined in window scope first and returns the global one fi found.

Categories