import React, { useState } from "react";
function App() {
const [name, setName] = useState("REACT");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<input
type="text"
onChange={handleChange}
placeholder="Enter a value"
value={name} //-----> 1) does value of name comes as "REACT" or as REACT in value variable as it expects string
/>
{`Javascript-${name}`} 2) // if name comes as "REACT" in first ques then why this does not
print Javascript-"REACT" as it will also come with double quotes
</div>
);
}
export default App;
I just have this doubt of javascript string variable behaviour in react?? and also when we console log the string in javascript why it removes the quotes from both end?
2
Answers
check this link to complete answer
MDN
It seems that there are several questions discussing that topic. Let’s start with first one:
String is one of the primitive data types in JavaScript. It is used to store some sequence of characters. In general it’s an Array of chars:
"abc" could be represented as [‘a’, ‘b’, ‘c’] joined together.
Why does value of the string is displayed without quotes? The quotes are used to define the value of the string. But you can also define value of the string with quotes, for example:
const a = "'my string'"
– in that case your""
quotes define that provided value is a String. And your''
quotes are the part of the value of the string.If you’ll try to
console.log
such string, the result is:'my string'
Template literals – “ – allow us to combine in one string hard-coded text and one or a few dynamic variables. The same logic works here – your literals just define that the provided in it value is a string, but if you’ll add another quotes in your literals:
it is displayed with quotes (" ").
In general the answer is that JavaScript has string as a type to contain some characters/texts. Mostly as a developer you don’t need quotes stored with your value. But in some exception cases you can define the string with one type of quotes (" ") and then write in another type of quotes as a value (‘ ‘).
For example:
Then
console.log(a)
will display:''
The same logic works using strings in React