Is there a way i can include the break statement in a ternary operator in this scenario?
I am trying to replace the if… else inside a loop for a ternary operator. I stated my condition and wrote the code to run but after i thought, and included a break keyword or statement ( i don’t know what it’s called…with semi-colon though) i got an error even after providing the else part. I would have to remove the break statement before the code will be valid.
Also, how can i successfully skip an else part of a ternary operator - just like if without an else? I have searched for that thread on stackoverflow, but i am not understanding what the solution was – a newbie
Sorry i am not providing a code snippet, but i think i am explained well enough.
We would need to see the code that you’re trying to replace and what you are trying to accomplish in order to help. It sound’s though like you are trying to do something that you really do not want to use a ternary for.
This snippet is inside a function that searches for a name. So, i am trying to stop the loop from continuing after finding the first match.
I successfully used an if… else, but just wanted to to try it out with ternary and then switch operator
You’re trying to break out of the parent for loop? You definitely wouldn’t want to write a ternary like that. Ternaries should only be used when the situation is so simple that the ternary is easier to read than an if/else block.
I have one more question, please.
Can a variable have more than one value stored at the same time? sounds foolish?
let me show why i asked that way.
i have this:
let searchValue = input.value.toUpperCase();
input.value = '';
input.focus();
for (let i = 0; i < names.length; i++) {
console.log(names[i]); // why billi:1234 here on the console?
let indexess = names[i].split(':')
console.log(indexess); /* i said it should store inside
indexess but i have 4 objects stored there
i know it's the loop result that is confusing me.
*/
if (searchValue === indexess[0].toLowerCase()) {
para.textContent = `${indexess[0]}'s number is ${indexess[1]} `;
break;
} else {
para.textContent = 'try again';
}
}
}
)
what made me confused is the conversion by the loop from array to string and then to array let indexess = names[i].split(':') – i am not really sure what happened there though, but on vs code the results came from the same line. i really want to understand the result of indexess.
No. You can reuse the same variable name in different scopes, but they refer to different memory locations.
I’m not entirely sure what you’re talking about, you assigned indexess with a .split() method, so it would contain an array. I’m guessing that you are seeing an array of four items?
Yes, on the console i am seeing four different arrays when i log indexess.
More like i am asking where those arrays are stored 'cause they all came from the same line