I'm just trying to figure out why this code isn't working.
var programming = false;
var happy = function() {
if(programming === true) {
happy = false;
}
else {
happy = true
}
};
or my secondary code
var programming = false;
var happy = function() {
if(programming === true) {
happy = false;
}
if(programming) {
happy = true;
}
};
I'm just trying to figure out why this code isn't working.
var programming = false;
var happy = function() {
if(programming === true) {
happy = false;
}
else {
happy = true
}
};
or my secondary code
var programming = false;
var happy = function() {
if(programming === true) {
happy = false;
}
if(programming) {
happy = true;
}
};
Share
Improve this question
edited Dec 20, 2022 at 3:24
General Grievance
5,04338 gold badges37 silver badges56 bronze badges
asked May 23, 2014 at 21:58
user3670483user3670483
291 gold badge1 silver badge2 bronze badges
2
- What do you expect it to do? What is actually happening? What exactly does "isn't working" mean? – Pointy Commented May 23, 2014 at 22:00
- Why are you assigning a boolean to happy if you don't want it to be a boolean? – Chuck Commented May 23, 2014 at 22:05
2 Answers
Reset to default 1I think you mean
var programming = false;
var happy = function() {
if(programming === true) {
return false;
}
else {
return true;
}
};
This is how javascript works. You set the return value of a function using the keyword return
, not by reassigning the function to it's return value.
What happens with your code is that the first time the function is called, it replaces itself by it's return value (that is a boolean). The second time you try to call it, the function doesn't exist anymore, because the variable happy
now contains a boolean (the result of the first time you called it).
Based on your code and the error message,
var happy = function() {
if(programming === true) {
happy = false;
}
else {
happy = true
}
};
you have a function called happy
but then you are overriding it with a boolean and it seems like you are calling it later which yields the error "Boolean is not a function". Change the variable happy
inside the function to a different name.
One interesting thing in JavaScript is that if you change the way you declare your function, you code will not throw an error:
var programming = false;
function happy() {
if(programming === true) {
happy = false; //you should use the keyword var here actually
} else {
happy = true;
}
}
happy();
This will not change the function to a boolean: http://jsfiddle/kLksY/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745330249a4622844.html
评论列表(0条)