function showWarning(options) { var width = options.width || 200; // по умолчанию var height = options.height || 100; var contents = options.contents || "Предупреждение"; } showWarning({ contents: "Вы вызвали функцию" // и всё понятно! }); 

How to check that the argument that is passed to the function is an object?

    4 answers 4

    The object in JS is a lot, so this is a pretty general check.
    You can do this:

     function test(config){ if(Object.prototype.toString.call(config).toLowerCase() === '[object object]'){ console.info(`${JSON.stringify(config)} - объект!`); }else{ console.info(`${config} - что-то иное, не объект :)`); } } test(42); test(_ => 42); test({0: 42}); 

    • I wouldn't be surprised if the author even asked for: if (options != null) - Grundy
    • @Grundy, we teach the good here, not to write the code of the Indians :) - user207618
    • and where then is the example with destructuring? :-) - Grundy
    • @Grundy, to teach, and not to drive a beginner crazy, whose head will burst with diversity :) By the way, what about her? - user207618
    • something like this: function showWarning({width:width=10,height:height=20}) { - Grundy

    For example, like this:

     option.constructor == Object 

    Checks whether the function is directly a constructor or not.

    typeof returns 'object' for both arrays and null.

    • one
      At null the property call will throw out an error - user207618
    • By the way.) Then your option is the best. - A. Gusev
    • Fixed, if desired, through try...catch . True, why so difficult? :) - user207618
     function showWarning(options) { if (typeof options == "object" && options != null) { console.log("Является объектом"); } else { console.log("Не является объектом"); } } 
    • one
      typeof null suddenly - "object" - Grundy
    • @Grundy, is it sudden? - user207618
    • @Other, generally speaking yes :) - Grundy
    • @Grundy, you don't know why you didn't fix it? In my opinion, this is a bug, even if it is fixed in strict mode. By the way, arrays are also considered objects, which are defined as. - user207618
    • @Other, no clue. Most likely, in order not to break a bunch of scripts that can somehow use it. typeof returns an object for everything except: undefined, function, symbol, and primitives number, string, boolean - Grundy
     if(options === 'object' && options != null)