-1

Why the result seems different when I put the variable inside/outside of the function?

Variable sound outside the function:

var sound = "" ; 

var laugh = function(num) {
    for (var x = 0 ; x < num ; x++) {
        sound = sound + "ha" ;  
    }
    sound = sound +"!"; 
    return sound; 
}
console.log(laugh(3)) 

Variable sound inside the function


var laugh = function(num) {
    for (var x = 0 ; x < num ; x++) {
        var sound = "" ; 
        sound = sound + "ha" ;  
    }
    sound = sound +"!"; 
    return sound; 
}
console.log(laugh(3)) 
Nora
  • 15
  • 6
  • see: [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – pilchard Aug 29 '21 at 09:11
  • 1
    Second function, sound is reset to "" for each step. – Grumpy Aug 29 '21 at 10:38

1 Answers1

1

The way you declared your variable inside the function, it will always start as an empty string, because you are resetting it at every iteration in the loop.

If you want to declare your variable inside the function, you have to do it outside the for loop.

var laugh = function(num) {
    var sound = "" ; //here is where you should declare it
    for (var x = 0 ; x < num ; x++) {
        sound = sound + "ha" ;  
    }
    sound = sound +"!"; 
    return sound; 
}
console.log(laugh(3)) 
J_K
  • 688
  • 5
  • 12