2

I'm starting to get annoyed when I'm using if statements. Sometimes i'm a bit to fast and i only use one "=" in my IF statement and then run my code. At first glance there is nothing wrong, but as i use my application weird stuff is happening. Then I use some time to go through my code to figure out that i only used one "=" in my IF statement.

So i'd like to know why an IF statement with one "=" get valid?

I remember some time ago when visual studio code would let me know through validation that it wasn't a valid statement. Or is it a vs code change that allow users to use one "=" in their if statements? Or is it just valid code?

if (k = array[i])
{
    console.log(k);
}
NotJohn
  • 88
  • 1
  • 9

2 Answers2

3

Try installing "VS Code JSHint extension" in your Visual Studio Code. If you are also interested you can use "vscode-tslint" for type script. It helps a lot.

Sunoj Vijayan
  • 138
  • 1
  • 12
1

It is a valid statement. However, it's very rarely what you actually want to do. A single equals is an assignment, which returns the value which was assigned:

console.log(a = 'hello');

Almost always you want to use a triple equals === as it's typically the safest way to make comparisons.

As to when vscode stopped flagging this up as a problem, that depends on how you've got your vscode setup. It isn't strictly a problem but I'm sure there are some linters which would alert you to this as a problem. You'd need to provide some more in depth information as to what your vscode setup is, which is probably a separate question altogether.

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
  • Thanks for your answer i'll try to find some extension that will let me know when i forgot to put in the proper amount of "=" – NotJohn Jan 28 '19 at 09:09
  • 1
    `eslint` has a rule called `no-cond-assign`, with the right config this would flag it up to you https://eslint.org/docs/rules/no-cond-assign – OliverRadini Jan 28 '19 at 09:33
  • Just because i'm curios when would you use an assignment in an if statement, and it would make sense? – NotJohn Jan 28 '19 at 10:14
  • There are a few edge cases, I can't say I've ever run into them personally, but this answer goes through a few of them: https://stackoverflow.com/questions/151850/why-would-you-use-an-assignment-in-a-condition – OliverRadini Jan 28 '19 at 10:21