Program JavaScript untuk Memeriksa Apakah Variabel adalah Tipe Fungsi

0
(0)

Contoh 1: Menggunakan instanceof 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

The variable is not of function type
The variable is of function type

Pada program di atas, instanceof operator digunakan untuk memeriksa jenis variabel.


Contoh 2: Menggunakan Operator typeof

// 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

The variable is not of function type
The variable is of function type

Pada program di atas, typeof operator digunakan dengan ketat sama dengan === operator untuk memeriksa jenis variabel.

Itu typeof operator memberikan tipe data variabel. === memeriksa apakah variabel sama dalam hal nilai serta tipe data.


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

The variable is not of function type
The variable is of function type

Itu Object.prototype.toString.call() metode mengembalikan string yang menentukan tipe objek.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.