JavaScript Loop stuck beginner - javascript

I am trying some loops and in this specific I do not understand why is sumSoFar = 0.
This is a task from Learn Street.com
function sum(n) {
var sumSoFar = 0;
var currentNumber = 1;
while (currentNumber <= n) {
sumSoFar += currentNumber;
currentNumber += 1;
}
return sumSoFar;
}

sumSoFar is initialized to zero at the start of the function because the rest of the function uses the += operator which takes the current value of sumSoFar and adds a value to that and then assigns the new value back to sumSoFar. If it wasn't initialized to zero, then it would not have an initial value and the first += operation on it would not have the desired result.
Initializing it to zero gives it the desired starting point so that the first time through the while loop, it adds currentNumber to that initial value of zero and assigns that to sumSoFar which is the desired behavior.
FYI, you can see your function work here: http://jsfiddle.net/jfriend00/kXrV8/ and in the latest version, you can try different input arguments to your sum(n) function.

If you don't initialize sumSoFar to zero you can't add values to it because it wouldn't be a number.

Related

Why counter increases and fn is called? How it works?

I solved kata on codewars. Acctually I did this by accident and I don't understand why this code works. May you explain it?
Kata:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
39 --> 3 (because 39 = 27, 27 = 14, 1*4 = 4 and 4 has only one digit)
My solution:
function persistence(num) {
let count = 0;
const arr = [...num.toString()];
const sumArr = arr.reduce((res, val) => (res *= val));
if (arr.length > 1) {
**// Why? How this line works?
// Why it doesn't crashes?
// Why it returns correct counter value and calls the function?**
count += 1 + persistence(sumArr)
}
return count;
}
persistence(39); //3
Why if I do like this, the counter do not save the result:
if (arr.length > 1) {
count += 1
persistence(sumArr) }
Basically, the persistence(sumArr) function acts as a recursive function and returns count of 0 for a base condition that is when the number is single digit. For 39, count is 1+persistence(27)
For 27, count is 1+persistence(14) and for 14, 1+ persistence (4) which is nothing but 1+0 and recursively it adds up to be 3
count is a local variable, only reachable within the scope of persistence(), so when you do a recursive loop, you create a new variable called count but it's in a new scope - the method that you called - it just happens to have the same name as persistence().
It would be totally different if count were a global variable, outside of the scope of the method.
let count = 0;
function persistence(num) {
...
}
Calling persistence() again within persistence() would then use the same variable, not a new one.
This is recursion!
Whenever a function is called by the caller, that function (a.k.a callee) is pushed into the call stack. All the arguments, local variables needed for that function is present there. This is also known as stack frame. The callee is popped out of the stack when it returns to the caller.
In your case both the caller and the callee happened to be the same function. This is called recursion. During recursion, variables local to that function aren't shared. A new stack frame is set up for each callee.
if (arr.length > 1) {
count += 1
persistence(sumArr)
}
Here, the count that you are returning from the callee isn't getting added up with the count of the caller.
If we visualize what is happening then:
persistence(37) = 1 + persistence(27) = 1 + 1 + 1 + 0 // [putting value returned from persistence(27)]
persistence(27) = 1 + persistence(14) = 1 + 1 + 0 // [putting value returned from persistence(14)]
persistence(14) = 1 + persistence(4) = 1 + 0 // [putting value returned from persistence(4)]
persistence(4) = 0

What do I need a return statement for in JavaScript?

I'm trying to wrap my head around the return statement but I can't see a reason why I should use one. My code works just fine without using one...
In both examples my console prints out 10 not matter if I use return or not.
Without return:
var sum = 5;
function myFunction() {
sum += 5;
}
myFunction();
console.log(sum);
With return:
var sum = 5;
function myFunction() {
return sum += 5;
}
myFunction();
console.log(sum);
By default, functions return the value undefined. If you want the function to return some other value, you need to have a return statement.
You may also use a return statement to halt execution of the function based on some logic, again returning a value that has some meaning or just undefined.
In the first example in the OP, the function is called and the return value is not used for anything, so it doesn't matter what the return value is and a return statement isn't necessary.
In another scenario, the return value might be important, e.g. a function that generates an integer random number between 0 and 10:
function getRandomInteger(){
return Math.floor(Math.random() * 11);
}
function showRandomNumber() {
document.getElementById('s0').textContent = getRandomInteger();
}
<button onclick="showRandomNumber()">Show random number</button>
<span id="s0"></span>
In the above, the getRandomInteger function needs to return a specific value, so it uses a return statement. The showRandomNumber function just displays the random number, so it doesn't need a return statement as the caller (the listener on the button) doesn't care what the return value is.
Here is what is happening with your example:
var sum = 5; //Sets the sum to =5
function myFunction() {
return sum += 5; // += reassigns the global (sum) to 10
}
myFunction();
console.log(sum);
A better example would be this:
sum = 5;
function myFunction() {
var sumOther = sum + 5;
return sumOther;
}
console.log(“sum:” + sum); // 5
console.log(“myFunction:” + myFunction()); // 10
This is how you would get the run of the function and not the global variable ‘sum’
This is because you use (global) variable declared outside the function (function modify it directly so there is no need to return value). However it is not good way of write functions because they are less reusable because they need proper global context to be used. Better is to use something like this:
function myFunction(num) {
return num += 5;
}
var sum = 5;
var result = myFunction(5) ;
console.log(result); // -> 10
this function can be easily used ind different context because it have parameter num and works only on it (function uses only values declared inside its declaration and body)
The trick in your case a is scope of a function. In both cases variable sum is defined in global scope. When you calling the function, it goes through the following steps:
Look whether var sum is defined in current step Since it not defined
inside the function, go one step over and take a look into outer
scope. Yes, it is defined here, start using it.
Perform calculation.
You are using incremental operator sum += 5 so actually it can be
written as sum = sum + 5. If you will look into second case,
you'll notice that variable have increased value now. And since that
variable is taken from global scope, your function just mutates it.
NOTE: At this point no matter whether you are returning something
from function or not. Your function just mutated outer variable.
The last step - exit from function. As I said earlier, return value
matters only if you want to use result of function call directly,
for instance: var result = myFunction()

Trying to figure out code snippet in the book Eloquent JavaScript

Chapter 3 Functions has the following code snippet:
const power = function(base, exponent) {
let result = 1;
for(let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 10));
// 1024
can someone explain what is going on in the code line by line, i'm confused by let result = 1 the most. Thanks!
In the first line, you're declaring a variable result. However, it's being declared with let, not var. Let is similar to var, except it can't be accessed outside the block it is defined in (including functions, loops and conditional statements). And since it's in a function here, that first line is equivalent to:
var result = 1;
In the second line:
for (let count = 0; count < exponent; count++) {}
You're looping over exponent - so the code within the {} of the loop will be executed exponent times.
In the third line:
result *= base;
You're multiplying result and base, and assigning the value to result. This line is equivalent to:
result = result * base;
Final line:
return result;
This line stops the function and returns result. The return means that whenever a function is called, it essentially is replaced with the return value (like in this line):
console.log(power(2, 10));
This calls power() with arguments 2 and 10, and logs the returned value to the console.
This example is a simple approach of building and executing an exponential function in JavaScript.
That said, we know that the below will essentially be creating something like the following in pseudocode:
print the result of (number to the power of some other number)
The code walkthrough:
// initialize a constant variable named 'power' as a function declaration with two arguments, 'base' and 'exponent' which will be used inside the function
const power = function(base, exponent) {
// declare and initialize variable called 'result' and set it with value of 1
// why this is 1, is because any number to the power of 1 is itself, so rather than setting this to 0, this must be 1 to ensure that the exponential function works accurately
let result = 1;
// let count = 0; this will initialize a variable named count to be used within the loop
// count < exponent; this is the conditional statement, it means that the loop will continue looping until the condition is met, meaning loop until 'count' is no longer less than 'exponent'
// count++; this increments the value of the initial variable, in this case 'count' for every trip through the loop for the duration that the condition statement remains true
for (let count = 0; count < exponent; count++) {
// multiply the 'result' variable by the 'base' variable and set it as the new value of the 'result' variable
result *= base;
}
// return the 'result' variable so that it is now available outside of the function
return result;
};
// pass in the 'base' and 'exponent' arguments for the function 'power' in order to get the value (effectively, 2^10), and then print this value to the console
console.log(power(2, 10));
// 1024

having trouble understanding this recursion

I need to find the sum of integers in an array using recursion.
The following code throws an error :
var sum = function(array) {
if(array.length === 0) return 0;
while(array.length) {
sum = array[0] + sum(array.slice(1));
return sum;
}
}
while this works :
var sum = function(array) {
if(array.length === 0) return 0;
while(array.length) {
return array[0] + sum(array.slice(1));
}
}
The difference is the way the sum is returned. Can someone explain?
As mentioned in comments, the while loop never loops - it executes a return statement before testing the loop condition a second time.
Even so, why does the first version work the first time it is called but not the second?
sum = array[0] + sum(array.slice(1));
stores the right hand expression value in sum, after the function call to sum returns. That variable is in scope, so the assignment is valid.
But the assignment doesn't occur until after the call to sum (on the right hand side) returns. Each time sum returns, assignment overwrites the variable sum with the partial, and eventually the final result.
So the first call works successfully, but leaves sum set to the result of the first call. Since you can't call a number, it errors the second time you call it.

Making a Addition function using Javascript - toString(), parseInt(), etc

I'm a new student who's learning Javascript for the first time. This time I'm trying to better grasp the concepts of converting numbers into strings, storing them in arrays, converting them back to numbers, and adding.
In this assignment, I'm trying to write a function that takes the individual digits of a number and adds them together.
So for example, the function would take (95) and return 14. Or given (135), would return 9.
Here's what I got so far:
var addDigits = function(num) {
var newNum = num.toString();
newNum = newNum.split('');
var sum = 0;
var thirdNum = newNum.forEach(function(x) {
parseInt(x);
sum + x };
};
I'm fully aware that is not very good code, but could anyone give me any tips? Should I be using parseInt or Number?
You're pretty close. Few things though. array.forEach doesn't return anything. It's used for creating side effects (increasing sum would be considered a side effect of the function you're passing into the forEach). So setting the forEach to a variable doesn't accomplish anything. parseInt does return something, so you need to set it to a variable. And you also want to increase sum by the parsed integer plus the sum you already have. You can look into the += operator for that if you wish. Last, you need to return a value from the function itself! As it is, if you did var added = addDigits(123), added would be undefined. So finish it off with a return statement.
After you've got the grasp of that, I'd suggest looking into array.reduce to replace array.forEach since it's perfect for a problem such as this.
var addDigits = function(string) {
newNum = string.split('');
var sum = 0;
for(var i = 0 ; i < newNum.length ; i++) sum += parseInt(newNum[i]);
return sum;
};
console.log(addDigits("1234"));
Maybe this will be better:
function getDigitsSum(number) {
var charArray = (number + '').split('');
var sum = 0;
charArray.forEach(function(item) {
sum += parseInt(item)
})
return sum;
}
Number() performs type conversion, whereas parseInt() performs parsing.
What is the difference between parseInt() and Number()?
In this situation, it doesn't make a difference since the strings are proper integers.
Here's how I would do it.
var addDigits = function(num) {
var newNum = num.toString().split('');
var sum = newNum.map(Number).reduce((prev, curr) => prev + curr);
return sum;
};
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Assuming your input will always be an integer string, consider the following function:
var addDigits = function(strInt) {
var int = function(x) {
return parseInt(x,10) //10 is the radix
}
return strInt.split('').map(int).reduce(function(a,b){return a+b});
}
The function tied to var int will ensure that the provided integer string be parsed into its corresponding base 10 integer (notice the difference in type, which can be validated with Javascript's built-in typeof() function). The return will first .split the string, .map the int function against every value within the given string, and then apply whatever function you have within .reduce against an accumulated value - in this case, simply adding against each member of the array.

Categories