Why Is My JavaScript Not Working? (With Examples)

We round up the most common causes for your JavaScript code not working.

Published Categorized as JavaScript, Web & Code

So the JavaScript tag you just added to your website isn’t working, and you want to get to the meat of the problem so you can fix it.

As any experienced developer will tell you, there’s more than one reason why this can happen. And, depending on how complex your code, finding that reason out can take you anywhere from a couple of minutes to hours of googling and debugging.

Hoping to help save you some time, in this post I’ve compiled a list of the most common mistakes that can make your JavaScript code “not work.”

Issues With the Tag

If your JavaScript code is not working, the first thing you should do is check the <script> tag.

When you include JavaScript in your HTML document with the <script> tag, many things can (and often do) go wrong. And, to avoid chasing a red herring, it’s best to rule them out before looking for other possible causes.

Misspelled Tag

Carefully inspect the <script> tag and the type="text/javascript" attribute.

Have you misspelled anything? Have you omitted a forward slash (/), quotation mark (‘), less-than (<) or greater-than (>) sign?

These mistakes happen more often than we think, especially when we work late into the night, with a reduced attention span, to meet tight deadlines.

Below, I’ve listed a few examples for things that can go wrong:

// Correct spelling
<script type="text/javascript"></script>

// Misspelled opening
<scrpt type="text/javascript"></script>

// Misspelled type="" attribute
<script type="text/javascrpt"></script>

// Dash instead of forward slash in type="" attribute
<script type="text-javascript"></script>

// Misspelled closing
<script type="text/javascript"></scipt>

// Omitted quotation symbol
<script type="text/javascript></script>

Wrong Relative Path or URI

If you’re loading your script from another location, such as your server or a CDN, make sure you’re using the right URI. In case you are, check if the file is still there.

Suppose you’re loading the script from your own server, and you’re doing it with a relative path. Check that relative path and make sure it’s correct.

If you’re loading the script from a CDN, try to open the URI in your browser and see if the file is still there. Scripts, especially libraries, are often updated—and legacy versions get deprecated.

// Mistyped relative path
<script src="/hme/scrips/my-script.js"></script>

// Old version that's no longer there
<script src="https://cdn.com/my-script.js?ver=1"></script>

Wrong Tag Placement

If your <script> tag contains code that needs to parse and manipulate the DOM elements in the HTML markup, you probably want to include it at the bottom of the <body> tag instead of the top of the <head> tag.

Not all scripts that should have a listener for the DOMContentLoaded event have it, and loading scripts that need to read the DOM before the DOM has been fully loaded is a very, very common issue.

For example, the following JavaScript code snippet won’t work because the tag is implemented in the HTML document’s <head> and, when it tries to select div#say-hello, it won’t be loaded and parsed by the browser window yet:

<!-- Doesn't work -->
<html>
<head>
<script>
document.querySelector('#say-hello').innerHTML('Hello world!');
</script>
</head>
<body>
<div id="say-hello"></div>
</body>
</html>

There are two solutions to this.

One is to add an event listener for the DOMContentLoaded event:

<!-- Works thanks to event listener -->
<html>
<head>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
    document.querySelector('#say-hello').innerHTML('Hello world!');
});
</script>
</head>
<body>
<div id="say-hello"></div>
</body>
</html>

The other is to place the tag immediately before the closing of the <body> tag:

<!-- Works thanks to tag placement -->
<html>
<head>
</head>
<body>
<div id="say-hello"></div>
<script>
document.querySelector('#say-hello').innerHTML('Hello world!');
</script>
</body>
</html>

Both of these solutions will fire the JavaScript code after the DOM element it needs to query for has been fully loaded and parsed by the browser.

Issues With the Code

Equally common are issues with the code itself, more often than not due to fatigue or haste. Chief among them are (1) mistyped function or variable names and (2) misused declarations.

The good news is that, by inspecting the error messages in the browser’s console, you can catch these quickly and easily because they tend to throw:

  • ReferenceError when you’re using the wrong name to reference a function or variable.
  • SyntaxError when you’ve mistyped something or omitted a character inside your function’s statement.

Try to rule these out before you continue debugging your code.

Mistyped Names

If you mistype your function’s name:

// Function statement
function myFunction() {};

// Function call with mistyped name
myFuntion(); // Uncaught ReferenceError: myFuntion is not defined

Or a constant’s or variable’s name within your function:

function myFunction() {
  let myVar = "Something";
  console.log(myVr); // Uncaught ReferenceError: myVr is not defined
};

You will see an Uncaught ReferenceError in the browser’s console.

Wrong Syntax

If you’re a Full-Stack Developer and you keep switching back and forth between HTML/CSS and JavaScript on the frontend and whatever language you’re using on the backend, it’s only a matter of time until you make a mistake and mix up the syntax between languages.

When in doubt, check the syntax of:

  • Parenthesis () after if, elseif, for, while statements.
  • Curly brackets {} for individual statement blocks (pay extra attention to statements within statements, a.k.a. nested statements).
  • Square brackets [] and new Array() method for arrays.
  • Quotation marks for strings (pay extra attention to quotes within quotation marks, a.k.a. nested quotes).
  • Uses of JavaScript methods and operators to store, manipulate, and compare data in objects (Are you using the right ones?).
  • Semicolons ; between statements in a loop.

My two go-to references for syntax are MDN Web Docs and this JavaScript cheat sheet.

Const, Let, and Var Declarations

In JavaScript, you can declare values using const, let, and var.

The declaration you opt for has important implications for your code because it determines what you can—and cannot—do to the data item/s you just stored in the memory.

As a general rule of thumb, here’s how to choose between the const, let, and var declarations in JavaScript:

  • Use const to declare a read-only constant.
  • Use let to declare a local variable limited to the scope of the block statement it’s declared in (as well as any sub-blocks).
  • Use var to declare a global variable or local variable limited to the function it’s declared in.

With all that said, let us take a look at some of the top issues pertaining from the limitations of these three declarations in JavaScript.

Trying to redeclare a constant:

You can’t redeclare a const. If you try to do it, as shown in the example below, the browser will throw an Uncaught SyntaxError back at you:

// Declares constant myList
const myList = '1,2,3,4,5';

const myList = '6,7,8,9,10'; // Uncaught SyntaxError: Identifier 'myList' has already been declared

Expectedly, if you’re trying to redeclare a constant with updated values, it won’t work and it may break the flow of data within your application.

Trying to redeclare a let variable in the same statement:

A let variable can only be declared once within a single statement. (But it can be reassigned as many times as you need it to.)

This means that you can reuse variable names, like x, y, and z across functions and statements—as long as you don’t try to do so within the same bracket or sub-bracket.

function myFunction() {
if (x) {
  // Declare once
  let y;

  // Try to redeclare
  let y; // SyntaxError
}
}

Keep this in mind, especially if you’re new to JavaScript or if you’re experienced with it, but you’ve only recently started to use let declarations in your code. This is a subtle constraint, and it can cause just as subtle bugs. 🙂

Image courtesy of Igor Vetushko /Depositphotos

Leave a comment

Your email address will not be published. Required fields are marked *