How to implement a security offer in JavaScript?

I want to protect my functions from zero values โ€‹โ€‹and continue only if there is a โ€œspecificโ€ value.

After looking around, the proposed solutions will double to undefined: if (something == undefined) . The problem with this solution is that you can declare an undefined variable.

So my current solution is to check the null if(something == null) value, which implicitly checks for undefined. And if I want to catch extra fake values, I will check if(something) .

See tests here: http://jsfiddle.net/AV47T/2/

Now am I missing something?

Matthias

+6
javascript undefined
source share
4 answers

JS Standard Protection:

 if (!x) { // throw error } 

!x will catch any undefined , null , false , 0 or an empty string.

If you want to check if the value is valid, you can do this:

 if (Boolean(x)) { // great success } 

In this fragment, a block is executed if x is nothing but undefined , null , false , 0 or an empty string.

-tjw

+6
source share

The only safe way that I know for protecting against variables is really undefined (meaning the name of the variable that has never been defined anywhere) is to check typeof :

 if (typeof _someUndefinedVarName == "undefined") { alert("undefined"); return; } 

Everything else (including if (!_someUndefinedVarName) ) will fail.

Basic example: http://jsfiddle.net/yahavbr/Cg23P/

Remove the first block and you will get:

_someUndefinedVarName not defined

+6
source share

Only recently opened using && as a security guard in JS. No more if approval!

 var data = { person: { age: 22, name: null } }; var name = data.person.name && doSomethingWithName(data.person.name); 
+1
source share

Ternar to the rescue!

 (i) => i == 0 ? 1 : i == 1 ? 2 : i == 2 ? 3 : null 
0
source share

All Articles