3

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);
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

JSHint works perfectly for my needs, now i won't screw up as much ;) Thanks!
You are most welcome. Can you please upvote if useful.
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.

4 Comments

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 "="
eslint has a rule called no-cond-assign, with the right config this would flag it up to you eslint.org/docs/rules/no-cond-assign
Just because i'm curios when would you use an assignment in an if statement, and it would make sense?
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: stackoverflow.com/questions/151850/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.