3

Hey guys i want to know that what is the difference between these two type of single quotes` and '

i tried to execute the below command with ` then it worked

axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        console.log(resp);
      });

but when i tried to run the same command using '' it doesnt work

axios.get('https://api.github.com/users/${this.state.userName}')
          .then(resp => {
            console.log(resp);
          });
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122

4 Answers4

5

The first is called template literals added in the ES6 - It first evaluates the given embedded expressions, gets the results and replaces the expressions with the results. In the ${} you give expressions (variable, function call, ...), and it creates a string replacing the ${expression} part with the result.

This code part

var str = 'text';
var template = `Some ${str}`; // `str` is a expression which returns the value

console.log(template);

is equivalent of concatenation of strings.

var str = 'text';
var template = 'Some ' + str; // Just concatenate the strings

console.log(template);

Template literals also allow you to create multi-line strings

const multiLine = `This is a multi-
line text`;

console.log(multiLine);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
3

Backticks (`) are used to define Template Literals strings in JavaScript since ES6. These are used to use inline variables as well as declare multiline strings, previously not possible without concatenation (+).

Eg:

var name = 'John';
var string1 = 'My name is ' + name;   //ES5
var string2 = `My name is ${name}`;   //ES6

also can be used to declare multiline strings:

var longString = `this is a
                  really
                  long
                  multiline
                  string`;

EDIT Regarding my multiline example, template literals preserve whitespace. So the example won't be stored as you think it would. This link http://2ality.com/2016/05/template-literal-whitespace.html would be useful on that end.

Dane
  • 9,242
  • 5
  • 33
  • 56
1

The first one `` is template literal or back ticks, where the second '' is single quotes

Template literal can be used for multi line and may use "interpolation" to insert the content of variables along $

With quotes '' this will require a string concatenation.

In your case it is used as interpolation

console.log(`Hello I am 


template literal `)

console.log("Hello I am" +

  " quotes")
brk
  • 48,835
  • 10
  • 56
  • 78
-1

It's not working as ' works for literals, so you probably getting what you typed literaly, on the other hand other kind of quotes let you develope a custom spresion