0

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Might be helpful if you explain the difference in your answer.
2
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..)

Comments

2
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')
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.