scratchpad - Keep getting "undefined" in the output on console. - javascript

function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
console.log(largerNum (5,12));
the output shows - The larger number of 6 and 12 is 12
undefined

This is because the function is not explicitly returning anything, it return undefined by default
function largerNum(a, b) {
if (a > b) {
console.log("The larger number of " + a, "and " + b, "is " + a, ".");
} else {
console.log("The larger number of " + a, "and " + b, "is " + b, ".");
}
// this function is not returning anything
}
console.log(largerNum(5, 12));

You are not returning any value from your largerNum function so the default return value of undefined is being returned. You could refactor your code like this.
note: the string is concatenated with + rather than using , to separate arguments to console.log
function largerNum(a, b) {
if (a > b) {
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else {
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(
largerNum(5, 12)
)
console.log(
largerNum(13, 42)
)

Because you don't need to console.log when invoking the function: your function returns nothing, and you see additional undefined. Just remove console.log() wrapper from console.log(largerNum (5,12)):
function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
largerNum(5,12);
Or return the value from function and log the function invocation:
function largerNum (a,b){
if (a>b){
return "The larger number of " +a+ " and " +b+ " is " +a+ ".";
}
else{
return "The larger number of " +a+ " and " +b+ " is " +b+ ".";
}
}
console.log(largerNum(5,12));

Your larger() function doesn't return any values so you are passing null to the last console.log() statement.
function largerNum (a,b){
if (a>b){
return a;
} else {
return b;
}
}
console.log(
"The larger number of " + a + ", and " + b + ", is " +
largerNum(a,b) + "."
);
Should work

because there is no return in your function and so console.log(largerNum (5,12)) gives undefined
make your function to return something
chnage to
function largerNum (a,b){
if (a>b){
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else{
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(largerNum (5,12));

Related

JavaScript conditional statements if/else if/else

Hello guys! Could you please help me out? I am trying to use certain conditions but they seem to be ignored for some reasons. When I ran the code the popped-up random number given was 93 that fitted in the first declared statement (if), but, It got ignored and moved to the last statement even when true && true.
I do not understand why...
???
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
if (matchingPercentage() >= 70 && matchingPercentage() <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You guys are meant to be together!");
}
else if( matchingPercentage() >=30 && matchingPercentage() <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You better look in another direction!");
}
}
function matchingPercentage() {
var n = Math.random();
var n = Math.floor(n * 100) + 1;
return n;
}
loveMatching();
you're calculating a new match % everytime you check it, multiple times in the same conditional. you need to just do it once at the start:
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
const matchPercent = matchingPercentage(); // call one time
if (matchPercent >= 70 && matchPercent <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You guys are meant to be together!");
}
else if( matchPercent >=30 && matchPercent <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You better look in another direction!");
}
}

Better way to do this If statement?

Pretty simple: I wrothe the following if/else statement:
if (cr1.ins <= cr2.ins) {
console.log("[ROUND 1] Creature 1 (#" + cr1.num + ") is attacking first.");
cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
if (cr2.hlt <= 0) {
console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
remove(cr2);
} else {
console.log("[ROUND 2] Creature 2 (#" + cr2.num + ") is attacking second.");
cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
if (cr1.hlt <= 0) {
console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
remove(cr1);
}
}
} else {
cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
console.log("[ROUND 1] Creature 2 (#" + cr2.num + ") is going first.");
console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
if (cr1.hlt <= 0) {
console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
remove(cr1);
} else {
console.log("[ROUND 2] Creature 1 (#" + cr1.num + ") is going second.");
cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
if (cr2.hlt <= 0) {
console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
remove(cr2);
}
}
}
I know there's probably a better way to do this, as the code in else{ } is basically the same as if{ } with some variable name changes, so, any suggestions for changes or refactoring? I'd like to improve readability and speed while accomplishing the same task as it performs currently.
Indeed you can simplify this, the general approach would be
if (cr1.ins > cr2.ins) {
[cr2, cr1] = [cr1, cr2]; // just swap them!
}
attack(cr1, cr2);
if (cr2.hlt > 0) {
attack(cr2, cr1);
}
For your logging statements with Creature 1/2 you would also need to pass through that information, so it might become something like
const a = {designator: "Creature 1", creature: cr1},
b = {designator: "Creature 2", creature: cr2};
const [first, second] = cr1.ins <= cr2.ins ? [a, b] : [b, a];
attack({attacker: first, defender: second, round: 1});
if (second.creature.hlt > 0)
attack({attacker: second, defender: first, round: 2});
Of course, if you refactor this to use an attack function as above, it might become shorter to write out the if/else again.

I have a function then a if else statement then a return with a maths in it

// var
var differentBillsInUSD;
// start of bills
differentBillsInUSD = {
firstBill: parseInt(124),
secondBill: parseInt(48),
thirdBill: parseInt(268),
fourthBill: parseInt(180),
fifthBill: parseInt(42),
}
// console to check if everything is alright
console.log(differentBillsInUSD);
console.log("Checking if bill is alright ^");
function calcBill(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip is: " (numberBill*0.20));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " (numberBill*0.15));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " (numberBill*0.20));
}
}
function calcBillTotal(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " ((numberBill*0.15)+numberBill));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
}
}
// first bill
console.log(calcBill(differentBillsInUSD.firstBill));
console.log(calcBillTotal(differentBillsInUSD.firstBill));
// second bill
cosnole.log(calcBill(differentBillsInUSD.secondBill));
cosnole.log(calcBillTotal(differentBillsInUSD.secondBill));
ERROR CODE
script.js:21 Uncaught TypeError: " tip + total is: " is not a function
at calcBill (script.js:21)
at script.js:37
It won't work because I am doing to a coding challenge.
It also seems that I am new to javascript.
I tried to do my research, it was very difucult to find.
I am in the middle of code but can not fix.
return(numberBill + " tip is: " + (numberBill*0.20));
you just miss to place a plus sign inside...
return(numberBill + " tip + total is: " (numberBill*0.15));
In JS when you place () after anything it tries to execute it as a function. as you missed the "+" just before "(numberBill*0.15)", so its trying to execute " tip + total is: " as a function. You just need to add a "+"
when you are concatenating a string with a variable , you need to use "+" sign in javascript. Here if you noticed in each if ,else if and else statement you are missing "+" sign.
if (numberBill < 50) {
return(numberBill + " tip is: " + (numberBill*0.20));

how to convert numbers to million in javascript

As in image. for some values converting correctly but some of values not converting... you can see in image
I want to convert numbers to million.I am using Money format function to convert numbers but i am unable to convert numbers.
This is controller part.for some numbers it is converting to millions and for some numbers it is not converting.. Please someone help.
$scope.MoneyFormat = function (labelValue)
{
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9
? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6
? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3
? Math.abs(Number(labelValue)) / 1.0e+3 + "K"
: Math.abs(Number(labelValue));
}
Here I am converting numbers by using Moneyformat. This is controller part where I am converting numbers
$scope.rep.won = $scope.MoneyFormat($scope.rep.won);
$scope.outlook.rem = $scope.MoneyFormat($scope.outlook.rem);
$scope.rep.expectedAmount = $scope.MoneyFormat($scope.rep.expectedAmount);
$scope.rep.potential = $scope.MoneyFormat($scope.rep.potential);
$scope.rep.quota = $scope.MoneyFormat($scope.rep.quota);
I have no idea what $scope.MoneyFormat is.
So I simplified your function to a plain old js function and it works.
function convertToInternationalCurrencySystem (labelValue) {
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9
? (Math.abs(Number(labelValue)) / 1.0e+9).toFixed(2) + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6
? (Math.abs(Number(labelValue)) / 1.0e+6).toFixed(2) + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3
? (Math.abs(Number(labelValue)) / 1.0e+3).toFixed(2) + "K"
: Math.abs(Number(labelValue));
}
alert( convertToInternationalCurrencySystem (6800000) ); // this outputs 6.8M
JSFiddle: https://jsfiddle.net/r5ju34ey/
getNumber = function(num) {
var units = ["M","B","T","Q"]
var unit = Math.floor((num / 1.0e+1).toFixed(0).toString().length)
var r = unit%3
var x = Math.abs(Number(num))/Number('1.0e+'+(unit-r)).toFixed(2)
return x.toFixed(2)+ ' ' + units[Math.floor(unit / 3) - 2]
}
console.log(getNumber(680000))
console.log(getNumber(6800009))
console.log(getNumber(68000009))
console.log(getNumber(680000000))
console.log(getNumber(6800000000))
console.log(getNumber(68000000000))
console.log(getNumber(680000000000))
console.log(getNumber(6800000000000))
console.log(getNumber(68000000000000))
console.log(getNumber(680000000000000))
console.log(getNumber(6800000000000000))
console.log(getNumber(68000000000000000))
console.log(getNumber(680000000000000000))
I know I'm almost 16 years late at the party, but I can't help myself to comment what I know about it after seeing so much long functions for this task. even the accepted and most upvoted answer uses a quite long function
However, you can use javascript's built-in method Intl (namespace for Internationalization API) here. Intl object has a function named NumberFormat where you can define your preferred language, notation type, and many more. in your use case, the code will look something like
const number = 234234;
const language = "en"
Intl.NumberFormat(language, {notation: "compact"}).format(number) //output - "234K"
check out MDN's doc about Intl and Intl.NumberFormat()
getNumberUnit = function(num, round = 1) {
const unit = Math.floor(Math.round(num / 1.0e+1).toLocaleString().replaceAll(',', '').length),
wunit = ["Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion","Septillion","Octillion","Nonillion","Decillion","Undecillion","Duodecillion","Tredecillion","Quattuordecillion","Quindecillion","Sexdecillion","Septemdecillion","Octodecillion","Novemdecillion","Vigintillion","Unvigintillion","Duovigintillion","Trevigintillion","Quattuorvigintillion","Quinvigintillion","Sexvigintillion","Septvigintillion","Octovigintillion","Nonvigintillion","Trigintillion","Untrigintillion","Duotrigintillion"][Math.floor(unit / 3) - 1],
funit = Math.abs(Number(num))/Number('1.0e+'+(unit-unit%3));
return wunit ? funit.toFixed(round).toLocaleString() + ' ' + wunit : num.toFixed(round).toString();
}
var result=getNumberUnit(764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
console.log(result)
The best of all
Improving upon the answer to include negatives:
function test(labelValue) {
const sign = Math.sign(Number(labelValue));
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e9
? sign * (Math.abs(Number(labelValue)) / 1.0e9) + "B"
: // Six Zeroes for Millions
Math.abs(Number(labelValue)) >= 1.0e6
? sign * (Math.abs(Number(labelValue)) / 1.0e6) + "M"
: // Three Zeroes for Thousands
Math.abs(Number(labelValue)) >= 1.0e3
? sign * (Math.abs(Number(labelValue)) / 1.0e3) + "K"
: Math.abs(Number(labelValue));
}
alert(test(-99998000000));
Because of how far javascript number goes they can only go up to 1e301
This function shows the number in a 3 digit along with a letter, for example 30000000000000000 would be 30,0 Quadrillion and 1000000 would be 1,00 Million.
function simpleNumber(costOfIt, visualOfIt) {
var visualOfIt = costOfIt.toString();
var visualLeng = 6;
var maxLeng = 4;
var letterArrayIndex = 0;
var letterArray = [" Thousand", " Million", " Billion", " Trillion", " Quadrillion", " Quintillion", " Sextillion", " Septillion", " Octillion", " Nonillion", " Decillion", " Undecillion", " Duodecillion", " Tredecillion", " Quatuordecillion", " Quindecillion", " Sexdecillion", " Septendecillion", " Octodecillion", " Novemdecillion", " Vigintillion", " Unvigintillion", " Duovigintillion", " Tresvigintillion", " Quatuorvigintillion", " Quinquavigintillion", " Sesvigintillion", " Septemvigintillion", " Octovigintillion", " Novemvigintillion", " Trigintillion", " Untrigintillion", " Duotrigintillion", " Trestrigintillion", " Quatuortrigintillion", " Quinquatrigintillion", " Sestrigintillion", " Septentrigintillion", " Octotrigintillion", " Novemtrigintillion", " Quadragintillion", " Unquadragintillion", " Duoquadragintillion", " Tresquadragintillion", " Quatuorquadragintillion", " Quinquaquadragintillion", " Sesquadragintillion", " Septemquadragintillion", " Octoquadragintillion", " Novemquadragintillion", " Quinquagintillion", " Unquinquagintillion", " Duoquinquagintillion", " Tresquinquagintillion", " Quatuorquinquagintillion", " Quinquaquinquagintillion", " Sesquinquagintillion", " Septenquinquagintillion", " Octoquinquagintillion", " Novemquinquagintillion", " Sexagintillion", " Unsexagintillion", " Duosexagintillion", " Tressexagintillion", " Quatuorsexagintillion", " Quinquasexagintillion", " Sexasexagintillion", " Septemsexagintillion", " Octosexagintillion", " Novemsexagintillion", " Septuagintillion", " Unseptuagintillion", " Duoseptuagintillion", " Tresseptuagintillion", " Quatuorseptuagintillion", " Quinquaseptuagintillion", " Sexaseptuagintillion", " Septenseptuagintillion", " Octoseptuagintillion", " Novemseptuagintillion", " Octogintillion", " Unoctogintillion", " Duooctogintillion", " Tresoctogintillion", " Quatuoroctogintillion", " Quinquaoctogintillion", " Sesoctogintillion", " Septemoctogintillion", " Octooctogintillion", " Novemoctogintillion", " Nonagintillion", " Unnonagintillion", " Duononagintillion", " Tresnonagintillion", " Quatuornonagintillion", " Quinquanonagintillion", " Sesnonagintillion", " Septemnonagintillion", " Octononagintillion", " Novemnonagintillion", " Centillion", " Uncentillion"];
var leng = 4;
var slic = 1;
for (var g = 0; g < visualOfIt.length; g++) {
if (visualOfIt.length <= visualLeng) {
if (leng < maxLeng) {
leng = maxLeng;
}
if (visualOfIt.length === leng) {
if (slic > 2) {
visualOfIt = costOfIt.toString().slice(0, slic) + letterArray[letterArrayIndex];
break;
} else {
visualOfIt = costOfIt.toString().slice(0, slic) + "," + costOfIt.toString().slice(slic, 3) + letterArray[letterArrayIndex];
break;
}
} else {
leng++;
slic++;
}
} else {
maxLeng += 3;
visualLeng += 3;
letterArrayIndex++;
}
}
return visualOfIt;
}
Just use console.log(simpleNumber(1435345, 0)) outside of the function then it would return 1,43 Million

Implement function array

I have a code for a loto which allows us to find and compare number in a array using loops.I need to update my program so that the work of checking the result is done
by a function called checkNumber. This function should take the customer
number and the array of winning numbers as arguments. The customer number
should be returned from a function called getCustomerNumber. The array of
winning numbers should be returned from a function called
getWinningNumbers. The display of the results should be done by a function
called displayResult(). The whole process should be kicked off by a function
called init. Thank you for your help!
x = checkNumber(12, 17, 24, 37, 38, 43);
function checkNumber() {
for (var i = 0; i < winningNumbers.length && !match ; i++)
if (winningNumbers[i] == customerNumbers) {
match = true;
}
}
}
function getWinningNumbers
function displayResult(){
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!";
alert(message)
} Else
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week";
alert(message)
}
}

Categories