Hailwood
Hailwood

Reputation: 92691

if statement running on false?

using javascript

I have a function

function test(variable)
{
  if(variable != 'undefined')
  {
     console.log('variable is not set');
     console.log('variable', where); 
  }
}

i call it using test();

yet in the console I get 'where is not set' 'where is set as undefined'

why?


Update This function is not what i am actually using.

The function should not do anything if the variable is undefined.

the example was to show the if statement not working.

But the issue was actually me using if variable != 'undefined' instead of variable != undefined

Upvotes: 0

Views: 241

Answers (3)

mr.b
mr.b

Reputation: 2708

I don't quite understand your question but try using different paramater name instead of "variable". See if the error still there.

Plus call the function like this: test(paramterValueHere);

Best

Upvotes: -1

Pekka
Pekka

Reputation: 449803

You are testing whether variable has the string content of "undefined".

What you probably want is

if(typeof variable != 'undefined')

The rest of the function is not making sense to me yet, either. Where does where come from?

Upvotes: 4

Gumbo
Gumbo

Reputation: 655785

You have both console.log calls in the same if branch. Do this instead:

function test(variable)
{
  if(variable != 'undefined')
  {
     console.log('where is not set');
  }
  else
  {
     console.log('where is set as ', where); 
  }
}

Besides that: If you want to test if a variable is undefined, use the typeof operator to test the type: typeof variable != 'undefined'. Currently you just test if variable is not equal to the string value 'undefined'.

Upvotes: 6

Related Questions