JavaScript: How to Check if a String is a Literal or an Object?


In this article, we will be exploring strings and how they can be used as a literal and an object depending on the requirements.

JavaScript Literals

A JavaScript literal can be referred to as representing fixed values in source code. In most languages, values are denoted by Integers, floating-point numbers, strings, boolean, characters, arrays, records, and many more.

JavaScript Objects

On the other hand, a JavaScript object can be defined as a list of unordered primitive data types (and sometimes reference data types) that are stored as a pair with key and value. In this list, each item is defined as a property.

The type of Operator

Now how we will check whether the string is a literal or an object.

For this, we will be using the typeof operator. The typeof operator returns the type of any data type in JavaScript and returns their actual data type. Operands can either be literals or data structures such as variables, functions, or objects. An operator returns the type of data.

We can also use the instanceof operator to compare an instance with an Object. It will return the instance of the particular object.

Example

In the below example, we are going to define the string in a literal form and an object form. Once the form is defined, we will be using the typeof or instanceof method for checking whether the string is of literal type or object type.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Checking String type</title>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible"content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
   <h1 style="color: green;">Welcome to Tutorials Point</h1>
   <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("Simply Learning"));

      // Pass an object of string
      let s = new String("Hi");
      console.log(check(s));
   </script>
</body>
</html>

Output

Updated on: 26-Apr-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements