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 " );
}
Related
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.
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
I'm a new self-learner and have recently taken on javascript. I have an assignment (from an online code camp) that I just cant seem to make pass. I feel like I understand the basics of it, but I can't write it in a functional way. Can anyone help me here?
The question is in the attached image.
My code looks a little something like:
function ageCalculator(name, yearOfBirth, currentYear) {
var age = currentYear - yearOfBirth;
return (name + "is" + age + "years old.");
console.log(ageCalculator("Miranda", 1983, 2015));
}
I would appreciate any help! Thank you!
You're calling the function ageCalculator just after the return statement. Anything just after the return statement won't be called.
Just pull that call outside.
function ageCalculator(name, yearOfBirth, currentYear) {
var age = currentYear - yearOfBirth;
return (name + " is " + age + " years old.");
}
console.log(ageCalculator("Miranda", 1983, 2015));
Call the function outside the function declaration.
function ageCalculator(name, yearOfBirth, currentYear) {
var age = currentYear - yearOfBirth;
return (name + " is " + age + " years old.");
}
console.log(ageCalculator("Miranda", 1983, 2015));
Whenever you return, the function stops immediately: it'll never get to your console.log the way it is now. Call console.log and the function itself outside your function, you don't want an infinite recursive loop.
Also make sure to add proper spacing:
function ageCalculator(name, yearOfBirth, currentYear) {
var age = currentYear - yearOfBirth;
return (name + " is " + age + " years old.");
}
console.log(ageCalculator("Miranda", 1983, 2015));
I have 2 variables which are concatenated into another variable. On the click of a button the values of the variables should update and also the concatenated variable, but the global variable is keeping the original value.
<button class="filter period" data-sort-value="number" data-period="ltd">LTD</button>
<button class="filter period" data-sort-value="number" data-period="r3">R+3</button>
<button class="filter period" data-sort-value="number" data-period="r12">R+12</button>
<button class="filter period" data-sort-value="number" data-period="rtodec">RTODEC</button>
<script>
var region = "ww";
var period = "ltd";
var finalFilter = "data-" + region + "-" + period;
$('button.filter').on('click', function () {
if ( $(this).hasClass("period") ) {
period = $(this).attr('data-period');
console.log(finalFilter);
console.log(period);
updatedFinalFilter();
}
});
</script>
Yes, i want that finalFilter to be update automatically when one of period or region change value
The only way to make that happen is to actually update it. Variables in JavaScript don't update automatically based on the expression you used to set them the first time. After:
var finalFilter = "data-" + region + "-" + period;
has run, finalFilter is purely set to "data-ww-ltd" - it has no knowledge of or link to region or period.
So before you call updatedFinalFilter(), you'd have to re-evaluate the expression:
var region = "ww";
var period = "ltd";
var finalFilter = "data-" + region + "-" + period;
$('button.filter').on('click', function () {
if ( $(this).hasClass("period") ) {
period = $(this).attr('data-period');
finalFilter = "data-" + region + "-" + period;
console.log(finalFilter);
console.log(period);
updatedFinalFilter();
}
});
Note the lack of var when we update it from in the function - you don't want to redeclare it there otherwise it will become a different finalFilter locally scoped to that function.
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();