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
  • 5,992
  • 6
  • 47
  • 83
  • this '<' operator simple means smaller. The question should be "what does it mean for +num'" . – Nexus Jan 29 '18 at 05:57

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
  • 66,568
  • 14
  • 114
  • 112
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
  • 66,568
  • 14
  • 114
  • 112
grovesNL
  • 6,016
  • 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
  • 8,749
  • 4
  • 47
  • 57