Why does this code snippet output undefined? [duplicate] - javascript

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

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.

My if and else statement always think it's -and [duplicate]

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 4 years ago.
I have a selector on my page that has -and or -or. I'd like to change the content of a div depending on what users choose with -And or -Or.
My if and else statements aren't working right now, well it's almost working it just always add -And. It looks as if it always see's -And?
First time I'm trying to use an if and else statement and I think I made mistake.
<script>
function Andor' + count + '(selTag) {
var x = selTag.options[selTag.selectedIndex].text;
if (x = '-and'){
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " ";
} else {
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " (";
}
}
</script>
You use one =, which is 'assign'. You want === (or ==) for 'equals'.
You do the same as: var example = 'foo';. You set the value to a string ('-and'), which always results in true, which makes it look like it's true.
What you want is example=='foo' to check if the content of example equals 'foo'.
Suggested reading material: https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a

Concatenate string and variable to get variable [duplicate]

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

Shorthand for "console.log("var: " + var)"?

It would be nice to have a super quick way to do this:
"console.log("var: " + var)"?
Tried this, but not sure if there's a way to get a variable name as a string once it's been passed in, or convert the name string to a reference to the variable...
var mLog = function(varNameStr){
console.log(varNameStr + ": " + _____);
}
EDIT: Judging by the results of googling "get name string of a variable js", it looks like there's no easy way to grab the name string of a variable from the reference (You have to create hash tables or other structures that make it not worthwhile.)
So, the only possible solution would be to convert a string into a reference to the variable. Is that possible in JS?
The following will do the trick. Pass it a variable name in string form.
var mLog = function(varStr){
console.log(varStr + ": " + eval(varStr));
}
Example:
> var strVar = 'A string variable';
> mLog('strVar');
< strVar: A string variable
> var arrVar = [1,2,3];
> mLog('arrVar');
< arrVar: 1,2,3
There is no way to "extract" the variable name, since variables aren't actually data. The closest thing you could do is use it for objects. Something like:
var obj= {
prop: 'value'
};
function mLog(object, prop) {
console.log(prop + ': ' + object[prop];
}
mLog(obj, 'prop');

Why are my Global Variables not working?

Im sure this is a silly/simple question, but it is really puzzling me. I understand 'Global Scope', and how functions have access to Global Variables, and their inner variables.
For some reason, my 'test' function, cannot access the global variables. When my 'test' function 'alerts' global variables it returns 0. But when I move those 'global' variables to 'local' variables it works.
Why are my global variables not working?
My question is specifically for the variables 'years' and 'months'
This alert's 0 (Global Scope) (In regards to the years variable):
//Varibles
var mortgageAmount = getById('mAmount');
var mortgageAmountOutput = logger('mAmount');
var calc = getById('calculateBtn');
var years = +document.getElementById('mPeriod').value;
var months = years*12;
//Functions
function test() {
//Test to see if numbers are 'numbers'
//Populate Page
populateMortgage();
populateIntRate();
//Math
alert("My Mortgage is for: " + years + " years, or for " + months + " months " );
}
When I move the variable declaration from the global scope, to local, it works just fine:
//Varibles
var mortgageAmount = getById('mAmount');
var mortgageAmountOutput = logger('mAmount');
var calc = getById('calculateBtn');
//Functions
function test() {
//Test to see if numbers are 'numbers'
//Populate Page
populateMortgage();
populateIntRate();
//Math
var years = +document.getElementById('mPeriod').value;
var months = years*12;
alert("My Mortgage is for: " + years + " years, or for " + months + " months " );
}

Categories

Resources