How to use ‘IF’ Statement Comparison Operator Incorrectly In Javascript
We’re talking about the “==” operator and the “=” operator. The first one does a comparison and the second assigns a value to a variable. The error created depends on the language. Some languages will throw an error, but JavaScript will actually evaluate the statement and return true or false.
Example:
javascript
// This if statement returns false (as expected) because x is not equal to 5: let x = 0; if (x == 5); // This if statement returns true (not expected) and Assigns 5 to x: let x = 0; if (x = 5); |
Javascript is loosely typed, except in switch statements. JavaScript is NOT loosely typed when it comes to case comparisons.
Example:
javascript
let myVar = 5; if (myVar == '5' ){ // returns true since Javascript is loosely typed alert( 'Welcome to w3wiki' ); } switch (myVar){ case '5' : // this alert will not show since the data types don't match alert('Welcome to w3wiki'); } |
JavaScript Common Mistakes
JavaScript is an easy language to get started with, but achieving mastery takes a lot of effort, time, and patience. Beginners often make a few well-known mistakes.
In this article, we’ll cover some of the most common learning mistakes people make and find out how to overcome them. Many of these tips will be applicable outside of JavaScript or even web development.
Contact Us