Checking passed parameters using null - JavaScript

Take an example here:

function a(b){
    console.log(b != null ? 1 : 2);
}

This code works fine by printing 1 if you pass the parameter, and 2 if you don't.

However, JSLint gives me a warning telling me to use strict equalities instead, i.e. !==. Regardless of whether the parameter passed or not, the function will print 1 when used !==.

So my question is: what's the best way to check if a parameter has passed? I do not want to use arguments.lengthor actually use the object argumentsat all.

I tried using this:

function a(b){
    console.log(typeof(b) !== "undefined" ? 1 : 2);
}

^ which seemed to work, but is it the best method?

+5
source share
2 answers

, b - undefined, null. , b :

function a(b){
    console.log(b !== undefined ? 1 : 2);
}

!== , null undefined , == !=, !== === , undefined .

+4

undefined (, , undefined, null) :

(!b)?1:2

0, null "" ( ).

, :

typeof(b) === "undefined"
// or thanks to the write protection for undefined in html5
b === undefined

: EcmaScript 2015 :

function a(b = 1){
    console.log(b);
}

undefined - ( null) - , ( ).

+2

All Articles