JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array.

I am in search of the most efficient method to determine its type.

In my opinion, the current approach is not optimized because if I already know that isFunction = true, there's no need to calculate the other variables (isArray, isObject);

What would be the best sequence to calculate them in order to optimize resources using ternary operations?

var isFunction,
    isArray,
    isObject;

var obj = function () {};

isFunction = (typeof obj === "function") ? true : false;
isArray = (obj.length > 0) ? true : false;
isObject = (typeof obj === "object") ? true : false;

console.log(isFunction , isArray , isObject ); // true, false, false (the correct way)
console.log(isFunction , isArray , isObject ); // true, undefined, undefined

Answer №1

This code snippet has been optimized for efficiency without compromising readability. It works well in modern browsers with native support for the some method, which stops executing the callback once a condition is met within an array.

To ensure compatibility with older browsers, it's advised to include Array.prototype.some.

function isOneOf(obj, types) {
  var type;
  type = Object.prototype.toString.call(obj);
  return types.split(' ').some(function (t) {
    return type.indexOf(t) > -1;
  });
}

isOneOf({}, 'Array Object Function');

This function supports various types such as Array, Date, Error, Function, Null, Number, Object, String, and Undefined. Although extensive cross-browser testing has not been conducted, it's advisable to perform thorough unit tests before relying solely on this implementation.

Answer №2

Here are the various functions from the dojo toolkit used to test for arrays, functions, and more:

checkString = function(str){
    return (typeof str == "string" || str instanceof String); // Returns a Boolean
},

verifyArray = function(arr){
    return arr && (arr instanceof Array || typeof arr == "array"); // Returns a Boolean
},

validateFunction = function(func){
    return opts.call(func) === "[object Function]";
},

determineObject = function(obj){
    return obj !== undefined &&
        (obj === null || typeof obj == "object" || lang.isArray(obj) || lang.isFunction(obj)); // Returns a Boolean
},

confirmArrayLike = function(item){
    return item && item !== undefined &&
        !lang.isString(item) && !lang.isFunction(item) &&
        !(item.tagName && item.tagName.toLowerCase() == 'form') &&
        (lang.isArray(item) || isFinite(item.length));
},

I personally don't see the need to optimize this particular code. If optimization is a concern, it's best to utilize simpler functions without overloading where these checks are not required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

Identifying when a user closes a tab or browser to trigger a logout in JavaScript with Vue.js using the Quasar framework

Is there a way to trigger the logout function only when the tab or browser is closed, and not when the page is refreshed? I attempted the following code example, which successfully triggers the logout on tab close but also logs out when the page is ref ...

What is the best way to change a date from the format DD/MM/YYYY to YYYY-MM-DD

Is there a way to use regular expressions (regex) to convert a date string from DD/MM/YYYY format to YYYY-MM-DD format? ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Enhancing speed on an extensive list without a set height/eliminating the need for virtualization

My webapp includes a feature that showcases exhibitors at an expo. The user can click on "Exhibitors" in the navigation bar to access a page displaying all the exhibitors. Each exhibitor may have different details, some of which may or may not contain data ...

Exploring ways to cycle through dynamically loaded checkboxes with AJAX?

I'm looking to apply a similar function to checkboxes that are loaded dynamically via AJAX: $('input:checkbox').each(function() { $(this).hide(); alert("hi"); $('<div class="checkbox-fx"><div class="che ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

What is the best method for dividing strings in javascript?

After invoking a JavaScript function, I received the following results: (1, 00), (2, 10), (3, 01), (4, 11) I am looking to store this data in an array or JSON format like this: [{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11} ...

Sending the ID of a mapped button to a component

I need help with my React mapping function that displays a series of cards, each with its own button to open up a dialog box. Right now, I'm struggling to pass the unique ID from each object to the correct dialog box. Instead, all IDs are being passed ...

reqParam = $.getQueryParameters(); How does this request work within an ajax form

I've spent a lot of time searching, but I can't figure out what the code reqParam = $.getQueryParameters(); means and how it is used in Ajax JavaScript. I copied this Java script from a website as an example. If anyone has any insights, please he ...

Struggling with integrating PHP within a JavaScript AJAX function

Here's a button I have: <button id= $id onClick="popup($id)">button</button> I am attempting to use it with an ajax function <script> function popup(id){ alert(" "); document.write(" "); } </script> My goal is to execute P ...

Guide to modifying text color in a disabled Material-UI TextField | Material-UI version 5

How can I change the font color of a disabled MUI TextField to black for better visibility? See below for the code snippet: <TextField fullWidth variant="standard" size="small" id="id" name=&quo ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...