in JavaScript by (12.8k points)
0 like 0 dislike
24 views

How I can to check null value in JavaScript?


js is null check
javascript null check

2 Answers

0 like 0 dislike
by (12.8k points)

In JavaScript highly desirable also undefined check. You can check null value and check undefined type in JavaScript somehow like it:

if ((typeof(x) !== 'undefined') && (x !== null)) {
	// ...
}

However, since the variable x is always defined since it is a formal function parameter, using the typeof operator is unnecessary and you can safely compare directly with undefined value:

function fn(x) {
	if (x !== undefined && x !== null) {
		// ...
	}
}

Do check all next way:

x != null
x != undefined
x !== null && x !== undefined

typeof foo === "undefined" is different from foo === undefined, never confuse them. typeof foo === "undefined" is what you really need. Also, use !== in place of !=. So the statement can be written as:

function (data) {
	if (typeof data !== "undefined" && data !== null) {
		// some code here
	}
}

You can not use foo === undefined for undeclared variables.

var t1;
if (typeof t1 === "undefined") {
  alert("cp1");
}
if (t1 === undefined) {
  alert("cp2");
}
if (typeof t2 === "undefined") {
  alert("cp3");
}
if (t2 === undefined) { // fails as t2 is never declared
  alert("cp4");
}

var a;
alert(a); // Alerts "undefined"
alert(b); // ReferenceError: b is not defined
a = null;
alert(a === null); // true
alert(typeof(x) === 'undefined'); // true

function test(data) {
    if (data != null) {
        console.log('Data: ', data);
    }
}

test(); // the data=undefined
test(null); // the data=null
test(undefined); // the data=undefined

test(0); // 0
test(false); // false
test('something'); // something
0 like 0 dislike
by (12.8k points)

if

js if statement all variants table

== (its negation !=)

js equally operator all variants table

=== (its negation !==)

js equally also in types operator all variants table

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.