Search code examples
javascriptfunctionvariablesparametersarguments

Why is a global variable undefined inside a function when I call it?


This function redirects to a URL, but the course_syllabus_code part shows up as undefined after the URL. I don’t know why this happens.

Basically the user will be able to open the code and enter the variables (there will be multiple) at the top. Then further below is where all the magic is supposed to happen.

The structure of the variable being entered cannot change but maybe the “magic” isn’t being executed in the best way possible.

const course_syllabus_code = "72524";

function syllabusLink(course_syllabus_code){
  location.href = "https://example.com/" + course_syllabus_code;
}
<ul>
  <li>
    <a href="javascript:syllabusLink();">Syllabus</a>
  </li>
</ul>


Solution

  • You're passing course_syllabus_code as an argument to the function, but calling the function without any arguments. When you call a function with fewer arguments than it defines, the ones that you don't pass come through with the value undefined. Since you've given the function argument the same name as the global, it "shadows" (obscures, hides) the global from the code in the function, which will access the argument instead.

    You have three choices (only do one of these, not all of them):

    1. Use the global by just removing the declared function argument:

      function syllabusLink() {
      // Removed here ------^
      
    2. Or, pass the global into the function where you call it:

      <a href="javascript:syllabusLink(course_syllabus_code)"><img src="CourseButton3.png" />Syllabus</a>
      

          I'd probably change the name of the argument as well (here I've used scode):

      function syllabusLink(scode) {
          location.href = 'https://foo.com'+scode;
      }
      
    3. Or, don't make course_syllabus_code a global at all, and pass it to the function:

      <a href="javascript:syllabusLink('72524')"><img src="CourseButton3.png" />Syllabus</a>
      

    I'd probably go for #3, unless there's a really good reason it has to be a global variable.