简体   繁体   中英

what is the meaning of “if (!J || !S)” in javascript?

var new= function(J, S) {
    if (!J || !S) return 0;

Can anyone help me to understanding this if condition?

It is basically going to return 0 (a “falsey” value itself) if either of the arguments J or S are "falsey", which in JavaScript means they are equal to undefined , false , NaN , null , 0 or '' (empty string).

The intention is probably to check that the arguments are not missing before going on to the rest of the function, presumably because the function will error or return invalid results if either argument is missing.

The function returns 0 if either ( || ) J or S are falsy :

  • false
  • 0
  • '', "", `` (empty string)
  • null
  • undefined
  • NaN

If both values are truthy, it returns undefined .

 var nu = function (J, S) { if (!J || !S) return 0; } // booleans console.log(nu(true, true)); console.log(nu(true, false)); console.log(nu(false, false)); // other truthy/falsy values console.log(nu(1, 1)); console.log(nu(1, 0)); console.log(nu(true)); // S is undefined console.log(nu('foo', '')); console.log(nu({}, null)); console.log(nu(1, NaN)); 

If J = "" or null or undefined, 0, NaN, false the !J will be true.

!"" -> true
!null -> true
!undefined -> true
!NaN -> true
!0 -> true
!false -> true

It will check J, S variable is empty or null or undefined or not.

if (!J || !S) is checking if at least one of the variables J or S evaluates to a falsey value, and then the expression is going to evaluates to true and therefore execute the return 0 .

But notice that you have an Uncaught SyntaxError: Unexpected token 'new' in your code, and that is because new is a JavaScript reserved word that can't be used as a variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM