19

I created a function:

function CheckHidden(el){ return $(el).css('display')!='none' }

My IDE warns me that:

Primitive value returned from constructor will be lost when called with 'new'

Actually when I call it like this:

var all = $("#catalog-body > div").filter(function(){return  CheckHidden(this)})

it doesn't work and doesn't reduce set of elements to unhidden ones. Please explain to me the issue. I have a giant lack of knowledge.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Alex Ho
  • 299
  • 1
  • 2
  • 9
  • There are multiple questions in one. Which one describes your problem best? – feeela Oct 13 '14 at 11:14
  • 1
    I'm not sure what IDE you're using, but this is specific to the IDE and not to JavaScript. If you have a method that you never instantiate with new then disregard the warning. – Konstantin Dinev Oct 13 '14 at 11:24

4 Answers4

86

I ran into this warning myself and if you want to know the cause, it is because your IDE expect function names to start with a lowercase letter. Since your function is called CheckHidden with a capital C, it thinks it's a class declaration.

However, you should still use jQuery's :visible selector to fix your specific issue.

Matt234
  • 1,055
  • 8
  • 14
  • 2
    If you don't want to change your function name to lowercase, you can avoid the warning with a`/** * @returns {boolean} */` comment line above the function. – terrymorse Apr 21 '17 at 18:35
11

If you create an object using the keyword new (as mentioned in the warning), JS returns an new instance of the object rather than the return value from the constructor.

A function like

function CheckHidden() {
    return false;
}

would return two different values, depending on how it is executed.

// "a" is boolean value
var a = CheckHidden();

// "a" is an object of type "CheckHidden"
var a = new CheckHidden();
feeela
  • 29,399
  • 7
  • 59
  • 71
0

jQuery actually has something like this built in. You can use the :visible selector. You can just do:

var all=$("#catalog-body > div").filter(':visible')

to get the visible elements.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

If you want to pull all elements which are visible, you can use jQuery's :visible selector:

var all = $("#catalog-body > div:visible")

Conversely, if you want to pull all elements which are hidden, you can combine this with jQuery's :not selector:

$("#catalog-body > div:not(:visible)")
James Donnelly
  • 126,410
  • 34
  • 208
  • 218