Bug 415210 - Incorrect warning for local variable not read or initialized when using if-then-else
Summary: Incorrect warning for local variable not read or initialized when using if-th...
Status: NEW
Alias: None
Product: JSDT
Classification: WebTools
Component: General (show other bugs)
Version: 3.5   Edit
Hardware: PC Windows 7
: P3 normal (vote)
Target Milestone: ---   Edit
Assignee: Project Inbox CLA
QA Contact: Chris Jaun CLA
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-08-16 04:55 EDT by Laurent Lyaudet CLA
Modified: 2013-08-16 06:17 EDT (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Laurent Lyaudet CLA 2013-08-16 04:55:33 EDT
Hi,

Invalid warnings are issued if a local variable is declared in both branches of an if-then-else:

function foo(){
  if(document.getElementById('myId1')){
    var myValue = document.getElementById('myId1').value;//warning never read
  }
  else{
    var myValue = document.getElementById('myId2').value;//no warning ???
  }
  //do something with myValue
  return myValue + 10;//warning never initialized
}

I know this code is ugly and variables should be declared first like that:
function foo(){
  var myValue = '';
  if(document.getElementById('myId1')){
    myValue = document.getElementById('myId1').value;
  }
  elseif(document.getElementById('myId2')){
    myValue = document.getElementById('myId2').value;
  }
  else{
    //do something for this really unexpected case (return or throw or whatever)
  }
  //do something with myValue
  return myValue + 10;
}

But since quick and dirty code is the defacto standard in web developpment ><, I shouldn't have any warning.

Best regards,
   Laurent Lyaudet
Comment 1 Laurent Lyaudet CLA 2013-08-16 06:17:18 EDT
Hi, 

the same logic applies also for try catch:
function foo(){
  try{
    var myValue = document.getElementById('myId1').value;//warning never read
  }
  catch(exc){
    var myValue = 0;//no warning ???
  }
  //do something with myValue
  return myValue + 10;//warning never initialized
}

In that case, the "correct" code looks uglier than the incorrect one:
function foo(){
  var myValue = 0;
  try{
    myValue = document.getElementById('myId1').value;
  }
  catch(exc){
    //do nothing, the default value is fine
  }
  //do something with myValue
  return myValue + 10;
}

Note that I consider that a warning "Multiple declaration of local variable" would be appropriate instead of an incorrect warning "never read" or "never initialized".

Best regards,
   Laurent Lyaudet