Concatenate string and variable to get variable [duplicate] - javascript

This question already has answers here:
Get global variable dynamically by name string in JavaScript
(6 answers)
Closed 5 years ago.
I want to be able to pass a string into a function, concatenate it with a common suffix, and use that new string as an existing variable. For example,
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
updateInfo(arg)
{
console.log(arg + "Info");
}
updateInfo("first");
/* Should print "The first string says this.", but instead does nothing. */
What am I doing wrong? This is plain javascript, but I am open to other libraries.

You need to use window[arg + "Info"] to get a value of global variable:
console.log(window[arg + "Info"]);
Here is a full fiddle

Use javascript function eval() , here's the doc
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
function updateInfo(arg)
{
console.log( eval(arg + "Info") );
}
updateInfo("first");

It should be
updateInfo(arg)
{
firstInfo = arg + "Info";
console.log(firstInfo );
}
updateInfo(firstInfo );

Your "firstInfo" variable is defined in the global scope, and is hence attached to window object.
If you console it in the function scope without the window reference it will be invoked with the local scope.
Try this I have used the window object.
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
function updateInfo(arg)
{
console.log(window[arg + "Info"]);
}
updateInfo("first");

Related

Compare values of object JavaScript

I have an object in JS like this:
var getToDoValue = document.getElementById("toDoInput").value;
var nameOfTeamMember = "Tobias";
var person = new Object();
person.task = "Task: " + getToDoValue;
person.member = "Member: " + nameOfTeamMember;
But problem comes when I try to enter the value of "nameOfTeamMember into an if statement:
var mem = person.member;
if (mem == "Tobias") {
console.log("works");
}
This does not work. But when I just console.log "var mem" outside of if statement it gives me "Member: Tobias". Any suggestions? Im still kinda new to JS so prob something with the comparisons
the issue with you code is that the value in person.member is "Member: Tobias" as you pointed out from the result of your console.log, which is the result from the line of code below where you are concatenating the name with the string "Memeber: " and assigning it to the member property.
person.member = "Member: " + nameOfTeamMember;
One option you could use to do the comparison would be:
if (mem.contains("Tobias", 8) {
console.log("works");
}
The 8 is so your search starts after the colon (:) so you don't include "Member:" in it, just what comes after it, which is the actual member name.

Why Math.sin`1` works and Math.sin'1' not [duplicate]

This question already has answers here:
Invoking a function without parentheses
(9 answers)
Closed 4 years ago.
If I enter this expression in the browser console (with grave accent):
Math.sin`1`
It will return:
0.8414709848078965
But if I enter this expression (with single quote):
Math.sin'1'
It will throw this error:
SyntaxError: Unexpected number
Why does this error happen?
That's what's called a tagged template literal:
fn`string`
assuming fn is a function, will simply result in fn being called with string as the first argument.
Tagged template literal functions are more useful when you have ${ .. } replacements to make. From the MDN example:
var person = 'Mike';
var age = 28;
function myTag(strings, personExp, ageExp) {
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "
return str0 + personExp + str1 + (
ageExp > 99
? 'centenarian'
: 'youngster'
);
}
console.log(myTag`that ${ person } is a ${ age }`);
tag`template literal` is specifically part of the template literal syntax. It doesn’t work for other string literals.

Declare JavaScript variable only with ' ' marks

I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default value.

Why does this code snippet output undefined? [duplicate]

This question already has answers here:
Why do I get the value "result" for this closure?
(3 answers)
Closed 8 years ago.
As part of my learning JavaScript, I try to write code to demonstrate the concept I am learning; today I'm learning hoisted variables. Here is the code I wrote:
console.log("A: My name is " + name);
function happy() {
console.log ("1: I am " + feeling);
var feeling = "happy";
console.log ("2: I am " + feeling);
}
happy();
var name = "Jim";
console.log("B: My name is " + name);
I expected the following results:
A: My name is undefined
1: I am undefined
2: I am happy
B: My name is Jim
However, when testing my code at WriteCodeOnline.com and in another sandbox, the first console.log displays A: My name is. I am using a Chrome browser, if that makes a difference.
So, my question is, why does the hoisted local variable within the function return undefined while the hoisted global variable returns a blank?
What is happening here is that you are accessing window.name.
This is a predefined property on window, so your hoisted var name isn't actually creating a new variable. There's already one in the global scope with that name and by default, it has a blank string value.
To observe the behavior you were expecting, you can use a variable name other than name, or put your code inside a function:
function hoisting() {
console.log("A: My name is " + name);
function happy() {
console.log ("1: I am " + feeling);
var feeling = "happy";
console.log ("2: I am " + feeling);
}
happy();
var name = "Jim";
console.log("B: My name is " + name);
}
hoisting();

Help on eval() function

I need help on this eval() problem:
var ScoreFuncName = 'scoreCondition_' + criteriaName;
var allCheckBox = $('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");
eval(ScoreFuncName + '(' + allCheckBox.length + ')');
The eval() function is evaluating which checkbox is ticked and will do other things accordingly, it worked great in Firefox but not in google Chrome and IE.
Scratching my head for 3 days on how to fix this. Thank you.
You should not be using eval for that.
If the function is in global scope. All you need to do is
window[ScoreFuncName](allCheckBox.length);
It would be better to name space it instead of using a global with window
Eval is not needed to do this. Also take notice that I am calling size on the jQuery object rather than length.
var scoreFunc = this['scoreCondition_' + criteriaName];
var allCheckBox =
$('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");
scoreFunc(allCheckBox.size());
Hm... don't.
There realistically is not a need to use eval in this condition (and I would say that there is no need for a string look-up of the function). Since it looks clear that you have a finite and knowable number of conditions and a finite and knowable number of functions, then you can simply use a switch to actually select a function dynamically:
var toRun; // variable to store the function.
switch(criteriaName)
{
case "criteria1":
// keep the actual function in the variable, not some string.
toRun = function(e){console.log("I is so special! " + e)}
break;
case "criteria2":
toRun = function(e){console.log( e + " is not a squid!" )}
break;
}
var allCheckBox = $('div#'+SubListId).find("input:image[name^='" +
ChkBoxPrefix + "'][value='1']");
// then just call it!
toRun(allCheckBox.length)

Categories

Resources