Which conditionals would you prefer [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
Which way of defining a string would you use?
Are there better ways to do this with even more strings?
I want to set abbreviations for a large set of predefined strings.
If style 1:
let stat = str3;
if (stat === "str1") {
stat = "string1";
} else if (stat === "str2") {
stat = "string2";
} else if (stat ==="str3") {
stat = "string3";
} else if (stat === "str4") {
stat = "string4";
} else if (stat === "str5") {
stat = "string5";
}
If style 2: (I think this is the best visually)
let stat = str3;
if (stat === "str1") stat = "string1";
else if (stat === "str2") stat = "string2";
else if (stat === "str3") stat = "string3";
else if (stat === "str4") stat = "string4";
else if (stat === "str5") stat = "string5";
Switch style:
let stat = str3;
switch (stat) {
case "str1":
stat = "string1";
break;
case "str2":
stat = "string2";
break;
case "str3":
stat = "string3";
break;
case "str4":
stat = "string4";
break;
case "str5":
stat = "string5";
break;
}

Put all the data in an object and then just access the values by key.
const dict = {
str1: 'string1',
str2: 'string2'
};
const stat = 'str1';
console.log(dict[stat]);

In my opinion you should use Switch because it's faster than "if" and also if it gets bigger it will be easier to read.
A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too
You could read More in this link

Related

How to break the loop of element by id ().innerText is undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to apply a condition where, if var bprodp = document.getElementById('ID_BPMPROD_' + rowIndex).innerText is undefined or null it should break the while loop and move to next part of code.
I tried if (bprodp = null) and (if bprodp = '') conditions but it always failed with an error "Unable to get property 'innerText' of undefined or null reference"
Can any one help me, how can i do this.
var count = 0;
var rowIndex = 1;
while (rowIndex <= 4){
var bprodp = document.getElementById('ID_BPMPROD_' + rowIndex).innerText
if (bprodp = null){
break;
}
var prodp = document.getElementById('ID_PROD_' + rowIndex).innerText;
rowIndex++;
if (bprodp != prodp) {
count++;
}
}
You should be checking the return value of document.getElementById(), not innerText. If the element exists, innerText will always be a string, never null.
while (rowIndex <= 4) {
var bprodp = document.getElementById('ID_BPMPROD_' + rowIndex);
if (!bprodp) {
break;
}
var prodp = document.getElementById('ID_PROD_' + rowIndex);
rowIndex++;
if (bprodp.innerText != prodp.innerText) {
count++;
}
}
Compare vales not assign:
If (bprodp === null){
....

I need to sort it out this quiz [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
my code is not working at all
I need to solve this quiz
question is write convertToString as function !
this function should convert to string from parameter
ex )
let output = convertToString(120);
console.log(output); // --> '120'
let output2 = convertToString('hello');
console.log(output2); // --> 'hello'
let output3 = convertToString(true);
console.log(output3); // --> 'true'
this is what I wrote
function convertToString(anything) {
if (typeof anything === 'number' && typeof anything === 'boolean') {
let ret = anything.toString()
} else {
return anything;
}
return ret1;
}
convertToString(120);
The easiest way to convert anything is by making + operation with ""
function convertToString(anything) {
return "" + anything
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
console.log(convertToString(null));
console.log(convertToString(undefined));
Zero checks necessary.
function convertToString(val) {
return String(val);
// or return val.toString();
// or return '' + val;
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));

Javascript coding quiz not adding up

I'm trying to do a simple quiz where it should sum the correct answers and incorrect answers. The thing is although I put two out of three correct answers, I keep getting the same result for the correct and incorrect array: 0. So there must be something wrong at the end, in the evaluate function. Thanks in advance
var responsesArray= [];
var correct=[];
var incorrect= [];
function question2() {
var firstQuestion = prompt('Does null === 0 ? (Yes or No)')
// why do you need to convert the answer to lowercase?
if (firstQuestion.toLowerCase() === 'yes') {
firstQuestion = true
} else if (firstQuestion.toLowerCase() === 'no') {
firstQuestion = false
} else {
// what if the user writes something other than yes or no?
// they will have to answer the question again
alert("Please answer either Yes or No");
return question2();
}
responsesArray.push(firstQuestion); // add the true or false value to the responses array
}
question2();
function question3() {
var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
js = js.toLowerCase();
switch (js) {
// your own answers
case "livescript":
console.log("Correct!");
break;
case "Java":
console.log("wrong");
break;
case "JavaLive":
console.log("wrong");
break;
case "ScriptyScript":
console.log("wrong");
break;
default:
console.log("Sorry the answer is LiveScript");
}
responsesArray.push(js);
var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
mine= mine.toLowerCase();
switch (mine) {
// your own answers
case "ruby":
console.log("Yeah!");
break;
case "html":
console.log("ouuu I'm sorry for you");
break;
case "javascript":
console.log("Yeah but so so");
break;
}
responsesArray.push(mine);
}
question3();
function evaluate(responsesArray)
{
for (var i = 0; i < responsesArray.length; i++)
{
if (responsesArray[i] === true|| "livescript" || "ruby")
{
correct++;
} else{
if (responsesArray[i] !== true|| "livescript" || "ruby") {
incorrect++;
}
}
}
Define an array to store the correct answer and then compare correct and user response and easily can identify whether it is correct or not.
Please check below snippet.
var responsesArray= [];
var correct=0;
var incorrect= 0;
//Correct answer key initialize
var index = 0;
//Initialize array to store correct answer.
var correctAnswers = [];
function question2() {
//Save correct answer.
correctAnswers[index++] = "yes";
var firstQuestion = prompt('Does null === 0 ? (Yes or No)')
// why do you need to convert the answer to lowercase?
if (firstQuestion.toLowerCase() === 'yes') {
console.log("correct");
firstQuestion = 'yes'
} else if (firstQuestion.toLowerCase() === 'no') {
console.log("in-correct");
firstQuestion = 'no'
} else {
// what if the user writes something other than yes or no?
// they will have to answer the question again
alert("Please answer either Yes or No");
return question2();
}
responsesArray.push(firstQuestion); // add the true or false value to the responses array
}
question2();
function question3() {
//Save correct answer.
correctAnswers[index++] = "livescript";
var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
js = js.toLowerCase();
switch (js) {
// your own answers
case "livescript":
console.log("Correct!");
break;
case "Java":
console.log("wrong");
break;
case "JavaLive":
console.log("wrong");
break;
case "ScriptyScript":
console.log("wrong");
break;
default:
console.log("Sorry the answer is LiveScript");
}
responsesArray.push(js);
//Save correct answer.
correctAnswers[index++] = "ruby";
var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
mine= mine.toLowerCase();
switch (mine) {
// your own answers
case "ruby":
console.log("Yeah!");
break;
case "html":
console.log("ouuu I'm sorry for you");
break;
case "javascript":
console.log("Yeah but so so");
break;
}
responsesArray.push(mine);
//Call function to evaluate correct or incorrect answer
evaluate(responsesArray,correctAnswers)
}
question3();
function evaluate(responsesArray,correctAnswers)
{
for (var i = 0; i < responsesArray.length; i++)
{
//Match response with correct answer.
if (responsesArray[i] === correctAnswers[i])
{
correct++;
} else{
if (responsesArray[i] !== correctAnswers[i]) {
incorrect++;
}
}
}
alert("Correct : "+correct+" and Incorrect : "+incorrect);
}
The way you test for correct answers is wrong. Instead define an array with the correct answers and verify them as follows:
var correct = incorrect = 0; // better initialise your variables
function evaluate(responsesArray) {
var correctAnswers = [true,"livescript","ruby"];
for (var i = 0; i < responsesArray.length; i++) {
if (responsesArray[i] === correctAnswers[i]) {
correct++;
} else {
incorrect++;
}
}
}
What you had was:
if (responsesArray[i] === true|| "livescript" || "ruby"){
But this means:
if the answer was true, or .... "livescript" is true, or ... "ruby" is true, then
As JavaScript considers strings to be truthy, the if condition would always be true.
Note also that there is no need to do a second if, since the else part is only executed if the first if condition was false, which means you already have filtered for the cases where the answer was wrong.
Finally, your counter variables should be defined before you start incrementing them. It works without this definition, but if one of the two variables is not incremented, it will still be undefined after your call to evaluate. Better always define your variables.

How to reduce "if statement" conditions? [reduce the conditions inside the if statement]

after days of hard thinking i choose to ask that question. I have if statement with multiple conditions:
//var current is array of arrays of integers
if((current[rot][0] + x)<blocks.length
&& (current[rot][1] + x)<blocks.length
&& (current[rot][2] + x)<blocks.length
&& (current[rot][3] + x)<blocks.length
&& !$(blocks[current[rot][0]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][1]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][2]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][3]+x]).hasClass("blockLand"))
{
//something to happen here ONCE!
}
Because i want something inside to happen just once i think i cant use for loop.
So my question is: is there a possible way to reduce the conditions number? and how?
P.S.: Yes i figured out that i can use flag (true/false) inside and do my stuff outside this if, in another if - but i think that not always gonna work, because for every loop the flag will be different.
var b = true;
for (var i = 0; i <= 3; i++) {
// In two lines for being clear, but it's possible just in one
b = b && (current[rot][i] + x)<blocks.length
b = b && !$(blocks[current[rot][i]+x]).hasClass("blockLand");
// You could speed it up this way.
if(!b) break;
}
if (b) {
//something to happen here ONCE!
}
I think I understand what you are asking but let me know if there is anything else I can do.
JavaScript has a ternary (conditional operator) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This operator allows you to assign true/false values based on an internal if/else condition.
Here is some code for you to explain this...
window.onload = function() {
var one = 1;
var two = 2;
console.log(one > two ? "greater" : "not greater");
};
You can also use a Switch statement which you can read about here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch.
Here is an example of a switch statement.
window.onload = function() {
var string = "testing this out";
switch (string) {
case "testing this out":
console.log('testing this out found in condition one');
break;
case "testing":
console.log('found testing');
break;
default:
console.log('not found');
break;
}
};
Let me know if I can improve this.

Bad Assignment, Logical Operators [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Am learning Javascript in code academy. This is the test I have been given,
"Inside the eat function, create an if statement that returns true only if both hungry and foodHere are true, and false otherwise."
My code below is executing but it has a warning. What could be the problem?
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere = false){
console.log("Choose one");
}
};
eat();
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else {
console.log("Choose one");
}
};
eat();
the problem was, that you tried to assign a value in the condition foodHere = false. If you want to compare things you need == and if you want to be sure that the types are the same use ===.
But you don't need that condition at all!
The assignment want you to return a boolean value (true or false) and not to print something, so i guess your code should look like this:
var hungry = true;
var foodHere = true;
var eat = function() {
return (hungry && foodHere)
};
eat();
Single = is for assignment, == is for comparison
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere == false){
console.log("Choose one");
}
};
eat();
Anyways, you don't need the second comparison since if the first one is false it will always go through the else
I just want to give additional information for emilioicai's answer, there are two kind of "equal comparison" in JavaScript
equal to ( == )
exactly equal to ( === )
Reference: http://www.w3schools.com/js/js_comparisons.asp
= is for assignment, == is for value comparison and === is for value and datatype comparison. So you can use == while comparing with the false. But this is not the best practice. We always uses '!' negation operator while converting true to false
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(!hungry || !foodHere){
console.log("Choose one");
}
};
eat()
I am using || operator assuming that any one needs to be false.You can go for && if both false are required

Categories