juicy89
juicy89

Reputation: 458

Can someone explain what this line is doing

Can someone help me understand what is happening on the below line of this function?

function getContainer(container, defaultContainer) {

    //this line below
    container = typeof container === 'function' ? container() : container;

    return ReactDOM.findDOMNode(container) || defaultContainer;
}

the container is being assigned the result of typeof container, but if the container is equal to a function, invoke that function.

I'm a bit head-blagged. This code was pulled from the Material UI docs for the react component Modal

Upvotes: 2

Views: 86

Answers (3)

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

The equal would be:

if(typeof container === 'function')container= container();
else container = container;

which calls container if it is a function and stores the result in the variable named container. It it isn't it does nothing.

Upvotes: 3

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

It is saying the following:

if container is a function assign it to a variable called container and the function will be invoked, else set the variable container as the argument container passed to the getContainer function.

You could also write it like this, which maybe easier to read:

if (typeof container === 'function') {
   container = container();
} else {
   container = container;
}

In your example it is using the ternary operator which is another way of writing an if/else statement. You can read more here.

Upvotes: 4

inrsaurabh
inrsaurabh

Reputation: 692

First, know the basics and the difference in the way we reference the function/method in js.

Let's say there is a function named container

function container() {

    let name = 'Js';

    return name;
}

console.log(container()); //js as we got the value here

console.log(typeof(container())) // string as this time we have value which of string type

console.log(typeof(container)) // function as we are pointig to function

we got complete function structure in the console when we reference only function name without ()

  console.log(container);  
    ƒ container() {

        let name = 'Js';

        return name;
    }

To know what is typeof

So in your question, it checking what is passed and last thing to know is

condition ? expr1 : expr2  

i.e ternary operator

Upvotes: 0

Related Questions