How can I determine if a variable is a primitive type and not an object?

Can a variable be tested to determine if it is a primitive data type?

I've come across many inquiries about testing a variable to check if it is an object, but not specifically for a primitive type.

This inquiry is purely academic, as I do not require this test in my own code. I simply want to enhance my knowledge of JavaScript.

Answer №1

To check for whether a value is a primitive:

function isPrimitive(input) {
    return input !== Object(input);
}

For example:

isPrimitive(100); // true
isPrimitive(new Number(100)); // false

Check it out here

Answer №2

Object takes a parameter and determines if it is an object, returning true if it is, or returning an object if it is not.

Afterwards, a strict equality comparison can be used to compare types and values.

If the value is an object, Object(value) will be identical to the original object, making value === Object(value) true. If the value is not an object, value !== Object(value) because they will have different data types.

Therefore, you can employ

Object(value) !== value

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

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Encountering an error with ResizeObserver.observe when using Next.js and ag-grid to render client side

I designed a product page that includes a searchbar component and a grid component with the ag-grid import and setup. Here is a simplified version of the product page: // Code for dynamic client side rendering import const ProductGrid = dynamic(() => ...

Guide to converting a form into a structured object format (with a tree layout)

Looking to transform a form into an object structure? <form> <input type="text" name="Name" /> <input type="checkbox" name="Feature.Translate" /> <input type="checkbox" name="Feature.Share" /> <input type="submi ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

Bringing in a JavaScript file into a Svelte component

Today, I stumbled upon Svelte and I am really intrigued by the concept. However, I encountered an issue while attempting to import a small helper.js file. No matter what I try, whenever I reference the class, I receive the error: ReferenceError: Helper ...

Stopping a function when another function is invoked in JavaScript

I've been immersing myself in the search for a way to halt one function if another is called or triggered in JavaScript. Initially, I believed it to be unattainable, but I'm open to having my perspective changed. My current focus lies within a t ...

Send a webhook post request without causing a redirection

Is there a way to send a post request to a webhook without redirecting the user directly to the webhook URL, after validating their input? ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Vertical alignment issue with icons in Bootstrap 5 HTML code

Just starting out with Css and I'm having trouble aligning the google icon vertically in the center with some padding from the bottom. You can see the issue in the attached file. The text is aligned in the center. .g-icon{ background-image: url(" ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

Steps to turn off popover functionality for a specific child element

Within a container, there are details along with a button. The container exhibits popover behavior upon hovering over it. However, the challenge lies in disabling the popover behavior while hovering specifically over the button within it. You can find th ...

When a legend is clicked, it should display only the selected item while hiding all other legends automatically in a chart created

I have a highchart with 10 legends. When I click on the first legend, only that legend should remain visible while the rest are automatically hidden... Below is a code snippet with two legends: $(function() { var chart = $('#container').hig ...

Exporting methods/functions in React Native

import { width as responsiveHeight } from "react-native-responsive-dimensions"; I am trying to export responsiveHeight with the name width. Can someone please guide me on the correct way to do this? The current approach is not yielding any results. ...

Numerous scripts available for achieving a responsive layout using (window).resize event

I am currently in the process of creating a one-page website with a responsive design. On smaller screens, I have implemented an animated scroll plugin to navigate between content divs, while on larger screens, I am using a plugin to toggle the visibility ...

create a nested promise with a delay in a node.js environment

Utilizing Google geocoding in my coding tasks has presented a challenge. I have around 50 places to geocode, but Google restricts the number of places that can be geocoded simultaneously, resulting in an 'OVER_QUERY_LIMIT' error. To address this ...

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

Is it possible to enable unknown keys for multiple schema objects simultaneously using Joi Validation?

I have a multitude of validator files each containing nearly a hundred schema objects. My goal is to validate unknown keys for all of them simultaneously. I've managed to figure out how to do it for a single object, as shown below. Is there a way to a ...

Is it possible to incorporate both Matter and Arcade physics into the Player object?

I attempted to instantiate a player object export default class Player extends Phaser.Physics.Matter.Sprite { constructor(data) { let { scene, x, y, texture, frame } = data; super(scene.matter.world, x, y, texture, frame); this. ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...