Skip to content

Defining variables inside the If statement in JavaScript

If statement is used validate an expression to boolean value, like checking a primitive/constant value against a JavaScript variable, but sometimes we would have wrongly assigned a value to a variable instead of comparing.

if(status = "end")
Advertisements

So what happens now? An error? The answer is NO!
Here we are assigning a value to status variable. if status is already declared the text “end” is assigned, if status is not declared prior to this statement, a new variable is created and value is assigned.

An example:

if (name = "poopcode") {
  console.log("Name defined!"); 
} else {
  console.log("Name not defined!)");
}

console.log(name);


//Name defined!
//poopcode
See also  How to handle paste event in textarea HTML element?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.