Can’t access attributes on a primitive-typed value (string).

Query: Can’t access attributes on a primitive-typed value (string).

When dealing with a primitive JavaScript value, such as a string, you cannot access attributes or properties on it directly. To understand this in detail, let’s go through an example:

    
// Define a string variable
const message = "Hello, World!";

// Try to access an attribute
console.log(message.length);
    
  

In the example above, we have a string variable “message” that holds the value “Hello, World!”. The “length” attribute is a property of strings that returns the number of characters in the string.

Now, if we try to access the “length” attribute directly on the string variable “message” and log it to the console, we will get the correct result:

    
// Correct usage to access "length"
console.log(message.length); // Output: 13
    
  

However, if we try to access the “length” attribute on the string value itself without storing it in a variable, we will get an error:

    
// Incorrect usage: accessing attribute on a primitive string value
console.log("Hello, World!".length); // Error: Cannot access properties of string literals
    
  

This happens because a string literal (a primitive value) does not have any inherent attributes or properties like a variable does. To access attributes or properties, you need to have a variable that holds the value.

Read more interesting post

Leave a comment