How to useconstructor property in Javascript

Using the constructor property to check if a variable is a string literal or an object of the String constructor, the constructor property of the input matches String, it is considered a string literal. If the constructor property matches String.prototype.constructor, it is considered an object of the String constructor.

Example: In this example, the check() function uses the constructor property to determine whether the input is a string literal or an object of the String constructor

Javascript




function check(str) {
    if (str.constructor === String) {
        return "It is a string literal";
    } else if (str.constructor === String.prototype.constructor) {
        return "It is an object of string";
    } else {
        return "Another type";
    }
}
 
// Pass a string literal
console.log(check("Hello, Geeks"));
 
// Pass an object of string
let result = new String("Hello, w3wiki");
console.log(check(result));


Output

It is a string literal
It is a string literal



How to test a string as a literal and as an object in JavaScript ?

In this article, we learn how to test a string as a literal and as an object using JavaScript. 

Similar Reads

What is JavaScript Literal?

Literals are ways of representing fixed values in source code. In most programming languages, values are notated by integers, floating-point numbers, strings, and usually by booleans and characters, enumerated types and compound values, such as arrays, records, and objects, are notated by other names as well....

What is JavaScript Object?

Each object consists of an unordered list

    of primitive data types (and sometimes reference data types) stored as pairs of names and values. In a list, each item is a property....

Approach 1: Using typeof operator

The typeof operator in JavaScript returns a string that identifies the data type of an expression. It is used to determine the data type (returns a string) of its operands. Operands can either be literals or data structures, such as variables, functions, or objects. An operator returns the type of data. The result of typeof can be an object, a boolean, a function, a number, a string, or an undefined value....

Approach 2: Using instanceof operator

...

Approach 3: Using constructor property

instanceof operator: It checks whether the LHS (left-hand side) object is an object of the RHS (right-hand side) class or not. If the object is of that particular class, then it returns true otherwise false....