If/else inside function JavaScript - javascript

Please don't be too hard on me as I've just started in school and I'm using Ubuntu. I've written this code (which might be the simplest code ever) that simply tells about the conversion of bytes into other units (Mebi, Kibi...). When I use the console.log it always displays Kibi.
function unit(x){
var x;
if (x=10){
x='Kibi';
} else if (x=20){
x='Mebi';
} else if (x=30){
x='Gibi';
}
return x;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
The thing here is that as I said it always displays Kibi on all console outputs, the funny thing for me that I don't understand is that if I change the first console.log for
console.log('2^10 bytes are 1 ' + unit(20) + 'byte'
it will still display all console outputs with Kibi even if I never called unit(10).
I really don't understand why this is happening and any help would be greatly apprecieated. Thank you.

you've declared variable x and not set value for it, and = just for left assign follows my code
Heres my code:
function unit(x){
var nickname = '';
if (x===10){
nickname='Kibi';
} else if (x===20){
nickname ='Mebi';
} else if (x===30){
nickname ='Gibi';
}
return nickname;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
your codes error:
variable x redeclared
x=10 means let 10 assigns to variable x.
hopes to help you
edited:
for your question, maybe this code will be better
function unit(x){
var nickname = '';
switch(x){
case 10:
nickname = 'kibi';
break;
case 20:
nickname = 'Mebi';
break;
case 30:
nickname = 'Gibi';
break;
}
return nickname;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");
I tell you
Variables should not have ambiguity, one variable do one thing.
you can follow to #epascarello and #Keith advice

All that is changed in this snippet was exactly what the two comments suggested. Remove the extra initialization of x and change "=" to "==" in the comparisons.
function unit(x){
if (x == 10){
x='Kibi';
} else if (x == 20){
x='Mebi';
} else if (x == 30){
x='Gibi';
}
return x;
}
console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");

Related

Am I correct about .toFixed() and decimals?

I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))

Javascript switch(true) executes false statements?

Im looping over a collection of coordinate values and doing math on the coordinates to see if the calculated values are in a hashmap. if they are in the hash map then I want to run an additional function. since I had multiple cases I wanted to check for each coord in the collection, I figured a switch statement would be cool to use to replace my if statements so all my checks could be visually and logically grouped. When I replaced my if statements with a switch, my code returned bad results. When I debugged, I realized the switch statements would sometimes execute even when the case was false(I added console.logs to output the result of the same switch condition and it would print false, but should only run when true). Here is a small example:
var idm = {0:1, 3:1, 9:1, 10:1, 11:1, 12:1, 20:1, 21:1, 23:1}
var findNeighbors = function(b) {
var u,d,l,r,lRow,rRow;
var currentBuilding = parseInt(b);
var currRow = Math.floor(currentBuilding/column);
//remove value from map so we dont recount it.
delete idm[currentBuilding];
u = currentBuilding - column;
d = currentBuilding + column;
l = currentBuilding - 1;
lRow = Math.floor(l/column);
r = currentBuilding + 1;
rRow = Math.floor(r/column);
console.log("current idx:" + currentBuilding);
console.log("u:" + u + ", d:" + d + ", l:" + l + " r:" + r);
// debugger;
switch(true) {
case (idm.hasOwnProperty(u) === true):
console.log((idm.hasOwnProperty(u)));
console.log("map has " + currentBuilding + " -> u: " + u);
findNeighbors(u);
case (idm.hasOwnProperty(d) === true):
console.log((idm.hasOwnProperty(d)));
console.log("map has " + currentBuilding + " -> d: " + d);
findNeighbors(d);
case (lRow === currRow && idm.hasOwnProperty(l) === true):
console.log((lRow === currRow && idm.hasOwnProperty(l)));
console.log("map has " + currentBuilding + " -> l: " + l);
findNeighbors(l);
case (rRow === currRow && idm.hasOwnProperty(r) === true):
console.log((rRow === currRow && idm.hasOwnProperty(r)))
console.log("map has " + currentBuilding + " -> r: " + u);
findNeighbors(r);
}
console.log("---------------------------");
}
I figured a switch statement would be cool to use to replace my if statements so all my checks could be visually and logically grouped.
Well, write code that works not code that looks cool. You were forgetting break statements, so the execution flow fell through - without evaluating the other case expressions after the first one matched. Btw switching on a constant is a horrible (uncool) practice.
Use standard if/else instead.

How to return data from a function

I'm trying to solve the following Kata:
a 2 digit number, if you add the digits together, multiply by 3, add 45 and reverse.
I'm unable to figure out how to return the data from my function so that I can later assign the value to an HTML element.
This is my code.
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
}
} else {
console.log("Not a 2 digit Number!!");
}
}
teaser(j);
}
}
From your question I'm guessing you need reversal value on function daily for loop.
Would recommend you to take out function teaser from inside for-loop, this will make code much cleaner and easy to understand and you can do like:
function daily() {
for(var j = 10; j < 100; j++) {
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
If don't want to take function out then you can do this:
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
Returning something from a function is very simple!
Just add the return statement to your function.
function sayHello(name) {
return 'Hello ' + name + '!';
}
console.log(sayHello('David'));
okay, so my issue has been solved! Thanks all of you, especially krillgar, so I had to alter the code you gave me krillgar, a little bit in order to populate the results array with only the numbers (one number in this case) that satisfy the parameters of the daily tease I was asking about. yours was populating with 89 undefined and on number, 27 because it is the only number that works.
One of my problems was that I was expecting the return statement to not only save a value, but also show it on the screen, but what I was not realizing was that I needed a place to store the value. In your code you created a result array to populate with the correct numbers. And also, I needed a variable to store the data for each iteration of the for loop cycling through 10 - 100. Anyways, you gave me what I needed to figure this out and make it do what I wanted it to do, and all is well in the world again.
Anyway, thank you all for your help and input, and I will always remember to make sure I have somewhere to store the answers, and also somewheres to store the value of each loop iteration in order to decide which numbers to push into the results array and save it so it can be displayed and/or manipulated for whatever purpose it may be. I guess I was just so busy thinking about the fact that when I returned num it didn't show the value, instead of thinking about the fact that I needed to store the value. Here is the final code for this problem and thanks again peoples!
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return num;
// Here you have one that is correct, so return it:
} else {
console.log(num + " does not fulfill function parameters");
// This is just so you can visualize the numbers
return null;
}
}
}
var answer = teaser(j);
if(answer != null) {
results.push(answer);
}
}
return results;
}
As was said in the comments of the question, because you're going to (most likely) have multiple answers that match your condition, you will need to store those in an array. Your teaser function returns individual results, where daily will check all the numbers in your range.
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
// Here you have one that is correct, so return it:
return num;
} else {
// Make sure we don't return undefined for when the sum
// times three doesn't equal the number.
return null;
}
} else {
console.log("Not a 2 digit Number!!");
return null;
}
}
var answer = teaser(j);
if (answer !== null) {
results.push(answer);
}
}
return results;
}

Couple of questions about code that hides text strings from output

Hello I started learning JavaScript and esterday I asked to help me hide NaN strings of array from output. Some guys helped me.. But I got new questions.
Here the link to answers
For this code,
if (typeof(degFahren[loopCounter]) === 'string') continue;
What's happening in there? As I can see If degFahren equal to text string, script will go ahead, but it works another way around and handle numbers for output.
For this code
if (parseInt(degFahren[loopCounter]) != "NaN")
It doesnt hide NaN strings at all. Shows all strings from array. Why?
Here block of code that does't work
for (loopCounter = 0; loopCounter <=6; loopCounter++){
if (parseInt(degFahren[loopCounter]) != "NaN")
degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
document.write ("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit");
document.write (" which is " + degCent[loopCounter] + " degrees centigrade<br />");
}
Your assumptions are right, but the code fails because you missed the braces. You should add braces after if condition
for (loopCounter = 0; loopCounter <=6; loopCounter++){
if (parseInt(degFahren[loopCounter]) != "NaN") {
degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
document.write ("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit");
document.write (" which is " + degCent[loopCounter] + " degrees centigrade<br />");
}
}
As I can see If degFahren equal to text string, script will go ahead
degFahren is apparently expected to be an array. It doesn't test whether degFahren is a string, it tests whether the current element being iterated over (which is inside the array) is a string.
It doesnt hide NaN strings at all. Shows all strings from array. Why?
NaN is not a string; it is a primitive value. But NaN !== NaN; you should use the isNaN() function instead.
You should also avoid implicitly creating global variables. It will be easier to read if you abstract the temperatures instead of messing with indicies:
for (loopCounter = 0; loopCounter <=6; loopCounter++){
const tempF = degFahren[loopCounter];
if (isNaN(tempF)) continue;
const tempCentigrade = convertToCentigrade(tempF);
document.write ("Value " + loopCounter + " was " + tempF + " degrees Fahrenheit");
document.write (" which is " + tempCentigrade + " degrees centigrade<br />");
}

adding and subtracting to the array range

Hey I have a question about this piece of code that I have:
var levelsRange = arrayeventslevel[0] + " through " + arrayeventslevel[arrayeventslevel.length-1]; ;
$("#existorders").html(
"There are currently: " + arrayeventslength.length +
" events on " + dayoftheweek +
"<br/>" + " with order levels: " + levelsRange +
"<br />" + "You can move new event to levels ranging between: " + newLevelsRange
);
currently levelsRange outputs for example 1 through 6 range. If that is the case,
I need another variable newLevelsRange that should say 0 through 7 based on initial variable range.
However, if levelsRangesays 0 through 6, new variable should say 0 through 7 NOT -1 through 7
I am having trouble adding subtracting properly from initial variable information. Can someone please assist.
var newLevelsRange=(arrayeventslevel[0]||1)-1 + " through " + (arrayeventslevel[arrayeventslevel.length-1]-1);
Simply check if the first element is zero, if so, take 1...
I just did this
if(arrayeventslevel[0] != 0){
arrayeventslevel[0] = arrayeventslevel[0] - 1;
arrayeventslevel.length =arrayeventslevel.length + 1;
}
var newLevelRange = arrayeventslevel[0] + " through " + arrayeventslevel.length;
not sure how to use Math.max

Categories