1

Do we need to use quotes around purely numeric variable values, like 10 or 100?

Below is example.

// 1st version - without quotes
var foo = 10;
var bar = 'hello';
if (foo == 10 && bar == 'hello') {
 alert('something');
}

// 2nd version - with quotes
var foo = '10';
var bar = 'hello';
if (foo == '10' && bar == 'hello') {
 alert('something');
}

// 3rd version - mixed
var foo = 10;
var bar = 'hello';
if (foo == '10' && bar == 'hello') {
 alert('something');
}

All three versions works identically. So, is it a good practice to use quotes around 10, 100 and another purely-numeric variable values?

I hope, this question will not be closed as "opinion-based", because there are probably some real use cases, from which we could say which version is the most correct.

john c. j.
  • 725
  • 5
  • 28
  • 81

1 Answers1

1

Some (self) explanations to this topic:

console.log(1 == '1')
console.log(1 === '1')
console.log(1 == true)
console.log(1 === true)
console.log('1' == true)
console.log('1' === true)

=== will also make a type check, which explains the behaviour.

Difference between == and === in JavaScript

greetings

messerbill
  • 5,499
  • 1
  • 27
  • 38