user2315641
user2315641

Reputation: 161

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.

Upvotes: 0

Views: 52

Answers (4)

Gwenc37
Gwenc37

Reputation: 2048

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

Upvotes: 0

phylax
phylax

Reputation: 2086

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

Upvotes: 2

isThisLove
isThisLove

Reputation: 269

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..)

Upvotes: 2

Tzach
Tzach

Reputation: 13376

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.

Upvotes: 4

Related Questions