Is it possible to use functions within a condition?

2

I was analyzing websites when I came across the following excerpt:

if (console.log(i), i && void 0 !== i.name) {
    // code here...
}

I tested this:

var i = {name: "mizuk"};
if (console.log(i), i && void 0 !== i.name) {
    console.log("condição verdadeira!");
}

What I understood from the code was:

// se 'i' não estiver vazio e 'i.name' não tiver o mesmo valor e tipo 
// que 'undefined' faça:

What I want to know is:

- > where does 'console.log (i)' come in?, is it part of the condition or was it simply called in the middle of the sentence?

- > if it was called, is this something common or is it a gambiarra?

- > if it's something common, can I perform other functions that way?

Thank you in advance for your help.

    
asked by anonymous 02.03.2018 / 17:58

3 answers

3

1 - console.log is there to display what was compared in if, but can be overridden by other functions. In this example this line means, execute the function (console.log) and compare, if true, to enter if .

2 - Common or gambiarra, I do not see much cases that this will really be necessary.

3 - Yes, you can, as in the example below:

var i = {name: "mizuk"};
if (concatenarEExibir(i), i && void 0 !== i.name) {
    console.log("condição verdadeira!");
}
function concatenarEExibir(i){
  console.log('Nome:' + i.name);
}

OBS:

In the example I used the same console.log command, but there could be anything.

    
02.03.2018 / 18:06
1

The console.log() function is used to display something in the browser console.

In spite of being a function, it does not return, Javascript has some forms of Display, Console.log() is one of them.

Correct is to use Console.log() separated from code logic. Including in the logic of the code is gambiarra and will give work for later as it will have to take.

    
02.03.2018 / 18:14
1

console.log(i) has no practical function in this if unless it prints the value in the console.

Without the console.log the if would only be:

if(i && void 0 !== i.name) {
    console.log("condição verdadeira!");
}

The condition is true because i is true (an existing object) and void 0 ( undefined ) is different in value and type of i.name .

I do not know what would be the function of using console.log within if (if there is one). First time I see this. Also because the message displayed in the console does not appear on the page, that is, it has no practical effect, except for developers.

Probably this console.log is just to check the value of the variable, this is even common at development time, but I prefer to use out of if because then it gets even easier to remove the line:

var i = {name: "mizuk"};
console.log(i);
if (i && void 0 !== i.name) {
    console.log("condição verdadeira!");
}
    
02.03.2018 / 18:08