Why I get "undefined" in JavaScript - javascript

Could you please help, why do I get this undefined value instead of returning a?
var a = 0;
var m = 888;
function sevens(m, a) {
if (m == 0) {
document.write("Amount of 8's is "+a+"<br>");
return a;
} else {
if(Math.floor(m % 10) == 8) {
a++;
sevens(Math.floor(m / 10), a);
} else {
sevens(Math.floor(m / 10), a);
}
}
}
document.write("in "+m + " " + "it is" + " " + sevens(m, a));
Thank you in advance.

Function needs to return something in the else statement. Like this:
function sevens(m, a){
if(m == 0){
document.write("Amount of 8's is "+a+"<br>");
return a;
}else{
if(Math.floor(m % 10) == 8){
a++;
return sevens(Math.floor(m / 10), a);
}else{
return sevens(Math.floor(m / 10), a);
}
}
}

You are not returning the function call while doing a recursion,
if(Math.floor(m % 10) == 8){
a++;
return sevens(Math.floor(m / 10), a);
}else{
return sevens(Math.floor(m / 10), a);
}
If you do not return anything inside a function, by default it will return undefined. Not in all the cases. That depends on the way you call the particular function.

Maybe you change the logic a bit, because you don't need an else part if in the then part the function is finished with return.
The other change is suspending Math.floor in combination with the remainder operator %. It returns always an integer value.
The third part is to move the call of sevens outside of the if statement, because it is anyway called.
var a = 0,
m = 888;
function sevens(m, a) {
if (m == 0) {
document.write("Amount of 8's is " + a + "<br>");
return a; // exit function, rest
} // of function is else part
if (m % 10 == 8) { // % --> int
a++;
}
return sevens(Math.floor(m / 10), a); // return result of call
}
document.write("in " + m + " " + "it is" + " " + sevens(m, a));

You forget the return, otherwise, I refactored a little bit the sevens function and you can run in code snippet.
var a = 0;
var m = 888;
function sevens(m, a) {
if (m === 0) {
document.write("Amount of 8's is " + a + "<br>");
return a;
}
if (Math.floor(m % 10) === 8) {
a += 1;
}
return sevens(Math.floor(m / 10), a);
}
document.write("in " + m + " " + "it is" + " " + sevens(m, a));

Related

How to get String output as in single quote in javascript

Advance thanks, Question looks like simple but i could not able to find the solution.
function sumStrings(a, b)
{
return +a + +b;
}
sumStrings('1','2') //=>3
Expected output
sumStrings('1','2') // => '3'
After addition, add ' to beginning and end.
function sumStrings(a, b){
return "'" + (Number(a) + Number(b)) + "'";
}
console.log(sumStrings('1','2'));
function sumStrings(a, b) {
// Separate decimal part here
var pointa = a.indexOf(".");
var pointb = b.indexOf(".");
var deca = pointa != -1 ? a.substring(pointa + 1) : "0";
var decb = pointb != -1 ? b.substring(pointb + 1) : "0";
if (deca.length < decb.length)
deca += (Math.pow(10, decb.length - deca.length)).toString().substring(1);
else
decb += (Math.pow(10, deca.length - decb.length)).toString().substring(1);
var inta = pointa != -1 ? a.substring(0, pointa) : a;
var intb = pointb != -1 ? b.substring(0, pointb) : b;
// console.log(deca + " " + decb);
var decc = addBigInt(deca, decb);
var intc = addBigInt(inta, intb);
if (decc.length > deca.length) {
intc = addBigInt(intc, "1");
decc = decc.substring(1);
}
var lastZero = decc.length - 1;
while (lastZero >= 0 && decc[lastZero] == "0") {
lastZero--;
}
if (lastZero >= 0)
return intc + "." + decc.substring(0, lastZero + 1);
else
return intc;
}
function addBigInt(a, b) {
var inda = a.length - 1;
var indb = b.length - 1;
var c = [];
const zero = "0".charCodeAt(0);
var carry = 0;
var sum = 0;
while (inda >= 0 && indb >= 0) {
var d1 = a.charCodeAt(inda--) - zero;
var d2 = b.charCodeAt(indb--) - zero;
sum = (d1 + d2 + carry);
carry = Math.floor(sum / 10);
sum %= 10;
c.unshift(sum);
}
if (inda >= 0) {
while (carry && inda >= 0) {
sum = a.charCodeAt(inda--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(a.substring(0, inda + !carry));
} else {
while (carry && indb >= 0) {
sum = b.charCodeAt(indb--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(b.substring(0, indb + !carry));
}
if (carry)
c.unshift(carry);
return c.join("");
}
console.log(sumStrings("1","2"));
console.log(sumStrings("800","9567"));
console.log(sumStrings("99.1","1"));
console.log(sumStrings("00103","08567"));
console.log(sumStrings("50095301248058391139327916261.5","81055900096023504197206408605"));
If you want to escape the single quote, you can try to add a backslash before the single quote.
i.e.
var x = '\'5\'';
With the new template literal you can try this:
a=`'5'`;
console.log(a);

Function call using a for loop to cycle through array not working, Help please

I'm very new to Javascript but I have a problem which I have spent all day trying to research and solve, like to do it myself but i'm very stuck.
My code is simple, I have created 5 functions, 1 tests for letters, one tests for numbers, 1 for an open bracket and 1 for a closed bracket, and the fifth spots a full stop. These functions return true.
I then created a function to call all of these functions when required to produce a numerical output depending on what is found in a text string.
Back to the top, I have a string, I created an array using split to place each of the characters in the string into the separate addresses in the array. The idea is that I use a for loop to scroll through the array and output the type into identity, which is then outputted in a list.
The issue is it will do the loop once then crash, and i can't find the problem, the issue lies in the line:
identity = isWhat(ModCompound[x],ModCompound[y]);
removing it with // and the for loop runs fine.
I would like to know why? what is the mistake?
code: (raw FORM)
<!DOCTYPE html>
<!--
Sjb 19/03/2015
-->
<html>
<head>
<title></title>
</head>
<body>
Chemicals
</br>
Compound: <input id="compound" value="NaCl.2(H20)">
<script>
var identity;
var x;
Compound = document.getElementById('compound').value;
ModCompound = Compound;
ModCompound = ModCompound.split('');
for (i = 0; i < Compound.length; i++){
x = i;
y = i;
document.write(i);
identity = isWhat(ModCompound[x],ModCompound[y]);
document.write(Math.random() + " : " + identity + "</p>");
}
ModCompound= ModCompound.join('');
// Custom Functions
function isWhat(n1,c1) //OUTPUT 1,2,9,0,8
{
if (isLetter(n1,c1) === true) {
return isWhat = 1;
//document.write = "L";
} //OUTPUT 1
if (isNumber(n1,c1) === true) {
return isWhat = 2;
//document.write = "N";
} //OUTPUT 2
if (isOpenBracket(n1,c1) === true){
return isWhat = 9;
//document.write("OB");
} //OUTPUT 9
if (isClosedBracket(n1,c1) === true) {
return isWhat = 0;
//document.write = "CB";
} //OUTPUT 0
if (isFullStop(n1,c1) === true) {
return isWhat = 8;
//document.write = "FS";
} //OUTPUT 8
}
function isNumber(n, c) //OUTPUT(s) TRUE
{
if (n >= 0 || n <= 9 ) {
//document.write(n + " N " + c + "</p>");
return isNumber = true;
}
}
function isLetter(n, c)
{
n = n.charCodeAt(0);
if (((n >= 65) && (n <= 90)) || ((n >= 97) && (n <= 122))) {
//document.write(n + " L " + c + "</p>");
return isLetter = true;
}
}
function isOpenBracket(n,c)
{
if (n === "(") {
//document.write(n + " OB " + c + "</p>");
return isOpenBracket = true;
}
}
function isClosedBracket(n,c)
{
if (n === ")") {
//document.write(n + " CB " + c + "</p>");
return isClosedBracket = true;
}
}
function isFullStop(n,c)
{
if (n === ".") {
//document.write(n + " F " + c + "</p>");
return isFullStop = true;
}
}
</script>
</body>
</html>
Your return statements should just be like this:
return 1;
You're writing this:
return isWhat = 1;
That's setting the variable isWhat to 1, then returning it. isWhat is a function, though, so setting it to 1 makes is so you can't call it (because now it's a number, not a function). Also, there's no need to type var===true, because if the variable is true, then var will evaluate to true and the if statement will run.

Generating and checking random numbers in JavaScript

I have some problems with JavaScript.
So far, I have this code:
<!DOCTYPE html>
<html>
<body>
<p>This program generates random numbers from 100 to 999.</p>
<button onclick="maingen()">Start</button> <-- Here's the FUNCTION OF FUNCTIONS..It should generate 3 digits, but only generates 1 :(
<p id="numbers"></p>
<script>
function generate1() {
var a = Math.floor((Math.random() * 9) + 1);
document.getElementById("numbers").innerHTML = a; <--generating the first digit (from 1 to 9)
}
function generate2() {
var b = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = b; <--generating the second digit (from 0 to 9)
}
function generate3() {
var c = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = c; <--generating the third digit (from 0 to 9)
}
function maingen(){
generate1();
generate2();
generate3();
}
</script>
</body>
</html>
And it doesn't work like I intended to. It should generate a random number from 100 to 999.
(I am generating separate digits because later I will need to check if there are same digits in that number (for example 222)).
So what did I do wrong? Any kind of help would be nice. Thank you.
You could do it using the += in each function or you could simplify it a little more.
function generate1() {
return Math.floor((Math.random() * 9) + 1);
}
function generate2() {
return Math.floor((Math.random() * 9) + 0);
}
function generate3() {
return Math.floor((Math.random() * 9) + 0);
}
function maingen() {
var a = generate1();
var b = generate2();
var c = generate3();
document.getElementById("numbers").innerHTML = a + '' + b + '' + c;
}
You can also do it like this
function generate_rand() {
return Math.floor((Math.random() * 9));
}
function maingen() {
var a = generate_rand() + 1;
var b = generate_rand();
var c = generate_rand();
document.getElementById("numbers").innerHTML = a + '' + b + '' + c;
}
Not sure if this is your solution, but looks like the functions are misspelled. I see:
function generuoti1() {
var a = Math.floor((Math.random() * 9) + 1);
document.getElementById("numbers").innerHTML = a; <--generating the first digit (from 1 to 9)
}
function generuoti2() {
var b = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = b; <--generating the second digit (from 0 to 9)
}
But then your main function is calling different functions:
function maingen(){
generate1();
generate2();
generate3();
}
I see that one of those functions is spelled right, so that may be why you're only seeing 1 digit. Try fixing your function names for generate1() and generate2().
And then as mentioned in the comments, append your innerHTML with += instead of =

javascript - How to reverse bitwise shift?

This is my Function. In this function there is two parameter value and how many bits shift.
function test(Value, ShiftBits) {
return (Value << ShiftBits) | (Value >>> (32 - ShiftBits));
};
Now i want to make reverse of this function. In this test() function if i put
test(105748,7);
it returns 13535744;
Now i need to make a function like, if i put
rev_test(13535744,7);
it returns 105748;
Any help Appreciated.
Why not reverse the logic? I spelled it out below:
Number.prototype.zeroFillBin = function() {
var s = this.toString(2);
while (s.length < 32) s = '0' + s;
return s;
}
function test(val, bits) {
return (val << bits) | (val >>> (32 - bits));
};
function rev_test(val, bits) {
return (val >>> bits) | (val << (32 - bits));
};
x = 105748;
y = test(x, 7); // return 13535744
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
x = 13535744;
y = rev_test(x, 7); // return 105748
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
Results:
105748 = 00000000000000011001110100010100
13535744 = 00000000110011101000101000000000
13535744 = 00000000110011101000101000000000
105748 = 00000000000000011001110100010100
105748 << 1 // 13535744
13535744 >> 1 // 105748

How would I create a function that takes three numbers as arguments and returns the largest of them?

I've been looking at simple JS exercises and I would appreciate it if you showed me how to approach this question or, even better, provide a solution that I can take a look at. Help much appreciated.
EDIT: I would also appreciate any simple working example of the function in use.
function whatDidYouTry() {
return Math.max.apply(null, arguments);
}
There's no need to create a new function as one already exists:
Math.max(num1, num2, num3);
Creating a new function is just extra overhead with no value added.
function get_max(num1, num2, num3)
{
var max = Math.max(num1, num2, num3);
return max;
}
alert(get_max(20,3,5)); // 20
DEMO.
​
Taking a crack at it.
function threeNumberSort(a,b,c) {
if (a<b) {
if (a<c) {
if (b<c) {
console.log(a + ", then " + b + ", then " + c);
} else {
console.log (a + ", then " + c + ", then " + b);
}
} else {
console.log (c + ", then " + a + ", then " + b);
}
} else {
if (b<c) {
if (a<c) {
console.log (b + ", then " + a + ", then " + c);
} else {
console.log (b + ", then " + c + ", then " + a);
}
} else {
console.log (c + ", then " + b + ", then " + a);
}
}
}
threeNumberSort(1456,215,12488855);
This will print on your console:
215, then 1456, then 12488855
I have used the algorithm I found on this page. More efficient ones probably exist out there.
This is the manual code I came up with using functions and else if statements:
function maxOfThree(a, b, c) {
if ((a >= b) && (a >= c)) {
return a;
} else if ((b >= a) && (b >= c)) {
return b;
} else {
return c;
}
}
console.log(maxOfThree(343,35124,42));

Categories

Resources