Skip to content
Advertisement

How to Check the variable value is [“”] in JavaScript

Example: When I check a variable containing this value [“”] it returns false.

var th=[]
th.push("");
if($("#multiselect").val()==th)

It returns always false.

Thank you.

Edit 1: changed Var to var. It was a typo.

Edit 2: Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [“”] even I haven’t selected any values basically it’s a plugin. So I was confused and I thought [“”] is a fixed primitive value like 1, 10, “bla blah”,.. So I tried to compare it with the same array as the right-hand side of the ‘=’ operator. It was stupid. Now I posted the solution to my problem and I explained my stupidity.

Advertisement

Answer

I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.

Anyway, I’m answering this question so it might help others.

Answer to my question:

When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [“”] value, I should do something like the below.

function isArrValEmptyCheck(value) {
  return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}

console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false

Sorry for the late response. Thanks to everyone who tried to help me.

Advertisement