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 4 years ago.
Improve this question
Suppose my code is as follows:
const days = ['Monday', 'Tuesday'];
for (const day of days) {
console.log(day);
}
It prints out 'Monday' and 'Tuesday'.
If for whatever reason, days is undefined, then I get a runtime error.
I could handle this by putting in code like the following:
if (undefined == days) {
// logic here
}
To me, that seems a little clunky. Is there a way to have the for ... of loop ignore undefined values? Basically, treat it like a zero-length array and so the logic inside the for loop won't execute, but it won't throw an error either.
You could always use a forEach, and a logical or || within a parenthesis block.
(days||[]).forEach(day=>{console.log(day)});
I suppose you could also use this in your for loop.
for(let day of (days||[])) {
console.log(day);
}
The best way to check for a empth value is to initialize a variable before using it, Either is a string, object or array. This way the programm understand the variable and can easily suggest function for you.
//Initializing Varable
let stringVariable = '' ;
let objectVariable = {};
let arrayVariable = [] ;
In your case
let days = []
for(let day of (days)) {
console.log(day);
}
Related
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 2 months ago.
Improve this question
function takaAnumber() {
startHealth = parseInt(prompt("give a positive number "));
//here i am calling the same function inside the if()block if the input is not a number or lesser than 0 is this a good practice?
if (isNaN(startHealth) || startHealth <= 0) {
takaAnumber();
}
// checkItsnumber();
playerHealth = startHealth;
monsterHealth = startHealth;
adjustHealthBars(startHealth);
}
I am trying get a number as an input, by calling a function. Inside the function the I have wrote a if() statement to check its a number if isn't it will call the function again. My question is it safe(good practice) to call a function inside it's own function in a large project code.
Your approach needs a return statement, because if the function returns, it goes on with the code of the calling function.
function takaAnumber() {
const startHealth = parseInt(prompt("give a positive number ")); // declare variables
if (isNaN(startHealth) || startHealth <= 0) {
return takaAnumber();
}
// other code
}
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 1 year ago.
Improve this question
I am using this method to find the frequency of words, however i am a bit confused with the whole code.
Here is the code:
function check(){
var word = document.querySelector('textarea').value.split(" ");
frequency ={};
word.forEach(function(i){
console.log(i)
if(!frequency[i]){
frequency[i] = 0;
}
frequency[i]+=1
})
console.log(frequency)
}
<textarea></textarea>
<button onclick = 'check()'>check</button>
I just wonder what does the i stand for and what does the frequency[i].
Could someone explain to me a little bit because I think this code is not quite friendly for me, the beginner.
foreach iterates over array, and as paramter has function into which is passed as parameter actual element of array. So i in this function is actual element of 'word' array.
for object frequency is frequency[i] the i'th element. At start, this object is empty, so frequency[i] will be undefined, but in foreach loop you filling this object with some values so in next iterations there may by some values
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
handleChange(e) {
const index = Number(e.target.id.substring(e.target.id.length - 1, 19));
const copyFormArray = JSON.parse(JSON.stringify(this.state.educationData));
copyFormArray[index][e.target.name] = e.target.value;
this.setState({
educationData: copyFormArray,
});
};
What does this handleChange method do, specifically in the index variable? I understand what substring and the Number constructor do but the second argument I cannot find any answers for this specific question although it works as intended.
Substring works in a tricky way, if second argument (in your case 19) is less than first argument - then they will be "swapped", and if not - it will just take text between indexes (argument1 and argument2).
So say for example i have a string:
var x = "aaaaa-5";
if i will write:
x.substring(x.length-1)
It will give me "5".
Then if i will write:
x.substring(3,6)
It will give me "aa-"
But then if i will write:
x.substring(6,3)
It will be exactly the same as previous call - "aa-"
So internally logic of substring is kind of like this:
function substring(start,end) {
if(start > end) {
var buf = end;
end = start;
start = buf;
}
//... other logic
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The book that I'm studying says about iterating over arrays with every that:
The function these methods use must follow one ruleāit must accept
three arguments like the following code:
function functionName(value, index, array) {
// do something here
}
Does that mean that I must always use 3 arguments? If so then why does this code work?
var numbers = [ 1, 2, 2 ];
function isLessThan3(value) {
var returnValue = false;
if (value < 3) {
returnValue = true;
}
return returnValue; }
document.write(numbers.every(isLessThan3));
There is no limitation on how many arrguments you can put in a function with Javascript.
you have a very good explenation about this topic in the next answer by #Niet the Dark Absol
https://stackoverflow.com/a/22747272/1283672
i believe that the book was reffering to something more specific within it's scope.
And just to be clear you can put no arrgs in a function either.
It's a bit ugly, the code, you have, but there is help. You might use the following without a temporary variable. Just return the result of the comparison.
function allLessThan3(value) {
return value < 3;
}
var numbers = [1, 2, 2];
console.log(numbers.every(allLessThan3));
No, you can use from 0 to 3 arguments
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 8 years ago.
Improve this question
I don't know what is better to use:
var s = "2";
var i = 2;
if(s.toString() === i.toString()){
//do something
}
//OR
if(s == i){
//do something
}
Thanks for the help
You are actually comparing two separate things, in first, you are casting both the variable values to a string and comparing, and the other comparison is lose one i.e you are not actually checking the data types of those variables. so it will return true if you compare string with int with a same value.
According to me, what you should be using is === which will not only compare the values but their data types as well because the ones you are using are both considered lose.
If you do not consider at all about data type then using == will suffice. You don't have to cast the values to a string.
In your first example if for any reason you get a 2 with a space, it will evaluate false (even with ==):
var s = " 2"; // 2 with a sneaky space
var i = 2;
if(s.toString() === i.toString()){ // will be false
//do something
}
Personally I prefer using ===, but I would change the values to integers, instead of to strings.
var s = " 2"; // 2 with a sneaky space again
var i = 2;
if(Number(s) === Number(i)){ // will be true
//do something
}
You don't need the second Number() but, I don't know, you may get data that is also a string.