Programa JavaScript para verificar se uma variável é do tipo de função

Neste exemplo, você aprenderá a escrever um programa JavaScript que verificará se uma variável é do tipo função.

Para entender este exemplo, você deve ter conhecimento dos seguintes tópicos de programação JavaScript:

  • Operador tipo JavaScript
  • Chamada de função Javascript ()
  • Objeto Javascript toString ()

Exemplo 1: Usando o operador instanceof

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

Resultado

 A variável não é do tipo de função A variável é do tipo de função

No programa acima, o instanceofoperador é usado para verificar o tipo de variável.

Exemplo 2: Usando typeof 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);

Resultado

 A variável não é do tipo de função A variável é do tipo de função

No programa acima, o typeofoperador é usado com estrito igual ao ===operador para verificar o tipo de variável.

O typeofoperador fornece o tipo de dados variável. ===verifica se a variável é igual em termos de valor e também do tipo de dados.

Exemplo 3: Usando o método 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);

Resultado

 A variável não é do tipo de função A variável é do tipo de função 

O Object.prototype.toString.call()método retorna uma string que especifica o tipo de objeto.

Artigos interessantes...