ReferenceError: assignment to undeclared variable "x"

The JavaScript strict mode -only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.

ReferenceError in strict mode only.

What went wrong?

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

Valid cases

To make "bar" a declared variable, you can add a let , const , or var keyword in front of it.

  • Strict mode

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Undeclared_var

How to Fix the ‘ReferenceError: assignment to undeclared variable “x”‘ Error in Our JavaScript App?

  • Post author By John Au-Yeung
  • Post date August 20, 2021
  • No Comments on How to Fix the ‘ReferenceError: assignment to undeclared variable “x”‘ Error in Our JavaScript App?

brown raccoon on rock

Sometimes, we may run into the ‘ReferenceError: assignment to undeclared variable "x"’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘ReferenceError: assignment to undeclared variable "x"’ when we’re developing JavaScript apps.

Fix the ‘ReferenceError: assignment to undeclared variable "x"’ When Developing JavaScript Apps

To fix the ‘ReferenceError: assignment to undeclared variable "x"’ when we’re developing JavaScript apps, we should make sure that we’re assigning values to variables that have already been declared.

The error message for this error is ReferenceError: "x" is not defined in Chrome.

And in Edge, the error message for this error is ReferenceError: Variable undefined in strict mode .

For instance, we shouldn’t write code like:

since bar hasn’t been declared in the foo function.

Instead, we should declare the bar variable by writing:

Now the error should be fixed.

Related Posts

Sometimes, we may run into the 'ReferenceError: "x" is not defined' when we're developing JavaScript…

It is easy to convert anything a boolean in JavaScript. Truthy values will be converted…

To throw errors in our JavaScript apps, we usually through an object that’s the instance…

javascript assignment to undeclared variable

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

ReferenceError: assignment to undeclared variable "x"

ReferenceError warning in strict mode only.

What went wrong?

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

Valid cases

To make "bar" a declared variable, you can add the var keyword in front of it.

  • Strict mode

© 2016 Mozilla Contributors Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-us/docs/web/javascript/reference/errors/undeclared_var

  • Skip to main content
  • Select language
  • Skip to search

ReferenceError: assignment to undeclared variable "x"

Valid cases.

ReferenceError warning in strict mode only.

What went wrong?

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

To make "bar" a declared variable, you can add the var keyword in front of it.

  • Strict mode

Document Tags and Contributors

  • ReferenceError
  • Strict Mode
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting a property that has only a getter
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

ReferenceError: assignment to undeclared variable "x"

The JavaScript strict mode -only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.

ReferenceError warning in strict mode only.

What went wrong?

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

What went wrong?

ReferenceError warning in strict mode only.

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

Valid cases

To make "bar" a declared variable, you can add the var keyword in front of it.

  • Strict mode

Document Tags and Contributors

  • ReferenceError
  • Strict Mode
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.ListFormat
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical operators
  • Object initializer
  • Operator precedence
  • (currently at stage 1) allows the creation of chained function calls in a readable manner. Basically, the pipeline operator provides syntactic sugar on a function call with a single argument allowing you to write">Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' operand 'x'
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • X.prototype.y called on incompatible type
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript variables, variables are containers for storing data.

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • Using const

In this first example, x , y , and z are undeclared variables.

They are automatically declared when first used:

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

Example using const, mixed example.

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

From the example above, you can guess that the total is calculated to be 11.

Variables are containers for storing values.

Advertisement

JavaScript Identifiers

All JavaScript variables must be identified with unique names .

These unique names are called identifiers .

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript identifiers are case-sensitive.

The Assignment Operator

In JavaScript, the equal sign ( = ) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

After the declaration, the variable has no value (technically it is undefined ).

To assign a value to the variable, use the equal sign:

You can also assign a value to the variable when you declare it:

In the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma :

A declaration can span multiple lines:

Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined .

The variable carName will have the value undefined after the execution of this statement:

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var , it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these statements:

You cannot re-declare a variable declared with let or const .

This will not work:

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :

You can also add strings, but strings will be concatenated:

Also try this:

If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Now try this:

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements".

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

Test Yourself With Exercises

Create a variable called carName and assign the value Volvo to it.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Skip to main content

UDN Web Docs: MDN Backup

ReferenceError: assignment to undeclared variable "x"

The JavaScript strict mode -only exception "Assignment to undeclated variable" occurs when the value has been assigned to an undeclared variable.

ReferenceError warning in strict mode only.

What went wrong?

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

  • Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
  • Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
  • Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Invalid cases

In this case, the variable "bar" is an undeclared variable.

Valid cases

To make "bar" a declared variable, you can add the var keyword in front of it.

  • Strict mode
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side JavaScript frameworks
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • FinalizationRegistry
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) operator
  • Destructuring assignment
  • Function expression
  • Grouping operator
  • Logical AND
  • Logical NOT
  • Logical operators
  • Nullish coalescing operator
  • Object initializer
  • Operator precedence
  • Optional chaining
  • Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Private class fields
  • Public class fields
  • constructor
  • Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration "x" before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the "delete" operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

What are undeclared and undefined variables in JavaScript?

  • Differences between undeclared and undefined variables in JavaScript
  • What does !== undefined mean in JavaScript ?
  • variable === undefined vs. typeof variable === “undefined” in JavaScript
  • How to check for null, undefined or blank Variables in JavaScript ?
  • What is Variable Scope in JavaScript ?
  • JavaScript TypeError - Variable "x" redeclares argument
  • Undefined Vs Null in JavaScript
  • Global and Local variables in JavaScript
  • Variables and Datatypes in JavaScript
  • What is Undefined X 1 in JavaScript ?
  • How to check for "undefined" value in JavaScript ?
  • JavaScript Course Variables in JavaScript
  • JavaScript ReferenceError - Assignment to undeclared variable
  • How to Declare a Variable in JavaScript ?
  • Undefined in JavaScript
  • JavaScript Local Variables
  • JavaScript Check the existence of variable
  • JavaScript undefined Property
  • Explain the difference between undefined and not defined in JavaScript
  • How to calculate the number of days between two dates in JavaScript ?
  • Convert a String to an Integer in JavaScript
  • How to append HTML code to a div using JavaScript ?
  • How to Open URL in New Tab using JavaScript ?
  • Difference between var and let in JavaScript
  • How do you run JavaScript script through the Terminal?
  • Remove elements from a JavaScript Array
  • How to read a local text file using JavaScript?
  • JavaScript console.log() Method
  • JavaScript Number toString() Method

Undefined: It occurs when a variable has been declared but has not been assigned any value. Undefined is not a keyword. 

Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using the var or const keyword . If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with the return value as “undefined” . The scope of the undeclared variables is always global. 

For example:

Undefined: 

Undeclared: 

Example 1: This example illustrates a situation where an undeclared variable is used. 

Output: 

Example 2: This example checks whether a given variable is undefined or not. 

Please Login to comment...

Similar reads.

  • JavaScript-Questions
  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Type of Undeclared Variable in JavaScript: What is it?

    javascript assignment to undeclared variable

  2. JavaScript ReferenceError

    javascript assignment to undeclared variable

  3. Javascript Variable (with Examples)

    javascript assignment to undeclared variable

  4. What are undeclared and undefined variables in JavaScript?

    javascript assignment to undeclared variable

  5. How to Check if a Variable is Undefined in Javascript · Dev Practical

    javascript assignment to undeclared variable

  6. assigning values to variables in javascript

    javascript assignment to undeclared variable

VIDEO

  1. html css JavaScript , assignment #2 at islamia university of Bahawalpur

  2. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  3. Javascript Variables

  4. Day 5: JavaScript Array and JSON

  5. JavaScript variable assignment const variable

  6. comparison operators in JavaScript in 1 min

COMMENTS

  1. ReferenceError: assignment to undeclared variable "x"

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  2. javascript

    @Hortitude: That's point (4). I generally wouldn't typeof foo=='undefined'; it tends to be used for (4a) global-sniffing, in which case I'd prefer to be explicit and say 'foo' in window, or (4b) testing against the undefined-value itself, in which case I'd prefer to be readable and say foo===undefined.In theory testing typeof against 'undefined' could have a use case that other constructs ...

  3. JavaScript ReferenceError

    This JavaScript exception Assignment to undeclared variable occurs in strict-mode If the value has been assigned to an undeclared variable. Message: ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in strict mode (Edge)

  4. A Comprehensive Guide on Reference Error: JavaScript

    If you've begun to try out JavaScript you might have encountered some pretty baffling errors. I know I sure did… ReferenceError: assignment to undeclared variable "x" Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored. Code without 'var' keyword

  5. Assignment (=)

    Assignment (=) The assignment ( =) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  6. Errors: Undeclared Var

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  7. How to Fix the 'ReferenceError: assignment to undeclared variable "x

    Fix the 'ReferenceError: assignment to undeclared variable "x"' When Developing JavaScript Apps To fix the 'ReferenceError: assignment to undeclared variable "x"' when we're developing JavaScript apps, we should make sure that we're assigning values to variables that have already been declared.

  8. javascript ReferenceError: assignment to undeclared variable "x

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  9. ReferenceError: assignment to undeclared variable "x"

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  10. Errors: Undeclared var

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  11. javascript

    For declared global variables, the configurable attribute is false. For undeclared global variables, it's true. The value of the configurable attribute can be retrieved using the getOwnPropertyDescriptor method, as shown below. var declared = 1; undeclared = 1; (Object.getOwnPropertyDescriptor(window, 'declared')).configurable // false.

  12. ReferenceError: assignment to undeclared variable "x"

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  13. JavaScript Variables

    All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). ... After the declaration, the variable has no value (technically it is undefined). To assign a value to the variable, use the equal sign ...

  14. ReferenceError: assignment to undeclared variable "x"

    Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

  15. What are undeclared and undefined variables in JavaScript?

    What are undeclared and undefined variables in JavaScript? Undefined: It occurs when a variable has been declared but has not been assigned any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using the var or const keyword. If we use 'typeof' operator to ...

  16. Set a variable if undefined in JavaScript

    Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match undefined but also null, false, 0, NaN, "" (but not "0"). If you want to set to default only if the variable is strictly undefined then the safest way is to write:

  17. How to set a javascript var as undefined

    Solution. To reliably set a variable boo to undefined, use a function with an empty return expression: boo = (function () { return; })(); After executing this line of code, typeof(boo) evaluates to 'undefined', regardless of whether or not the undefined global property has been set to another value. For example: undefined = 'hello'; var boo = 1;

  18. ReferenceError: assignment to undeclared variable "x"

    ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in strict mode (Edge) ... 已声明的和未声明的变量之间有一些差异,这可能会导致意想不到的结果,这就是为什么 JavaScript 在严格模式打印出这种错误。 ...

  19. ReferenceError: assignment to undeclared variable "x"

    それが、 strict モードで JavaScript がエラーを発生させる理由です。. 宣言した変数と宣言していない変数について、3 つの注意点があります。. 宣言した変数は、それが宣言された実行コンテキストに制限されます。. 宣言していない変数は常にグローバルです ...

  20. javascript

    There are two ways to name functions. You can set a variable equal to a function. Or you can give a function a name. Here are two ways to solve your problem