1

I encountered this strange supposed operator and am having trouble figuring out what it is. Any ideas?

var laugh = function(num){
var string=""; 
    for (i=0; i<+num; i++) {
    string+="ha";  
    }
return string + "!"; 
};

console.log(laugh(10));
nCardot
  • 4,600
  • 3
  • 34
  • 72

3 Answers3

4

One of the purposes of the + sign in JS is to parse the right part into the number.

const str = '4';
console.log(str + 5); // Concatenared as strings
console.log(+str + 5); // Sums the numbers

In your case you have an statement i < +num, which just parses num into number and i compares with it. If your num is a number, this will do nothing.

Look. I have used '10' instead of 10 and it still works, because the given string is parsed into number.

var laugh = function(num) {
   var string=""; 
   for (var i = 0; i < +num; i++) {
      string+="ha";  
   }
   
   return string + "!"; 
};

console.log(laugh('10'));
Suren Srapyan
  • 62,337
  • 13
  • 111
  • 105
2

<+ is not an operator. You may interpret it simply as for (i=0; i < +num; i++) where + is the unary plus operator. The unary plus operator will coerce num into a number.

For example, if the value passed to num was "100" (as a String), the unary plus operator would coerce it to 100 (a Number).

MDN contains some examples of unary plus and other arithmetic operators.

Suren Srapyan
  • 62,337
  • 13
  • 111
  • 105
grovesNL
  • 5,746
  • 2
  • 20
  • 32
1

This is the way this is parsed;

i < +num

In other words, num is being coerced to an integer before < is run on it.

There is no <+. They are parsed as separate symbols.

Shadow
  • 7,997
  • 4
  • 45
  • 55