Contoh 1: Centang undefined atau null
// program to check if a variable is undefined or null
function checkVariable(variable) {
if(variable == null) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
Keluaran
The variable is neither undefined nor null The variable is neither undefined nor null The variable is undefined or null The variable is undefined or null
Dalam program di atas, sebuah variabel diperiksa jika setara dengan null
. Itu null
dengan ==
cek keduanya null
dan undefined
nilai-nilai. Hal ini karena null == undefined
mengevaluasi untuk benar.
Kode berikut:
if(variable == null) { ... }
setara dengan
if (variable === undefined || variable === null) { ... }
Contoh 2: menggunakan typeof
// program to check if a variable is undefined or null
function checkVariable(variable) {
if( typeof variable === 'undefined' || variable === null ) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
Keluaran
The variable is neither undefined nor null The variable is neither undefined nor null The variable is undefined or null The variable is undefined or null
Itu typeof
operator untuk undefined
pengembalian nilai tidak terdefinisi. Oleh karena itu, Anda dapat memeriksa undefined
nilai menggunakan typeof
operator. Juga, null
nilai diperiksa menggunakan ===
operator.
Catatan: Kami tidak dapat menggunakan typeof
operator untuk null
saat kembali obyek.