Program JavaScript untuk Memeriksa Apakah Variabel dari Jenis Fungsi

Dalam contoh ini, Anda akan belajar menulis program JavaScript yang akan memeriksa apakah suatu variabel berjenis fungsi.

Untuk memahami contoh ini, Anda harus memiliki pengetahuan tentang topik pemrograman JavaScript berikut:

  • Jenis JavaScript dari Operator
  • Panggilan Fungsi Javascript ()
  • Objek Javascript toString ()

Contoh 1: Menggunakan contoh Operator

 // program to check if a variable is of function type function testVariable(variable) ( if(variable instanceof Function) ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Keluaran

 Variabel bukan tipe fungsi Variabel adalah tipe fungsi

Dalam program di atas, instanceofoperator digunakan untuk memeriksa jenis variabel.

Contoh 2: Menggunakan jenis Operator

 // program to check if a variable is of function type function testVariable(variable) ( if(typeof variable === 'function') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Keluaran

 Variabel bukan tipe fungsi Variabel adalah tipe fungsi

Pada program di atas, typeofoperator digunakan dengan ketat sama dengan ===operator untuk mengecek jenis variabel.

The typeofOperator memberikan tipe data variabel. ===memeriksa apakah variabel tersebut sama dalam hal nilai serta tipe datanya.

Contoh 3: Menggunakan Metode Object.prototype.toString.call ()

 // program to check if a variable is of function type function testVariable(variable) ( if(Object.prototype.toString.call(variable) == '(object Function)') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Keluaran

 Variabel bukan tipe fungsi Variabel adalah tipe fungsi 

The Object.prototype.toString.call()method mengembalikan string yang menentukan jenis objek.

Artikel yang menarik...