Javascript if statement not executing 2nd parameter - javascript

I have a var that is either 1 or 0, if it's 1 the page should go to cnn.com if it's 0 it should go to google.com. Problem is, when it's 1 or 0 it always goes to google.com. Check out the running version at http://jsbin.com/ucovef/7 Thanks in advance
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
}

You need:
if (randomnumber == 0)
And:
if (randomnumber == 1)
Expressions randomnumber = 0 and randomnumber = 1 are assignment expressions that assign numbers 0 and 1 to the variables, despite them being inside an if conditional statement.
So, it always goes to google.com because everything not equal to 0 is a true expression in JavaScript.

You have to use == to make a check. = sets the value instead of evaluating it. I would also suggest passing the random number to the function.
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('random').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(randomnumber){
if (randomnumber == 0){
this.location.href ="http://www.cnn.com";
}
else if(randomnumber == 1){
this.location.href="http://www.google.com";
}
}

You must use == not = !!!!!!!!!!!!!!!!

Ben, you are using local variable from random in check_random. This won't work. Try this
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(n){
if (n == 0){
this.location.href ="http://www.cnn.com";
}
if (n == 1){
this.location.href="http://www.google.com";
}
}

Related

Using an outside count variable in javascript to display different results based on the count

Okay so I'm putting together a test that will be the core of something I'm trying to achieve, still learning javascript so any help would be appreciated.
So I've set up a simple test with three buttons, first button shows where the count is at with a numerical value, the second button increases the count, and the last button is what I'm trying to use to get different results based on where the count is at.
Problem is that the third button only ever sees a count of 1, regardless of it being increased with the second button, and the count is also reset by hitting it.
var count = 1;
function getCount() {document.getElementById("demo").innerHTML = count;}
function incCount() { count++ }
function shoCount()
{
if (count = 1)
{document.getElementById("test").innerHTML = "A";}
else if (count = 2)
{document.getElementById("test").innerHTML = "B";}
else if (count > 2)
{alert('invalid');}
}
<button onclick="getCount()">getCount</button>
<button onclick="incCount()">incCount</button>
<button onclick="shoCount()">shoCount</button>
<p id="demo"></p>
<p id="test"></p>
</body>
The problem is the way you use to compare count with a number :
This if (count = 1) returns true.
It is an assignment operator and if (1) is evaluated to true in JavaScript
So you enter always in this statement :
{document.getElementById("test").innerHTML = "A";}
What you want is the equality comparator == :
if (count == 1)
{document.getElementById("test").innerHTML = "A";}
else if (count == 2)
{document.getElementById("test").innerHTML = "B";}
else if (count > 2)
{alert('invalid');}
}
Use == or ===
if (count = 1) // 1 will be assigned to count
if (count == 1)
{document.getElementById("test").innerHTML = "A";}
else if (count == 2)
{document.getElementById("test").innerHTML = "B";}
else if (count > 2)
{alert('invalid');}
}
Use equality comparator(== or ===) instead of assignment operator(=) in your if statement
change your script to use == or ====
if (count === 1)
{document.getElementById("test").innerHTML = "A";}
else if (count === 2)
{document.getElementById("test").innerHTML = "B";}
else if (count > 2)
{alert('invalid');}
}
In javascript you have to use either == or === for comparison. First is known as abstract equality it will resolve the data type and compare the values for you. Second is known as strict equality it will first check if the type (ex: string, number, boolean etc) on the left hand side is same as the value being compared on the right hand side.
For example:
console.log(4 == "4"); // true (abstract equality)
console.log(4 === "4"); // false (strict equality)
In your case, you can modify the shoCount function as follows to be safe,
function shoCount() {
if (count == 1) {
document.getElementById("test").innerHTML = "A";
} else if (count == 2) {
document.getElementById("test").innerHTML = "B";
} else if (count > 2) {
alert('invalid');
}
}

Checking for evenness through recursion (Eloquent javascript-exercise)

I've started reading Eloquent Javascript, and there's an exercise about making a recursive function to check for evenness.
I've made it in a couple different ways, it's quite simple, but for some reason I can't get it to work with negative numbers anymore. I had it working, then probably accidentally changed something, and now it only works for positives.
Could you please tell me why this code is 'wrong'?
(textfield.append just prints something to a textfield I've made in an html/css-document, so I can save the exercises in some kind of 'program'.)
function evencheck(n){
if (n == 0){
$('#textfield').append('Even');
}
if (n == 1 || n == -1){
$('#textfield').append('Uneven');
}
else{
if(n > 1){
n -= 2;
evencheck(n);
}
if(n < -1){
n += 2;
evencheck(n);
}
}
}
I know it can be written shorter, I've made a shorter form of it, but that didn't work on negatives either.
I know the problem is a stack overflow, but why is this happening?
not an answer but an extended comment
function evencheck(n){
if (n == 0){
return $('#textfield').append('Even');
}
if (n == 1 || n == -1){
return $('#textfield').append('Uneven');
}
return evencheck(n > 1? n-2 : n+2);
}
The upper code will probably be faster, as the compiler can optimize it to:
function evencheck(n){
while(true){
if (n == 0){
return $('#textfield').append('Even');
}
if (n == 1 || n == -1){
return $('#textfield').append('Uneven');
}
n = n>1? n -2 : n+2;
}
}
So youre not filling the function stack ( really huge numbers possible) , and its actually really fast.
More about that
Your code seems to work, except for large numbers. Try it with something like -12 or 10 works fine. When you input 30000 it hangs itself. Probably because you call the method recursively too many times.
const
inputElement = document.getElementById('number-input'),
checkTrigger = document.getElementById('check-number')
resultLog = document.getElementById('result');
function evencheck(n){
if (n == 0){
resultLog.textContent = `${n} is event.`;
}
if (n == 1 || n == -1){
resultLog.textContent = `${n} is unevent.`;
}
else{
if(n > 1){
n -= 2;
evencheck(n);
}
if(n < -1){
n += 2;
evencheck(n);
}
}
}
function checkInputNumber(event) {
const
numberToCheck = parseInt(inputElement.value);
evencheck(numberToCheck);
}
checkTrigger.addEventListener('click', checkInputNumber);
$('#evenrecursive').click(function(){ $('#textfield').append("<p style ='color:blue'>new command: check if number is even.</p>"); var n = prompt('pick a number', ''); evencheck(n); });
#evenrecursive {
border: 1px solid;
min-height: 20px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="number-input" type="number" />
<button type="button" id="check-number">check</button>
<p id="result"></p>
<div id="evenrecursive">click me for prompt.</div>
I've added your trigger and the problem you're having is type coercion. When the initial value of n is "-10" the code winds up in n += 2, this comes down to n = "-10" + 2 which is "-102" and thus your code never reaches the end.
now it only works for positives. why is this happening?
You might be passing a string, in which case n += 2 does do string concatenation instead of number addition (whereas -= 2 always casts to a number). Try adding
if (typeof n != "number") throw new TypeError("n must be a number");
in the first line of the function, and make sure you do use parseInt or some other suitable parsing method if you take a string input from the user.

I just want to call some loop when give the condition. but it was error

var game1 = prompt("Welcome to FuzzBUzz", "Let's try now GO");
for (var i= 1; i<21; i++){
if(i / 3){
console.log("Fizz");
}
else if (i/ 5){
console.log("Buzz");
}
else if ((i / 3) && (i / 5)){
console.log("FizzBuzz");
}
else{
console.log("choose what you want");
}
};
Your if statements are not conditional. You are just dividing i by a number. If you want to check if it's divisible, use the modulus and check for 0.
if(i%3 == 0){ //if i can be divided evenly by 3, then do something
do something
}
Conditions in if statements need to evaluate to a result which tells the if statement whether or not to execute the block; if the condition holds true the block is executed and vice versa. Change your condition statements to be statements which can be evaluated using comparison operators like: ==, !=, >, >= and you will be successful.

Making a function parameter a variable within the same function

I want to pass my function's size parameter to be used inside the same function, specifically inside an 'if' statement.
function text_size(size){
if (size = '1'){
alert('something')
}
else if (size = '2'){
alert('something else')
}
}
This function is called inside another function (didn't write the whole function):
if (newImg.height > 750, newImg.width > 750){
text_size('1')
}
else if (newImg.height < 500, newImg.width < 500){{}
text_size('2')
}
As for now it always alerts 'something' regardless of the parameters.
Short answer:
Change if (size = '1'){ to if (size == '1'){ (and do the same for the second if).
Longer answer:
size = '1' sets size to '1' and evaluates as '1', which is evaluated as true in javascript. This makes the code inside the first if statement always run.
function text_size(size){
if (size === '1'){
alert('something')
}
else if (size === '2'){
alert('something else')
}
}
= assign a value to a variable
== do assertions between left and right conditions of the ==
=== do like == but also check type (string, integer, etc..)
if (newImg.height > 750, newImg.width > 750){
text_size('1')
}
should be (to use logically and, for or its ||):
if (newImg.height > 750 && newImg.width > 750){
text_size('1')
}
As #Tzach said, the problem comes from
if (size = '1'){
You have to use size == '1' instead.
Why? because if you use only one '=', in means that you are doing an assigantion :
var size = 0;
if (size = 1){...}
alert(size); //size is now equal to 1
var size = 0;
if (size == 1){...}
alert(size); //size is equal to 0

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources