-1

If I type display('Hello World'); in the script.js file,It will display Hello World in HTML.But in the display.js, display function is defined without any parameters.Could not understand how the display function works here? Code is referenced from one of the online tutorials.

<html>
  <body></body>
  <script src="display.js"></script>
  <script src="script.js"></script>
</html>


display('Hello World'); //scrpt.js
\\display.js
function display() {
  for (var i = 0; i < arguments.length; i++) {
    if (typeof arguments[i] === 'object') 
      displayObject(arguments[i])
    else
      displayValue(arguments[i], true)
  }
}

function displayObject(object) {
  if (object == null)
    displayValue('null')
  displayValue(getTypeName(object) + ' {')
  for(var propertyName in object) {
    if (propertyName != 'constructor') {
      displayValue(propertyName + ': ' + object[propertyName], false, true);
    }
  }
  displayValue('}', true)
}

function displayValue(value, addMargin, addPadding) {
  var div = document.createElement('div');
  div.style.fontSize='32px'
  if (addMargin)
    div.style.marginBottom='30px'
  if (addPadding)
    div.style.paddingLeft='30px'
  div.textContent = value;
  document.body.appendChild(div)
}

function getTypeName(object) {
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec(object.constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
}

1 Answers1

0

Have a look at the MDN docs for arguments

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

For example, if a function is passed 3 arguments, you can access them as follows:

arguments[0] // first argument
arguments[1] // second argument
arguments[2] // third argument
Liam
  • 27,717
  • 28
  • 128
  • 190