Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code: how does it work?

I recently completed the DevTools ~> http://discover-devtools.codeschool.com/ course and while inspecting the code used I came across some sections which I did not understand:

String.prototype.repeat = function (num) {
  return new Array(num + 1).join(this);
};

used in the displayDate() method thus:

var body = $('body')[0].outerHTML.repeat(10000);

What is the importance of using this code?

Secondly, within displayToday() method, displayDate() method is called with an argument although it is not defined to take an arg. Why is this so?

I am learning JS and couldn't npt wrap my head around these. Any help is welcome.

like image 654
gmajivu Avatar asked Dec 07 '25 14:12

gmajivu


1 Answers

String.prototype.repeat = function (num) {
  return new Array(num + 1).join(this);
};

This code creates an array that is num+1 in length, filled with undefined. It is then collapsed into a string using join, separating each undefined value with the context this which is the outerHTML string. When an array is joined into a string, undefined values are just nothing, thus the string generated only contains your separators which appear num times, thereby "repeating" the string.

//let . be "undefined, which when turned into a string, is just nothing
[u,u,u,...,u].join('test');
'(u)test(u)test(u)...(u)test'
'testtest...test'

As for the second question, functions in JS will always take in arguments, even if the function isn't meant to take one. Defining arguments in the function in JS is simply assigning the passed arguments a name. The arguments will always go to the function, and collected in a special array available in functions as the arguments variable.

function fn(){
  console.log(arguments); //['hello','world'];
}

foo('hello','world');
like image 77
Joseph Avatar answered Dec 09 '25 04:12

Joseph