1

What string console && (typeof console.log === "function") && console.log('contains called'); is doing in this function:

(function ($) {
$.validator.addMethod('contains', function (value, element, param) {
    console && (typeof console.log === "function") && console.log('contains called');
    if (this.optional(element)) { return true; } // let required rule deal with this.

    var pattern = new RegExp('' + param, "gi");
    return value && ('' + value).match(pattern);
}, "Part of the word is invalid");

$.validator.unobtrusive.adapters.add('contains', function (options) {
    var element = options.element,
            message = options.message;
    options.rules['contains'] = $(element).attr('data-val-contains-word');
    if (options.message) {
        options.messages['contains'] = options.message;
    }
});
})(jQuery);

I would understand if that string was like: var var1 = console && (typeof console.log === "function") && console.log('contains called');

or like: if(console && (typeof console.log === "function") && console.log('contains called'))

It's not a buggy code. It's working.

4 Answers 4

1

It's just a less readable way of writing:

if (console && (typeof console.log === "function")) {
  console.log('contains called');
}

It (mis)uses the fact that you can write an expression that doesn't do anything with the result, and that a statement is also an expression, so it can be written inside an expression to do something.

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

Comments

1

It just writes something to the browsers console.. But only if that console is available and if it has a 'log' function. The first 2 conditions can prevent the third from running, thus not causing a js error in case console.log(..) does not exist.

Comments

1

The runtime checks the first condition. If there isn't a console, it stops checking the other conditions because false && ... is in every case false. If there is a console the runtime checks if console.log is a function and if so it logs something to the console. This is called short-curcuit-evaluation. Otherwise the runtime would always try to execute each condition which would lead to runtime errors if e.g. there were no console object.

Comments

0

It's doing the same as

if (console && (typeof console.log === "function")) {
    console.log('contains called');
}

The interpreter will stop as soon as something is false so console.log won't be called if console doesn't have a log function. It won't check if this function exist neither if console doesn't even exist.

Comments

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.