Power on/off button to control audio

I’m not sure about when it is assign to a variable.
I would need to test that out, my coding styleI don’t usually set function to a variable.

But it would work if just a function, ensure global scope:

function myFunc(){
//code here
}

This sounds like an issue with hoisting. When you say that it only works if you move myFunc OUTSIDE of the document.ready callback, are you moving it above or below the rest of the code?

If you define a function like in the following examples, you can place it anywhere in your script. It’ll be available everywhere because it’s being hoisted:

function myFunc(){
    // available everywhere
}

var myFunc = function(){
    // available everywhere
}

var myFunc = () => {
    // available everywhere
}

If you define a function with let or const, it must be defined before you try to access it:

let myFunc = function(){
    // I won't be hoisted to the top
}

const myFunc = () => {
    // I won't be hoisted to the top
}
1 Like

just for my understanding (forgive me if i use improper words or definitions):
i have to consider the audio as an obj, asking for the value of its first key (the audio, i suppose)…
then , there is shoudl be a “muted” prop which is by default false but that i can set to true… i also found the .prop() method vs the .attr() method and that is very very interesting for something else I was planning ^-^
but where can i find the list of properties of the audio element?

google is your friend search

search for “html audio tag”

https://www.w3schools.com/tags/tag_audio.asp

search for “jquery attr vs prop”

yes, there is also a w3s page about .prop() vs .attr() and, for my present level, i often find stackoverflow still too difficult

about the audio, i came to the same page you proposed but, my bad, I didn t realize i had not scrolled to the end :stuck_out_tongue:

regarding the question about the <button onclick=“myFunc()” i tested and yes, it was a matter of hoisting…if a use var it works :slight_smile:

ok - its a long hard road - but the more you do - the easier it gets :slight_smile:

About prop - read this one.
https://api.jquery.com/prop/
read the bit about
Attributes vs. Properties

Happy coding

forgive me, i will abuse of your kindness for one more question, related to scope, since I am a issue on a new project (the JS calculator)
I have a bunch of id-ed button corresponding to the numbers and mathematical operator and when I click one, i have to store the number/operator in a variable.
I have written something like this, so far

$(document).ready(function(){
   let selected = "";
   let arr= [];
   let temp;
   let regex = /\*|\//;
   //clickhandler
   $("button").click(function(){
      selected=$(this).text();          
  })
     console.log(selected);
  
})

this way, the console.log prints nothing. I tried to use var(instead of let) when declaring selected, but I get errors. I also tried to declare it as var outside jquery (as a global variable with no scope/function) but again no results.
According to what I studied, var has no block scope, so it should be available, but outside the handleclick func i cannot get the value I assign to selected inside the handleclick :frowning:

Ideally you should start this as another post (make it easier to track)

If you want a global variable - you can set it outside the $(document).ready()
Or it can be set by not using var before the variable name - but I would not recommend doing it like this.

Look where you have put the console.log …

It is outside of your click event

No no no please don’t start creating global variables all over the place, and don’t use var, that’s terrible practice :smiley:

In your case above, you can just put the console.log inside the click handler. Think of how JavaScript goes through your code:

  • it reads everything inside your document.ready function
  • it sees a variable selected, which is equal to an empty string
  • it sees that you’re attaching a click event to your button, which, if someone clicks the button, will reassign the selected variable to whatever the button’s text is
  • it sees your console.log, but nobody has clicked the button yet, so selected is still an empty string (that’s why you see nothing when you log it)
1 Like

Hello jsdisco,

Why so many "No"s for global variable?

And why not use var?
Why is it bad practice?

I created a new post

thank you for your help :slight_smile:

It’s just making your code vulnerable to bugs. As long as you write small projects, it’s nothing to worry about. But imagine you have a large real-world application with lots of variables. If they all live in the global scope, they might collide. Maybe at the top of the script, you declare a variable user. Then, 1000 lines later, someone else adds some code and also calls his variable user (because it’s an obvious choice for a variable name).

If you use var for the variable declaration, JavaScript won’t complain. It will just resassign the user variable with the new value. The guy who wrote the first 1000 lines of code will notice that somehow his user variable suddenly gives him wrong values or even throws bugs.

If you use let or const for the declaration, and try to initialise a variable twice with the same name, JavaScript won’t allow it, it’ll throw an error.


Another reason is that var leaks out of its scope. Take a simple example, you declare a variable index and set its value to 10:

var index = 10;

console.log(index) // 10

Now imagine there’s a lot of code between those two lines, and someone puts a loop in between, that also uses var index:

var index = 10;


for (var index = 0; index < 3; index++) {
    doStuffWith(someArray[index]);
}


console.log(index) // 3

And now, index has suddenly changed and logs 3 instead of 10. Again, a bug that’s really hard to pin down. Nothing of this can happen if you only use let and const.

Thanks jsdisco for explanation.

So with big projects can be a big problem.

But with global variables are you saying not to use them at all?

The var - I’ve not had the luxury to be able to use let and const, due to backwards compatility (IE issues). Yes, still have to cater for IE, hopefully not for much longer.
But yes the var index senario you mentioned - is a big issue - happend to me many a time, but not any more.

That’s not really possible, you’ll always have variables that need to be known across the whole application. I meant “limit scope of variables to the least necessary”.

Ok @jsdisco - good thing

As I use them for configuration type data stored as json or collection type information :slight_smile:

They do not have to be global just because you need them top-level. Wrap all the code in a IIFE, or something like a DOMContentLoaded handler. Then at least the top-level variables will still be scoped to a function.

Hello @lasjorg,

Is it good practice to add them in a IIFE?

Thinking about it - is that what jQuery does ?
I mean how it is structured - so can add plugins to it etc

Most people that use jQuery will wrap their code inside a ready handler. That would act like an IIFE as well, it’s a function that wraps all the code. So all the variables will be scoped to the ready function.

Not sure I understand the question. But I think the answer is no. They used to use AMD (no not the CPU, more info) but they switched to ES modules at some point. This is another (better) option if you only have to support browsers that support it. Not sure what they used before AMD but I’m guessing some sort of module pattern was used.

The example I gave (large codebase for huge application) was just to illustrate, but it’s unrealistic these days. Nobody would write a 10000 line JS file to handle it all. You’d split up your code into modular files that each handle their specific parts. So the variables of a file would be scoped anyway.

Not sure what you mean with “configuration type data stored as json or collection type information”, but I guess I’d put those into separate files and import them where I need them.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.