Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 22 Nov, 2021

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

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 <ol> of primitive data types (and sometimes reference data types) stored as pairs of names and values. In a list, each item is a property.

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.  

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.

Example: In this example, we are going to check if the string is an object or a literal using the if-else condition.

index.js




<script>
    function check(str) {
        if(str instanceof String) {
            return "It is an object of string";
        } else {
            if(typeof str === "string") {
                return "It is a string literal";
            } else {
                return "another type";
            }
        }
    }
      
    // Pass a literal
    console.log(check("Hello geeks"));
      
    // Pass an object of string
    let s = new String("Hi");
    console.log(check(s));
</script>

Output:

It is a string literal
It is an object of string

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!