Is it possible to use functions within a condition?

Asked

Viewed 90 times

2

I was going through some websites when I came across the following excerpt:

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

I tested it out:

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)' fit into all this? , it is part of the condition or it was simply called in the middle of the sentence?

-> if he was called, it’s something common or it’s a gambiarra?

-> if it’s something common, I can perform other functions like this?

Thanks in advance for all the help.

3 answers

3


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

2 - Common or common, I don’t see many cases that this will be really necessary.

3 - Yes, it 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 console.log command, but there can be anything.

1

The console.log(i) has no practical function in this if other than printing the value on the console.

Without the console.log the if would just:

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 don’t know what function to use console.log within a if (if there is one). First time I see this. Because the message displayed on the console does not appear on the page, that is, it has no practical effect, except for developers.

Likely that console.log whether just to check the value of the variable, this is even common at the time of development, but I prefer to use outside the 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!");
}
  • 2

    I believe q console.log is kind of useless in the end anyway, but as to perform a function in the same place, can serve to save a line, but also could not see real utility.

1

The function console.log() serves to show something in the browser console.

Despite being a function, it gives no return, Javascript has some forms of Display, the Console.log() is one of them.

The correct thing is to use the Console.log() separate from code logic. Include in code logic is gambiarra and will give work for later as will have to take.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.