Understanding JavaScript Using Logical Operations Between Same Variables for Branching

Asked 1 years ago, Updated 1 years ago, 13 views

I'm a beginner at JS.
When I was reading the sample code, I found something I didn't understand and it didn't get stuck in my search, so please let me ask you a question.

var content=(object of type String);

if(content&&content!==""){
    // Processing
}

The above code appears in the sample code, but I don't understand the meaning of the part used in the if statement.
Please teach me.

javascript

2022-09-30 17:14

2 Answers

If the content value is null or undefined, I think it is to determine false.

For content!==" only, the value of the content is null, undefined, or true.
Therefore, using methods such as .toUpperCase() in the if block results in an error:

Leave
var content;//undefined.
Set content=null;// or null.

If(content!==""){//true is determined
  console.log(content.toUpperCase()); // Error here
}

If content&content!==", the first content is false, you can exclude null and undefined.


2022-09-30 17:14

In if(content&content!==""), & is the logical AND operator.For expr1&expr2 , return expr1 if expr1 is false, or return expr2.Therefore, if both operations are true, return true, otherwise return false.

Next, the authenticity of content is 0, -0, null, false, NaN, undefined, empty string (").

On the right, content!==" is not an empty string.For JavaScript, if(content&content!=="") can exclude empty strings only with if(content)

if(content&content!=="") in the sample is if(content!=="") and Content got an error when null, so if(content&content!==") reflected many other programs.


2022-09-30 17:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.