An example showcasing the use of ES6 rest parameters for arguments

I'm having trouble grasping the JavaScript example provided below.

function containsAll(arr) {
  for (let k = 1; k < arguments.length; k++) {
    let num = arguments[k];
    if (arr.indexOf(num) === -1) {
      return false;
    }
  }
  return true;
}
let x = [2, 4, 6, 7];
console.log(containsAll(x, 2, 4, 7));
console.log(containsAll(x, 6, 4, 9));

When I run this code, it outputs 1 and 0 to the console.

I'm struggling to visualize how this function should operate.

  1. Considering the call console.log(containsAll(x, 2, 4, 7)), the x should be substituted, resulting in console.log(containsAll(2, 4, 6, 7, 2, 4, 7)).
  2. The function containsAll processes those numbers (2, 4, 6, 7, 2, 4, 7).
  3. In the line,

    for(let k = 1; k < arguments.length; k++)
    , k should represent a new array [1, 2, 3, 4, 5, 6], depending on the argument length which corresponds to the length of arr (in this instance, the length is 7), correct?

  4. Next, in

    let num = arguments[k]; if (arr.indexOf(num) === -1) {return false;}
    let num should take the value num = 1, is that right?

  5. Subsequently, the if statement checks if 1 is present in the array, arr = [2, 4, 6, 7, 2, 4, 7]. If no match is found, it returns false. This process should continue for each number in the arr array, correct?

I'm simply trying to understand why the output is 1 for

console.log(containsAll(x, 2, 4, 7));
when I expected something like
[false, true, false, true, false, true]
.

Answer №1

  1. When using console.log(containsAll(x, 2, 4, 7)), make sure to replace the variable x with the actual values: console.log(containsAll(2, 4, 6, 7, 2, 4, 7)).

The correct values are [2, 4, 6, 7], 2, 4, 7

  1. The function containsAll takes these numbers: (2, 4, 6, 7, 2, 4, 7).

It takes [2, 4, 6, 7], 2, 4, 7

  1. When looking at this line,
    for(let k = 1; k < arguments.length; k++)
    , remember that k is representing the index in the arguments, not an array.

k is a number representing the index, not an array. The length is 4, and the array is a single element

  1. In the next step,
    let num = arguments[k]; if (arr.indexOf(num) === -1) {return false;}
    , the variable num should be set to num = 1, correct?

num iterates over the remaining elements of arguments (2, 4, 7). Note the skipping of the first element with k=1.

  1. The if statement checks if 1 is in the array, arr = [2, 4, 6, 7, 2, 4, 7]. If no match is found, it returns false. This process repeats for each number in the arr array.

The method returns as soon as it finds a match.

Concerns about the output of 1 when using

console.log(containsAll(x, 2, 4, 7));
arise from the fact that the execution stops when a return is encountered inside the method.

Execution halts at the moment of a return statement.

Answer №2

Currently, the output of your code shows `true` and `false` instead of 1 and 0. The reason why you're not getting an array like [false, true, false, true, false, true] is due to the `return` keyword used in the conditional `if` statement within your `for` loop.

Here's an alternative way to achieve the desired outcome:

function checkAll(arr) {
  let results = []
  for (let i = 1; i < arguments.length; i++) {
    let number = arguments[i];
    if (arr.indexOf(number) === -1) {
      results.push(0);
    } else {
      results.push(1);
    }
  }
  return results;
}

let y = [3, 5, 7, 8];
console.log(checkAll(y, 3, 5, 7)); //Expected Output [1, 1, 1]
console.log(checkAll(y, 7, 5, 9)); //Expected Output [1, 1, 0]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Communication between clients using a Progressive Web Application (PWA) when

Is there an efficient way to communicate and share data between devices using an offline progressive web app without internet access? I thought of exploring the possibilities with the Web Bluetooth API and generating QR codes through libraries like QRCode ...

Is there a way to enlarge an iFrame to fill the entire screen with just a button click, without using JavaScript

I am currently attempting to achieve full screen mode for an iFrame upon clicking a button, similar to the functionality on this site. On that website, there is a bar that expands to full screen along with the embedded game, which is what I am aiming for. ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...

The view in my node is rendering a different ejs view, and I have verified that the path

Currently, I am using the render method for a view in EJS. The path is correct but the view in the route is an old one that I used for testing purposes. This is my server.js code: https://i.sstatic.net/Xl1Ct.png Here is my route: https://i.sstatic.net/ ...

Steps to determine if an element exists in an array's key value

Check out this array example: Array ( [0] => [ "18.06.2016", "18.06.2016", "18.06.2016", "Test Test", "Test Name", "Michael Dean", "London", "1", "980.00", "", ...

VueJS1 flexible $parent.$parent method duration

Trying to utilize a parent function across multiple layers of nested child components. {{ $parent.$parent.testFunction('foo', 'bar') }} This approach currently functions, however, each time I navigate through levels in the hierarchy, ...

What could be causing such a significant variance in performance for a wrapped JavaScript function?

Here is a code snippet that I have been experimenting with: function Run () { var n = 2*1e7; var inside = 0; while (n--) { if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) < 1) inside++; } return inside; } var s ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

What causes my scene to appear black until OrbitControl is activated in ThreeJS?

What causes the scene in ThreeJS to only appear after clicking and moving the cursor? The page remains black until I interact by clicking and moving, then everything shows up. I'm stumped on what the issue could be. Any assistance would be greatly ap ...

Combining and organizing Javascript files for efficient loading and reusable code functionality

I've been tasked with cleaning up a project that contains around 45-50 separate .js javascript files. I'm trying to figure out the most effective way to reduce their loading size. Should I combine all the files into one using npm or gulp? Or shou ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

Issue with Bootstrap v3.3.6 Dropdown Functionality

previewCan someone help me figure out why my Bootstrap dropdown menu is not working correctly? I recently downloaded Bootstrap to create a custom design, and while the carousel is functioning properly, when I click on the dropdown button, the dropdown-menu ...

Surprising outcomes encountered when playing audio with JavaScript

https://i.sstatic.net/1jz45.png I've been diving into learning JavaScript and decided to create a simple web page. This page, when Pikachu (image) is clicked, plays an audio file. Similarly, if the string "Pikachu" is typed into the form, it should ...

Prevent automatic form filling in ASP.NET C# by disabling browser autocomplete for textboxes

Is there a way to prevent browsers from autocompleting textboxes in an ASP.NET C# application? I've attempted using the following jQuery code, but it doesn't seem to be working: $(document).ready(function () { $("input[type=text]").attr("aut ...

The functionality for dragging elements is not functioning properly in JavaScript

Here is the code I used in an attempt to make a div element draggable: let div = document.querySelector('div') div.onmousedown = function() { div.addEventListener('mousemove', move, true) } window.onmouseup = function() { window. ...

The read more button is not functioning properly when used in conjunction with the <br>

Can someone help me debug an issue I'm facing with my code? I have created an HTML tab that contains multiple DOM elements, each with a "Read More" button. Everything works fine when it's just plain text, but as soon as I add tags within the p ...

Issue with Tweening in Three.js: Initial value does not change

Having trouble with tweening my camera position. I've set up a Codepen with minimal code to showcase the issue, complete with annotations and plenty of console.log() statements for debugging purposes. Check out the Codepen The starting point of my c ...

What strategies can be used to reduce the frequency of update calls?

I'm currently working on a Tetris demo using ThreeJs. To render the game, I am utilizing requestAnimationFrame. Below is a snippet of the code: game.prototype.render = function(){ var thisObj = this; requestAnimationFrame( function() {thisObj.rend ...