Ошибка expected expression got

I got SyntaxError: expected expression, got '<' error in the console when i’m executing following node code

var express = require('express');
var app = express();
app.all('*', function (req, res) {
  res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
})

Error :enter image description here

I’m using Angular Js and it’s folder structure like bellow

enter image description here

What’s I’m missing here ?

asked Mar 6, 2015 at 7:30

underscore's user avatar

This code:

app.all('*', function (req, res) {
  res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})

tells Express that no matter what the browser requests, your server should return index.html. So when the browser requests JavaScript files like jquery-x.y.z.main.js or angular.min.js, your server is returning the contents of index.html, which start with <!DOCTYPE html>, which causes the JavaScript error.

Your code inside the callback should be looking at the request to determine which file to send back, and/or you should be using a different path pattern with app.all. See the routing guide for details.

answered Mar 6, 2015 at 7:33

T.J. Crowder's user avatar

T.J. CrowderT.J. Crowder

1.0m187 gold badges1912 silver badges1863 bronze badges

4

Try this, usually works for me:

app.set('appPath', 'public');
app.use(express.static(__dirname +'/public'));

app.route('/*')
  .get(function(req, res) {
    res.sendfile(app.get('appPath') + '/index.html');
  });

Where the directory public contains my index.html and references all my angular files in the folder bower_components.

The express.static portion I believe serves the static files correctly (.js and css files as referenced by your index.html). Judging by your code, you will probably need to use this line instead:

app.use(express.static(__dirname));

as it seems all your JS files, index.html and your JS server file are in the same directory.

I think what @T.J. Crowder was trying to say was use app.route to send different files other than index.html, as just using index.html will have your program just look for .html files and cause the JS error.

Hope this works!

answered May 14, 2015 at 23:55

devonj's user avatar

devonjdevonj

1,1781 gold badge12 silver badges24 bronze badges

The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw
application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.

answered Sep 18, 2015 at 10:12

Nick Roz's user avatar

Nick RozNick Roz

3,8512 gold badges36 silver badges57 bronze badges

2

I had same error. And in my case

REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.

SOLUTION: give access to user for resourses or remove restriction at all.

answered Sep 2, 2015 at 11:27

Erlan's user avatar

ErlanErlan

1,9901 gold badge22 silver badges31 bronze badges

You can also get this error message when you place an inline tag in your html but make the (common for me) typo that you forget to add the slash to the closing-script tag like this:

<script>
  alert("I ran!");
<script> <!-- OOPS opened script tag again instead of closing it -->

The JS interpreter tries to «execute» the tag, which looks like an expression beginning with a less-than sign, hence the error: SyntaxError: expected expression, got '<'

answered Nov 3, 2015 at 15:00

gigawatt's user avatar

gigawattgigawatt

871 silver badge4 bronze badges

2

Just simply add:

app.use(express.static(__dirname +'/app'));

where '/app' is the directory where your index.html resides or your Webapp.

Pang's user avatar

Pang

9,489146 gold badges81 silver badges122 bronze badges

answered May 26, 2017 at 7:12

Moolshankar Tyagi's user avatar

2

I had this same error when I migrated a WordPress site to another server.
The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

answered Mar 20, 2015 at 21:11

Birdie Golden's user avatar

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess.
The solution was to add the correct path slashes in .
Each situation is unique, but hope this helps someone.

answered Aug 4, 2015 at 16:58

Philip E's user avatar

Philip EPhilip E

8289 silver badges15 bronze badges

This problem occurs when your are including file with wrong path and server gives some 404 error in loading file.

answered Aug 7, 2015 at 12:06

Muhammad Khalid's user avatar

0

I got this type question on Django, and My issue is forget to add static to the <script> tag.

Such as in my template:

<script  type="text/javascript"  src="css/layer.js"></script>

I should add the static to it like this:

<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>

answered Oct 19, 2017 at 6:34

aircraft's user avatar

aircraftaircraft

24.4k27 gold badges90 silver badges165 bronze badges

This should work for you. If you are using SPA.

app.use('/', express.static(path.join(__dirname, 'your folder')));
// Send all other requests to the SPA
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'your folder/index.html'));
});

answered Oct 23, 2017 at 8:07

tigercosmos's user avatar

tigercosmostigercosmos

3353 silver badges17 bronze badges

I was getting this error when trying to access an angular SPA via ASP.NET Core. Turns out the environment variables were not being loaded correctly, and the following line was not being called:

app.UseSpaStaticFiles();

After I ensured the line was getting called, the app started working again.

answered Jan 21, 2022 at 17:46

Eternal21's user avatar

Eternal21Eternal21

4,0902 gold badges47 silver badges62 bronze badges

May be this helps someone. The error I was getting was

SyntaxError: expected expression, got ‘<‘

What I did clicked on view source in chrome and there I found this error

Notice: Undefined variable: string in
D:Projectsdemoge.php on line 66

The issue was this snippet of code,

$string= ''; <---- this should be declared outside the loop

while($row = mysql_fetch_assoc($result))
    {
        $string .= '{ id:'.$row['menu_id'].', pId:'.$row['parent_id'].', name:"'.$row['menu_name'].'"},';
    }

which fixed the problem.

answered Nov 9, 2018 at 12:52

TheTechGuy's user avatar

TheTechGuyTheTechGuy

16.4k16 gold badges115 silver badges135 bronze badges

Are you stuck with the uncaught syntaxerror expected expression got  in JavaScript?

If this error gives you a hard time don’t worry, we got your back! You just have to continue reading.

In this article, we’ll walk you through how to troubleshoot the uncaught syntaxerror expected expression got ‘<‘ error message.

The syntaxrror: expected expression got is an error message you might encounter while working with JavaScript.

This error message indicates that the JavaScript interpreter expected to find an expression in your code but instead found something else.

The specific details of the error message will depend on what the JavaScript engine found instead of the expected expression.

This error typically happens when the browser tries to fetch JavaScript files, but instead receives the contents of an HTML file from the server.

For example:

app.all('*', function (req, res) {
  res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})

In simple words, JavaScript engine expected an expression but got something else instead.

For instance, if the error message is Uncaught SyntaxError: expected expression, got ‘<’ it means that the JavaScript engine expected to find an expression but instead found a ‘<’ character.

This could happen if you accidentally included a ‘<’ character in your code where an expression was expected.

How to fix “uncaught syntaxerror expected expression got”?

To fix the uncaught syntaxerror: expected expression, got error message, you need to identify the specific syntax error in your code that is causing the error message. The details of the error message can provide clues about where to look for the error.

Once you have identified the syntax error, you can fix it by correcting the code. This could involve removing or replacing an incorrect character, adding missing characters or code, or reorganizing your code to ensure that expressions are placed where they are expected.

Here are the following solution which can help you to resolve the error:

Solution 1: Add missing expression

Example 1 Missing expression after an operator

Incorrect code:

function example() {
  var a = 50;
  if (a <) {
    console.log('a is less than 100');
  }
}

Output:

 SyntaxError: expected expression, got ')'

As you can see, the error occurs because the if statement is missing an expression after the < operator. To fix this error, we need to add an expression after the < operator.

Corrected code:

function example() {
  var a = 50;
  if (a < 100) { // fixed
    console.log('a is less than 100');
  }
}

example();

Output:

a is less than 100

Example 2: Incorrect use of a reserved word

Incorrect code:

function example() {
var return = 50; 
}

The error occurs because the variable name return is a reserved word in JavaScript. To fix this error, we need to use a different variable name that is not a reserved word.

Output:

SyntaxError: expected expression, got keyword 'return'

Corrected code:

function example() {
var returnValue = 50; 
console.log(returnValue);
}
example();

Output:

50

Example 3: Missing closing parenthesis

Incorrect code:


function example() {
var a = (50 + 30; 

The error occurs because the expression (50 + 30 is missing a closing parenthesis. To fix this error, we need to add the missing closing parenthesis.

Output:

SyntaxError: expected expression, got ';'
}

Corrected code:


function example() {
var a = (50 + 30); 
console.log(x);
}

example();

Output:

80

Solution 2: Correct any other syntax errors

Incorrect code:


let a = 100;
if (a === 100) 
  console.log("a is equal to 100");
}

The uncaught syntaxerror: expected expression error can also occur due to other syntax errors in your code. In this example, the error might be caused by missing closing curly braces (}) or improper indentation.

By ensuring the correct syntax, the error can be resolved. When a is equal to 100, the message “a is equal to 100” will be logged to the console


let a = 100;
if (a === 100) {
  console.log("a is equal to 100");
}

Output:

a is equal to 100

Conclusion

In conclusion, the syntaxrror: expected expression got is an error message you might encounter while working with JavaScript.

This error message indicates that the JavaScript interpreter expected to find an expression in your code but instead found something else.

This article already discussed what this error is all about and multiple ways to resolve this error.

By executing the solutions above, you can master this SyntaxError with the help of this guide.

You could also check out other SyntaxError articles that may help you in the future if you encounter them.

  • Syntaxerror await is only valid in async function
  • Syntaxerror missing parentheses in call to print
  • Syntaxerror missing initializer in const declaration

We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
//forms
;(function($){
    $.fn.forms=function(o){
        return this.each(function(){
            var th=$(this)
                ,_=th.data('forms')||{
                    errorCl:'error',
                    emptyCl:'empty',
                    invalidCl:'invalid',
                    notRequiredCl:'notRequired',
                    successCl:'success',
                    successShow:'4000',
                    mailHandlerURL:'bat/MailHandler.php',
                    ownerEmail:'support@template-help.com',
                    stripHTML:true,
                    smtpMailServer:'localhost',
                    targets:'input,textarea',
                    controls:'a[data-type=reset],a[data-type=submit]',
                    validate:true,
                    rx:{
                        ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".email":{rx:/^(("[w-s]+")|([w-]+(?:.[w-]+)*)|("[w-s]+")([w-]+(?:.[w-]+)*))(@((?:[w-]+.)*w[w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][0-9].|1[0-9]{2}.|[0-9]{1,2}.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})]?$)/i,target:'input'},
                        ".phone":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},
                        ".fax":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},
                        ".message":{rx:/.{20}/,target:'textarea'}
                    },
                    preFu:function(){
                        _.labels.each(function(){
                            var label=$(this),
                                inp=$(_.targets,this),
                                defVal=inp.val(),
                                trueVal=(function(){
                                            var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()
                                            return defVal==''?defVal:tmp
                                        })()
                            trueVal!=defVal
                                &&inp.val(defVal=trueVal||defVal)
                            label.data({defVal:defVal})                             
                            inp
                                .bind('focus',function(){
                                    inp.val()==defVal
                                        &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))
                                })
                                .bind('blur',function(){
                                    _.validateFu(label)
                                    if(_.isEmpty(label))
                                        inp.val(defVal)
                                        ,_.hideErrorFu(label.removeClass(_.invalidCl))                                          
                                })
                                .bind('keyup',function(){
                                    label.hasClass(_.invalidCl)
                                        &&_.validateFu(label)
                                })
                            label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()
                        })
                        _.success=$('.'+_.successCl,_.form).hide()
                    },
                    isRequired:function(el){                            
                        return !el.hasClass(_.notRequiredCl)
                    },
                    isValid:function(el){                           
                        var ret=true
                        $.each(_.rx,function(k,d){
                            if(el.is(k))
                                ret=d.rx.test(el.find(d.target).val())                                      
                        })
                        return ret                          
                    },
                    isEmpty:function(el){
                        var tmp
                        return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')
                    },
                    validateFu:function(el){                            
                        el.each(function(){
                            var th=$(this)
                                ,req=_.isRequired(th)
                                ,empty=_.isEmpty(th)
                                ,valid=_.isValid(th)                                
                            
                            if(empty&&req)
                                _.showEmptyFu(th.addClass(_.invalidCl))
                            else
                                _.hideEmptyFu(th.removeClass(_.invalidCl))
                            
                            if(!empty)
                                if(valid)
                                    _.hideErrorFu(th.removeClass(_.invalidCl))
                                else
                                    _.showErrorFu(th.addClass(_.invalidCl))                             
                        })
                    },
                    getValFromLabel:function(label){
                        var val=$('input,textarea',label).val()
                            ,defVal=label.data('defVal')                                
                        return label.length?val==defVal?'nope':val:'nope'
                    }
                    ,submitFu:function(){
                        _.validateFu(_.labels)                          
                        if(!_.form.has('.'+_.invalidCl).length)
                            $.ajax({
                                type: "POST",
                                url:_.mailHandlerURL,
                                data:{
                                    name:_.getValFromLabel($('.name',_.form)),
                                    email:_.getValFromLabel($('.email',_.form)),
                                    phone:_.getValFromLabel($('.phone',_.form)),
                                    fax:_.getValFromLabel($('.fax',_.form)),
                                    state:_.getValFromLabel($('.state',_.form)),
                                    message:_.getValFromLabel($('.message',_.form)),
                                    owner_email:_.ownerEmail,
                                    stripHTML:_.stripHTML
                                },
                                success: function(){
                                    _.showFu()
                                }
                            })          
                    },
                    showFu:function(){
                        _.success.slideDown(function(){
                            setTimeout(function(){
                                _.success.slideUp()
                                _.form.trigger('reset')
                            },_.successShow)
                        })
                    },
                    controlsFu:function(){
                        $(_.controls,_.form).each(function(){
                            var th=$(this)
                            th
                                .bind('click',function(){
                                    _.form.trigger(th.data('type'))
                                    return false
                                })
                        })
                    },
                    showErrorFu:function(label){
                        label.find('.'+_.errorCl).slideDown()
                    },
                    hideErrorFu:function(label){
                        label.find('.'+_.errorCl).slideUp()
                    },
                    showEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideDown()
                        _.hideErrorFu(label)
                    },
                    hideEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideUp()
                    },
                    init:function(){
                        _.form=_.me                     
                        _.labels=$('label',_.form)
 
                        _.preFu()
                        
                        _.controlsFu()
                                                        
                        _.form
                            .bind('submit',function(){
                                if(_.validate)
                                    _.submitFu()
                                else
                                    _.form[0].submit()
                                return false
                            })
                            .bind('reset',function(){
                                _.labels.removeClass(_.invalidCl)                                   
                                _.labels.each(function(){
                                    var th=$(this)
                                    _.hideErrorFu(th)
                                    _.hideEmptyFu(th)
                                })
                            })
                        _.form.trigger('reset')
                    }
                }
            _.me||_.init(_.me=th.data({forms:_}))
            typeof o=='object'
                &&$.extend(_,o)
        })
    }
})(jQuery)

Синтаксическая ошибка:Неожиданный знак

Исключения JavaScript «неожиданный токен» возникают,когда ожидалась определенная языковая конструкция,но было предоставлено что-то другое.Это может быть простая опечатка.

Message

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Error type

Что пошло не так?

Ожидалось,что будет определенная языковая конструкция,но было предоставлено кое-что еще.Это может быть простая опечатка.

Examples

Expression expected

Например,при цепочечных выражениях трейлинговые запятые не допускаются.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}

Правильным было бы опустить запятую или добавить другое выражение:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Недостаточно скобок

Иногда вы опускаете скобки вокруг операторов if :

function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { 
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} 

Поначалу скобки могут выглядеть правильно, но обратите внимание на то, как || находится вне скобок. Правильно было бы заключить в скобки || :

function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}

See also

  • SyntaxError


JavaScript

  • ReferenceError: присвоение необъявленной переменной «x»

    Исключение только для строгого режима JavaScript «Присвоение необъявленной переменной» возникает, когда значение ReferenceError было присвоено только в строгом режиме.

  • ReferenceError: ссылка на неопределенное свойство «x»

    Предупреждение JavaScript «ссылка на неопределенное свойство» возникает при попытке доступа к несуществующему объекту.

  • TypeError: «x» (не) «y»

    Исключение JavaScript «(не)y» возникает, когда был непредвиденный тип.

  • SyntaxError:оператор функции требует имени

    Исключение JavaScript «оператор функции требует имени» возникает, когда в коде есть оператор функции, требующий имени.

  • Previous
  • Overview: First steps
  • Next

When you built up the «Guess the number» game in the previous article, you may have found that it didn’t work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an
understanding of what JavaScript is.
Objective: To gain the ability and confidence to start fixing problems in your own
code.

Types of error

Generally speaking, when you do something wrong in code, there are two main types of error that you’ll come across:

  • Syntax errors: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!
  • Logic errors: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn’t an error message to direct you to the source of the error.

Okay, so it’s not quite that simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We’ll look at both of these types going forward.

An erroneous example

To get started, let’s return to our number guessing game — except this time we’ll be exploring a version that has some deliberate errors introduced. Go to GitHub and make yourself a local copy of number-game-errors.html (see it running live here).

  1. To get started, open the local copy inside your favorite text editor, and your browser.
  2. Try playing the game — you’ll notice that when you press the «Submit guess» button, it doesn’t work!

Note: You might well have your own version of the game example that doesn’t work, which you might want to fix! We’d still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.

At this point, let’s consult the developer console to see if it reports any syntax errors, then try to fix them. You’ll learn how below.

Fixing syntax errors

Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (if you can’t remember how to open this in your browser, follow the previous link to find out how). What’s even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser’s JavaScript engine. Now let’s go hunting.

  1. Go to the tab that you’ve got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines:
    "Number guessing game" demo page in Firefox. One error is visible in the JavaScript console: "X TypeError: guessSubmit.addeventListener is not a function [Learn More] (number-game-errors.html:86:3)".
  2. The first line of the error message is:
    Uncaught TypeError: guessSubmit.addeventListener is not a function
    number-game-errors.html:86:15
    
    • The first part, Uncaught TypeError: guessSubmit.addeventListener is not a function, is telling us something about what went wrong.
    • The second part, number-game-errors.html:86:15, is telling us where in the code the error came from: line 86, character 15 of the file «number-game-errors.html».
  3. If we look at line 86 in our code editor, we’ll find this line:

    Warning: Error message may not be on line 86.

    If you are using any code editor with an extension that launches a live server on your local machine, this will cause extra code to be injected. Because of this, the developer tools will list the error as occurring on a line that is not 86.

    guessSubmit.addeventListener("click", checkGuess);
    
  4. The error message says «guessSubmit.addeventListener is not a function», which means that the function we’re calling is not recognized by the JavaScript interpreter. Often, this error message actually means that we’ve spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for «mdn name-of-feature» with your favorite search engine. Here’s a shortcut to save you some time in this instance: addEventListener().
  5. So, looking at this page, the error appears to be that we’ve spelled the function name wrong! Remember that JavaScript is case-sensitive, so any slight difference in spelling or casing will cause an error. Changing addeventListener to addEventListener should fix this. Do this now.

Syntax errors round two

  1. Save your page and refresh, and you should see the error has gone.
  2. Now if you try to enter a guess and press the Submit guess button, you’ll see another error!
    Screenshot of the same "Number guessing game" demo. This time, a different error is visible in the console, reading "X TypeError: lowOrHi is null".
  3. This time the error being reported is:
    Uncaught TypeError: can't access property "textContent", lowOrHi is null
    

    Depending on the browser you are using, you might see a different message here. The message above is what Firefox will show you, but Chrome, for example, will show you this:

    Uncaught TypeError: Cannot set properties of null (setting 'textContent')
    

    It’s the same error, but different browsers describe it in a different way.

    Note: This error didn’t come up as soon as the page was loaded because this error occurred inside a function (inside the checkGuess() { } block). As you’ll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the checkGuess() function was run by line 86.

  4. The line number given in the error is 80. Have a look at line 80, and you’ll see the following code:
    lowOrHi.textContent = "Last guess was too high!";
    
  5. This line is trying to set the textContent property of the lowOrHi variable to a text string, but it’s not working because lowOrHi does not contain what it’s supposed to. Let’s see why this is — try searching for other instances of lowOrHi in the code. The earliest instance you’ll find is on line 49:
    const lowOrHi = document.querySelector("lowOrHi");
    
  6. At this point we are trying to make the variable contain a reference to an element in the document’s HTML. Let’s see what the variable contains after this line has been run. Add the following code on line 50:
    This code will print the value of lowOrHi to the console after we tried to set it in line 49. See console.log() for more information.
  7. Save and refresh, and you should now see the console.log() result in your console.
    Screenshot of the same demo. One log statement is visible in the console, reading simply "null". Sure enough, lowOrHi‘s value is null at this point, and this matches up with the Firefox error message lowOrHi is null. So there is definitely a problem with line 49. The null value means «nothing», or «no value». So our code to set lowOrHi to an element is going wrong.
  8. Let’s think about what the problem could be. Line 49 is using a document.querySelector() method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question:
  9. So we need a class selector here, which begins with a dot (.), but the selector being passed into the querySelector() method in line 49 has no dot. This could be the problem! Try changing lowOrHi to .lowOrHi in line 49.
  10. Try saving and refreshing again, and your console.log() statement should return the <p> element we want. Phew! Another error fixed! You can delete your console.log() line now, or keep it to reference later on — your choice.

Syntax errors round three

  1. Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
  2. At that point, the game fails again, and the same error is spat out that we got at the beginning — «TypeError: resetButton.addeventListener is not a function»! However, this time it’s listed as coming from line 94.
  3. Looking at line number 94, it is easy to see that we’ve made the same mistake here. We again just need to change addeventListener to addEventListener. Do this now.

A logic error

At this point, the game should play through fine, however after playing through a few times you’ll undoubtedly notice that the game always chooses 1 as the «random» number you’ve got to guess. Definitely not quite how we want the game to play out!

There’s definitely a problem in the game logic somewhere — the game is not returning an error; it just isn’t playing right.

  1. Search for the randomNumber variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 45:
    let randomNumber = Math.floor(Math.random()) + 1;
    
  2. And the one that generates the random number before each subsequent game is around line 113:
    randomNumber = Math.floor(Math.random()) + 1;
    
  3. To check whether these lines are indeed the problem, let’s turn to our friend console.log() again — insert the following line directly below each of the above two lines:
    console.log(randomNumber);
    
  4. Save and refresh, then play a few games — you’ll see that randomNumber is equal to 1 at each point where it is logged to the console.

Working through the logic

To fix this, let’s consider how this line is working. First, we invoke Math.random(), which generates a random decimal number between 0 and 1, e.g. 0.5675493843.

Next, we pass the result of invoking Math.random() through Math.floor(), which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:

Math.floor(Math.random()) + 1;

Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:

Math.floor(Math.random() * 100);

Hence us wanting to add 1, to give us a random number between 1 and 100:

Math.floor(Math.random() * 100) + 1;

Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!

Other common errors

There are other common errors you’ll come across in your code. This section highlights most of them.

SyntaxError: missing ; before statement

This error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the checkGuess() function:

const userGuess = Number(guessField.value);

to

const userGuess === Number(guessField.value);

It throws this error because it thinks you are trying to do something different. You should make sure that you don’t mix up the assignment operator (=) — which sets a variable to be equal to a value — with the strict equality operator (===), which tests whether one value is equal to another, and returns a true/false result.

The program always says you’ve won, regardless of the guess you enter

This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside checkGuess():

if (userGuess === randomNumber) {

to

if (userGuess = randomNumber) {

the test would always return true, causing the program to report that the game has been won. Be careful!

SyntaxError: missing ) after argument list

This one is pretty simple — it generally means that you’ve missed the closing parenthesis at the end of a function/method call.

SyntaxError: missing : after property id

This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing

to

This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!

SyntaxError: missing } after function body

This is easy — it generally means that you’ve missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the checkGuess() function.

SyntaxError: expected expression, got ‘string‘ or SyntaxError: unterminated string literal

These errors generally mean that you’ve left off a string value’s opening or closing quote mark. In the first error above, string would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.

For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what’s wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!

Summary

So there we have it, the basics of figuring out errors in simple JavaScript programs. It won’t always be that simple to work out what’s wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don’t turn out right, especially in the earlier stages of your learning journey.

See also

  • There are many other types of errors that aren’t listed here; we are compiling a reference that explains what they mean in detail — see the JavaScript error reference.
  • If you come across any errors in your code that you aren’t sure how to fix after reading this article, you can get help! Ask for help on the communication channels. Tell us what your error is, and we’ll try to help you. A listing of your code would be useful as well.
  • Previous
  • Overview: First steps
  • Next

  • Ошибка expected declaration specifiers or before string constant
  • Ошибка expected asm or attribute before token
  • Ошибка expected class name before token
  • Ошибка exiting pxe rom при загрузке windows
  • Ошибка existing state of has been invalidated