Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript arguments keyword and multiple arguments ...args

I have some issues with my code. Here I will show two versions of my code but one of them is not working.

This code using the arguments keyword is not working:

$(document).ready(function(){
  var data = {
    'one':'b',
    'two':'c',
    'three':'d'
  }
  function func(){
    for(var i=0;i<arguments.length;i++){
      $('.a').each(function(){
        if($(this).hasClass(data[arguments[i]])){
          $(this).css('background','red')
        }
      })
    }
  }
  func('one','two')
})
body{
  margin:0;
  pading:0;
  height:100vh;
}
.a{
  height:50px;
  width:50px;
  background:green;
  margin:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a"></div>
<div class="a b"></div>
<div class="a c"></div>

However when I use a rest parameter, ...val, everything works perfectly:

$(document).ready(function() {
  var data = {
    'one': 'b',
    'two': 'c',
    'three': 'd'
  }

  function func(...val) {
    for (var i = 0; i < val.length; i++) {
      $('.a').each(function() {
        if ($(this).hasClass(data[val[i]])) {
          $(this).css('background', 'red')
        }
      })
    }
  }
  func('one', 'two')
})
body {
  margin: 0;
  pading: 0;
  height: 100vh;
}

.a {
  height: 50px;
  width: 50px;
  background: green;
  margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a"></div>
<div class="a b"></div>
<div class="a c"></div>

How do I make this code work perfectly without using ...val and by using only the arguments keyword?

like image 592
Ayush Gupta Avatar asked Jan 01 '26 03:01

Ayush Gupta


2 Answers

This is because 'arguments' is a reserved keyword in Javascript. It's context will change when you call it inside other function inside the .each(). It is not just like any other variable that will be passed inside as it is.

If you want to achieve that, you should use arrow functions.
Arrow functions in JS
Hope that the issue was fixed.

like image 171
Lelouch Avatar answered Jan 02 '26 16:01

Lelouch


There are two more possible ways to do this in addition to your way:

  • Use an arrow function so that the scope of arguments is still linked to the outer function.
  • If you want to keep the function, you can pass the value every time as a parameter, but that's just a wastage of computational power.
like image 33
Ajay Nagar Avatar answered Jan 02 '26 18:01

Ajay Nagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!