I still don't understand how it works...?

I posted a few days ago about how I don’t fully get the full concept of arguments in JavaScript. Like passing arguments in parameters, etc.

I was watching this tutorial and following along to it. I understand the code like what the code is supposed to do (open navbar in mobile screen) but, again, arguments? I just can’t get my head around it…

how does this code below work with the argument name element? I know it can be named whatever you would like but why does an argument have to be named for this function and querySelector??

How does this help in JavaScript?

//Select element function… so basicallly i will call this function, and whatever class or element or ID that I pass, it is going to be returned to me
const selectEl = function(element) {
return document.querySelector(element)
};
let menuToggler = selectEl(’.menu-toggle’);
let body = selectEl(‘body’);
menuToggler.addEventListener(‘click’, function (){
body.classList.toggle(‘open’);
})

a function has parameters
they are variables that exist inside the function and can have any name

function myFunc (bananas) {
   // doing something with bananas
}

when you call a function you pass arguments in and these arguments are assigned to the parameters in order

myFunc("orange") // the bananas parameter in the function has now value of "orange"
1 Like

Let’s put aside javascript functions for now. Think about algebraic functions. let’s say you have a function f(x) and it is equal to 2x+1. The “x” is like the argument in javascript functions. By plugging in a number (let’s say “3” for example), you will get a value given by the function.

f(3) = 2(3) + 1
f(3) = 6+1
f(3) = 7

Now how does this relate to a javascript function?
I will create the same function as shown above in javascript:

function y_equals_two_x_plus_1(x){
return 2 * x + 1;
};

you don’t actually need that crazy long title. try logging the function to the console while plugging in different numbers.

console.log( y_equals_two_x_plus_1(3) );

the function will return the given number. The main usage of a function is so that you won’t need to write so much of the same code over and over again.

Hope that helps.

1 Like

Ok, so arguments are values or references that are handed from the calling function or object to the called function or object. The idea behind this is like you are handing a function some data that it will use.

For your example specifically, element is passed by a string value that contains either the classes, indexes, and tags that will be passed to a selector in order to get the DOM object.

Now, element is only a placeholder for the argument that are passed to the function, but in some languages and applications you can also use this placeholder as a tag (I am not sure if you can do this in JavaScript though).

For example:
foo(variable=value)