TypeError: Assignment to Constant Variable in JavaScript

avatar

Last updated: Mar 2, 2024 Reading time · 3 min

banner

# TypeError: Assignment to Constant Variable in JavaScript

The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword.

When a variable is declared using const , it cannot be reassigned or redeclared.

assignment to constant variable

Here is an example of how the error occurs.

type error assignment to constant variable

# Declare the variable using let instead of const

To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const .

Variables declared using the let keyword can be reassigned.

We used the let keyword to declare the variable in the example.

Variables declared using let can be reassigned, as opposed to variables declared using const .

You can also use the var keyword in a similar way. However, using var in newer projects is discouraged.

# Pick a different name for the variable

Alternatively, you can declare a new variable using the const keyword and use a different name.

pick different name for the variable

We declared a variable with a different name to resolve the issue.

The two variables no longer clash, so the "assignment to constant" variable error is no longer raised.

# Declaring a const variable with the same name in a different scope

You can also declare a const variable with the same name in a different scope, e.g. in a function or an if block.

declaring const variable with the same name in different scope

The if statement and the function have different scopes, so we can declare a variable with the same name in all 3 scopes.

However, this prevents us from accessing the variable from the outer scope.

# The const keyword doesn't make objects immutable

Note that the const keyword prevents us from reassigning or redeclaring a variable, but it doesn't make objects or arrays immutable.

const keyword does not make objects immutable

We declared an obj variable using the const keyword. The variable stores an object.

Notice that we are able to directly change the value of the name property even though the variable was declared using const .

The behavior is the same when working with arrays.

Even though we declared the arr variable using the const keyword, we are able to directly change the values of the array elements.

The const keyword prevents us from reassigning the variable, but it doesn't make objects and arrays immutable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: Unterminated string constant in JavaScript
  • TypeError (intermediate value)(...) is not a function in JS

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

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 const.

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Must be Assigned

JavaScript const variables must be assigned a value when they are declared:

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

But you can NOT reassign the array:

Constant Objects

You can change the properties of a constant object:

But you can NOT reassign the object:

Difference Between var, let and const

What is good.

let and const have block scope .

let and const can not be redeclared .

let and const must be declared before use.

let and const does not bind to this .

let and const are not hoisted .

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.

Browser Support

The let and const keywords are not supported in Internet Explorer 11 or earlier.

The following table defines the first browser versions with full support:

Advertisement

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope .

The x declared in the block, in this example, is not the same as the x declared outside the block:

You can learn more about block scope in the chapter JavaScript Scope .

Redeclaring

Redeclaring a JavaScript var variable is allowed anywhere in a program:

Redeclaring an existing var or let variable to const , in the same scope, is not allowed:

Reassigning an existing const variable, in the same scope, is not allowed:

Redeclaring a variable with const , in another scope, or in another block, is allowed:

Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

This is OK:

Variables defined with const are also hoisted to the top, but not initialized.

Meaning: Using a const variable before it is declared will result in a ReferenceError :

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

How the let, const, and var Keywords Work in JavaScript

TAPAS ADHIKARY

As a JavaScript beginner, you probably learned how to declare variables and assign values.

In the old, pre-ES6 era of JavaScript, developers used to declare variables using the keyword var or without any keywords. But times have changed!

With ES6 (EcmaScript 2015), the beginning of the modern era in JavaScript, the language got two new keywords to help us declare variables. These are let and const .

In this article, we will learn about all of these keywords (yes, including var ) with examples, and we'll see when to use them, and when not to use them.

If you like to learn from video content as well, this article is also available as a YouTube video tutorial here: 🙂

Btw, this is a widely discussed topic. Then, why write about it again? Well, these keywords can be tough to learn because:

  • Many devs try using them interchangeably(especially let with the other two).
  • At times, you may get confused about the relationship of these keywords to a fundamental JavaScript concept called Scope .

So, this article aims to teach these keywords in the context of three essential concepts. I hope you enjoy reading it.

How to Declare Variables in JavaScript

In JavaScript, we can declare variables in three different ways like this:

It is best when you understand var, let, and const with these three concepts:

  • Reassigning a new value
  • When you access a variable before declaring it

These keywords differ in usage in respect to these concepts. Let's see how.

Variable Scope in JavaScript

In JavaScript, we use scope as a way to identify where and whether we can use a variable. The variables may exist within a block, inside a function, or outside a function and block.

So, what is a block? A block (that is, a code block) is a section of the code we define using a pair of curly brace s({...}). Something like this:

On the other hand, a function is a bunch of code instructions you want to place logically together.

Usually, you define a function using the function keyword and a name. Just be aware that you can define a function without a name, which we call an anonymous function . But we won't discuss that in today's article for simplicity.

Here is a function with the name test .

Anything and everything outside of a block or a function we'll call Global . So, when we declare variables, they can exist within a block, inside a function, or outside of a block/function – that is, they have global scope.

There are mainly three types of scope:

  • Block Scope  
  • Functional Scope  
  • Global Scope

The three keywords var , let , and const work around these scopes. So let's understand how things fit together.

How to Use JavaScript Variables in Block Scope

If you do not want a variable declared inside a { } block to be accessed outside of the block, you need to declare them using the let or const keywords. Variables declared with the var keyword inside the { } block are accessible outside of the block too. So, be careful.

Let's take an example:

As you see, the value of the age variable may get overridden unknowingly and eventually introduce a bug. So, the moral of the story is,

Do not use the var keyword inside a block (block scope). Always use let and const instead.

How to Use JavaScript Variables in Functional Scope

A variable declared inside a function using these keywords is not accessible outside the function. That's the applied functional scope.

It is true irrespective of whether you use var, let, or const. Inside the function, they are pretty similar in managing a variable's scope.

Let's take an example again:

As you see above, none of the variables are accessible outside of the function, not even age which is declared using var . So, the conclusion is,

The variable declared with var inside a function is not accessible outside of it. The keyword var has function-scope.

How to Use JavaScript Variables in Global Scope

Variables declared outside of any functions and blocks are global and are said to have Global Scope . This means you can access them from any part of the current JavaScript program.

You can use var , let , and const to declare global variables. But you shouldn't do it too often.

As you see, the variables are accessible everywhere.

So, to restrict the scope of a variable using the var , let , and const keywords, here's the order of accessibility in scope starting with the lowest:

  • var : The functional scope level
  • let : The block scope level
  • const : The block scope level

The image below shows a mindmap of these three keywords with reference to different scopes.

28

Let's move on to the next concept to understand how these three keywords influence the code's behavior when we reassign a new value to a variable.

How to Reassign a New Value to a Variable in JavaScript

Once you've declared a variable with var or let , you can reassign a new value to the variable in your programming flow. It is possible if the variable is accessible to assign a value. But with const , you can't reassign a new value at all.

There is a tricky part with const that you must be aware of. When an object is declared and assigned a value with const , you can still change the value of its properties . But you can not reassign another object value to the same variable. This is a common mistake many devs make.

Check out the example here:

Here is a mindmap to help you grasp how reassigning works for variables declared with these three keywords.

29-1

What Happens When You Access a Variable Before Declaring it in JavaScript

As a pragmatic programmer, you should never try accessing a variable without declaring it. But in case it happens, let's see how the variable may behave.

With var in non-strict mode, the variable will have an undefined value. This means that a variable has been declared but has no value assigned.

In strict mode, you will get a ReferenceError that the variable is not declared.

With let and const , if you try to access a variable before declaring, you will always get a ReferenceError .

Here is a mindmap again to help you understand it visually. In the mindmap, var is depicted for non-strict mode.

30

That's all, my friends. You need to consider these circumstances and concepts to evaluate how var , let , and const behave. So, the rule goes:

  • Don't use var anymore.
  • Use let or const .
  • Use const more often. Use let when you need to reassign another value to a variable.
  • Don't try to access a variable without declaring it.

Before We End...

That's the story behind let , const , and var . I hope you found the article insightful and informative. My DMs are open on Twitter if you want to discuss further.

Let's connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well:

  • Follow me on Twitter
  • Subscribe to my YouTube Channel
  • Side projects on GitHub

See you soon with my next article. Until then, please take care of yourself, and stay happy.

Writer . YouTuber . Creator . Mentor

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope

JavaScript Hoisting

  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Variable Scope

JavaScript let Vs var

JavaScript Destructuring Assignment

  • JavaScript Keywords and Identifiers
  • JavaScript Data Types

JavaScript Variables and Constants

  • JavaScript Variables

A JavaScript variable is a container for storing data. For example,

Here, num is a variable that's storing the number 5 .

  • Declare Variables in JavaScript

In JavaScript, we use either the var or let keywords to declare variables. For example,

Here, x and y are variables.

Both var and let are used to declare variables. However, there are some differences between them.

Note: It is recommended we use let instead of var . However, there are a few browsers that do not support let . Visit JavaScript let browser support to learn more.

  • Initialize Variables in JavaScript

We use the assignment operator = to assign a value to a variable.

Here, 5 is assigned to variable x .

You can also initialize variables during its declaration.

In JavaScript, it's possible to declare multiple variables in a single statement.

Here, we have declared and assigned values to three variables in a single line:

  • The value assigned to x is 5 .
  • The value assigned to y is 6 .
  • The value assigned to z is 7 .

If you use a variable without initializing it, it will have an undefined value.

Here, we have declared a variable named x . But since it does not contain any value, its value is undefined .

If you want to learn more about undefined , visit JavaScript null and undefined .

  • Change the Value of Variables

The value of a variable may vary . Hence, the name variable .

Let's look at the example below to learn how to change the value of a variable:

Initially, the value of x is 5 . It is then changed to 3 .

  • Rules for Naming JavaScript Variables
  • Variable names must start with either a letter, an underscore _ , or the dollar sign $ . For example,
  • Variables cannot start with numbers. For example,
  • Variable names are case-sensitive. So y and Y are different variables. For example,
  • Variable names cannot be reserved words (keywords). For example,

Note: In JavaScript, text values should be enclosed within either single quotes '' or double quotes "" . We will learn about this in detail in the JavaScript String tutorial.

You can name the variables any way you want. However, we recommend you use the following naming conventions:

  • In JavaScript, variables are generally named in camelCase format if they have multiple words. For example: firstName , annualSalary , numberOfBooks , etc.
  • It's a good practice to give a descriptive name to a variable. For example, if you are using a variable to store the number of apples, it is better to name that variable apples or numberOfApples rather than x or n .
  • JavaScript Constants

A constant is a type of variable whose value cannot be changed.

In JavaScript, we use the const keyword to create constants. For example,

Once a constant is initialized, we cannot change its value.

Always Initialize a Constant During Declaration

If you do not initialize a constant at the time of declaration, it throws an error. For example,

Note: If you are sure that the value of a variable won't change throughout the program, it's recommended you use const .

However, there are a few browsers that do not support const . Visit JavaScript const browser support to learn more.

Table of Contents

Video: javascript variables.

Sorry about that.

Related Tutorials

JavaScript Tutorial

  • 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 is Set Intersection in JavaScript ?
  • What is the use of the Bind Method ?
  • What is the use of the Confirm Function in JavaScript ?
  • How Hoisting works in JavaScript ?
  • What is the use of the Alert Function in JavaScript ?
  • How to Handle Errors in JavaScript ?
  • What is Function Currying in JavaScript ?
  • What is the use of the Prompt Function in JavaScript ?
  • How to use the ! Operator to negate a Boolean Value in JavaScript ?
  • What is the use of the Array.from() method in JavaScript ?
  • What are Classes in ES6 ?
  • How to Exit a Loop Before it Completes all Iterations in JavaScript ?
  • How to Create a Multi Line Comment in JavaScript ?
  • How do we use the encodeURIComponent() function in JavaScript ?
  • How to Create a Single Line Comment in JavaScript ?
  • How does the JSON.parse() method works in JavaScript ?
  • How to Check if a Variable is of Type Number in JavaScript ?
  • What is the use of the Math.random Function in JavaScript ?
  • How to Concatenate Two Variables in JavaScript ?

How to Declare a Constant Variable in JavaScript ?

In JavaScript , you can declare a constant variable using the const keyword. The const keyword is used to create variables whose values should not be reassigned once they are initially set.

Example: Here, pi is a constant variable, and its value is set to 3.14 . Once a value is assigned to a constant variable using const , you cannot change that value throughout the rest of the program.

Please Login to comment...

Similar reads.

  • JavaScript-QnA
  • Web Technologies
  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JavaScript const Keyword Explained with Examples

by Nathan Sebhastian

Posted on Oct 27, 2023

Reading time: 4 minutes

Hi friends! Today, I will teach you how the const keyword works in JavaScript works and when you should use it.

The const keyword is used to declare a variable that can’t be changed after its declaration. This keyword is short for constant (which means “doesn’t change”), and it’s used in a similar manner to the let and var keywords.

You write the keyword, followed it up with a variable name, the assignment = operator, and the variable’s value:

We’ll see how the const keyword differs from the let keyword next. Let’s write a variable called name that has a string value, and we change the value after the declaration:

The code runs without any problem, and the console.log displays the new value ‘Good morning!’ instead of the first value ‘Hello!’.

Now let’s replace let with const and run the code again:

This time, we get an error as follows:

Since we declared the message variable as a constant, JavaScript responded with an error when we tried to assign a new value to the variable.

A constant variable is usually written in an all-uppercase format ( message becomes MESSAGE )

If the variable name is more than one word, separate the words using underscores. For example: TOTAL_MESSAGE_COUNT .

The const Keyword Only Prevents Reassignment

The const keyword doesn’t allow you to change the object the variable points to, but you can still change the data in the object.

For example, suppose you have a person object that has a name property. You can change the name property value even when you declare the object using a const as follows:

But if you try to change the object the variable points to, you’ll get the same error:

Note carefully the differences between the two examples above. In the first example, the name property is modified, but the variable person still points to the same object. This is allowed.

In the second example, we tried to change the object the person variable points to, and this is not allowed.

The same goes when you have a variable pointing to an array. You can change the elements stored in the array, but not the array itself.

The const keyword prevents reassignment (making the variable point to a different value) but not mutation (editing the value itself)

When to use the const keyword

Now that you know how the const keyword works, when do you need to use it in your code?

The answer is when you need to declare a variable that will never change during the lifecycle of your program.

For example, suppose you’re writing a program that has a lot of time calculations. You can declare a few constants that store the relation between hours, minutes, and seconds as follows:

There will always be 60 seconds in a minute, 3600 seconds in a minute, and 24 hours in a day, no matter where you live, as long as it’s on Earth 😄

You also always have 7 days in a week, 4 weeks in a month, and 12 months in a year. A month can have different days (27, 28, 30, 31) so don’t make it a constant.

Another example is when you need to work with geometry. To calculate the circumference of a circle, you need the PI value, which is a constant:

I hope these examples help you get the point. The key to knowing when to use const is to ask yourself this: would you have to assign a new value to the variable later, after its declaration? If not, use const . Otherwise, use let .

This article has shown you how the const keyword works, how it doesn’t prevent mutation, and when to use it in your project.

The const keyword is kind of bewildering in how it doesn’t prevent mutation. Indeed, JavaScript is a tricky language with some weird behaviors that can lead to errors.

I have some more articles related to JavaScript that you can read here:

Bubble Sort in JavaScript Understanding Encapsulation in JavaScript

I also have a JavaScript course that’s currently in progress. I want to make this course the best and complete JavaScript course for beginners. If you enjoy this article, you might want to check it out.

Thanks for reading. See you next time! 👋

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

Marius Schulz

Constant Variables in JavaScript, or: When "const" Isn't Constant

ECMAScript 2015 introduced the let and const keywords as alternatives to var , which JavaScript has always had. Both let and const declare local variables with block scope rather than function scope . In addition, const provides some notion of constancy, which let doesn't.

Unfortunately, the name of the const keyword might be misleading. In JavaScript, const does not mean constant , but one-time assignment . It's a subtle yet important distinction. Let's see what one-time assignment means:

However, variables declared using the const keyword do not generally have a truly immutable value. Remember, const does not mean "constant", it means one-time assignment . The part that's constant is the reference to an object stored within the constant variable, not the object itself. The following example illustrates the difference:

Declaring a variable to be constant doesn't make the objects it references immutable, as the above example shows. Object properties can change or be deleted altogether. The same goes for arrays assigned to a constant variable; Elements can be added, removed, reordered, or modified:

For the sake of completeness, it is possible to create true constants in some cases. If a primitive value (such as a string, number, or boolean value) is assigned to a constant variable, that variable will be a true constant. Our PI constant is an example for this. There's no way to modify the value of the numeric literal 3.141592653589793 after it has been assigned.

To make an object truly immutable, you can pass it to the Object.freeze function to prevent any changes to its properties. Be aware that freeze is shallow, so you'll have to recursively call it for nested objects if you want the entire object tree to be frozen. If you need immutable data structures, it might be safer and more convenient to use a library such as Facebook's Immutable.js which is specifically made for this purpose.

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

TypeError: invalid assignment to const "x"

Const and immutability, what went wrong.

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword.

Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

Fixing the error

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.

const , let or var ?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var .

Check if you are in the correct scope. Should this constant appear in this scope or was is meant to appear in a function, for example?

The const declaration creates a read-only reference to a value. It does not  mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:

But you can mutate the properties in a variable:

Document Tags and Contributors

  • 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
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • 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." href="Property_access_denied.html">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: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing variable name
  • 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 read-only
  • TypeError: More arguments needed
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: cyclic object value
  • 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

11 Variables and assignment

11.1  let, 11.2.1  const and immutability, 11.2.2  const and loops.

  • 11.3  Deciding between const and let
  • 11.4.1  Shadowing variables
  • 11.5  (Advanced)
  • 11.6.1  Static phenomenon: scopes of variables
  • 11.6.2  Dynamic phenomenon: function calls

11.7.1  globalThis [ES2020]

11.8.1  const and let : temporal dead zone.

  • 11.8.2  Function declarations and early activation
  • 11.8.3  Class declarations are not activated early

11.8.4  var : hoisting (partial early activation)

  • 11.9.1  Bound variables vs. free variables
  • 11.9.2  What is a closure?
  • 11.9.3  Example: A factory for incrementors
  • 11.9.4  Use cases for closures

These are JavaScript’s main ways of declaring variables:

  • let declares mutable variables.
  • const declares constants (immutable variables).

Before ES6, there was also var . But it has several quirks, so it’s best to avoid it in modern JavaScript. You can read more about it in Speaking JavaScript .

Variables declared via let are mutable:

You can also declare and assign at the same time:

11.2  const

Variables declared via const are immutable. You must always initialize immediately:

In JavaScript, const only means that the binding (the association between variable name and variable value) is immutable. The value itself may be mutable, like obj in the following example.

You can use const with for-of loops, where a fresh binding is created for each iteration:

In plain for loops, you must use let , however:

11.3 Deciding between const and let

I recommend the following rules to decide between const and let :

  • const indicates an immutable binding and that a variable never changes its value. Prefer it.
  • let indicates that the value of a variable changes. Use it only when you can’t use const .

exercises/variables-assignment/const_exrc.mjs

11.4 The scope of a variable

The scope of a variable is the region of a program where it can be accessed. Consider the following code.

  • Scope A is the (direct) scope of x .
  • Scopes B and C are inner scopes of scope A.
  • Scope A is an outer scope of scope B and scope C.

Each variable is accessible in its direct scope and all scopes nested within that scope.

The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.

11.4.1 Shadowing variables

You can’t declare the same variable twice at the same level:

eval() delays parsing (and therefore the SyntaxError ), until the callback of assert.throws() is executed. If we didn’t use it, we’d already get an error when this code is parsed and assert.throws() wouldn’t even be executed.

You can, however, nest a block and use the same variable name x that you used outside the block:

Inside the block, the inner x is the only accessible variable with that name. The inner x is said to shadow the outer x . Once you leave the block, you can access the old value again.

See quiz app .

11.5 (Advanced)

All remaining sections are advanced.

11.6 Terminology: static vs. dynamic

These two adjectives describe phenomena in programming languages:

  • Static means that something is related to source code and can be determined without executing code.
  • Dynamic means at runtime.

Let’s look at examples for these two terms.

11.6.1 Static phenomenon: scopes of variables

Variable scopes are a static phenomenon. Consider the following code:

x is statically (or lexically ) scoped . That is, its scope is fixed and doesn’t change at runtime.

Variable scopes form a static tree (via static nesting).

11.6.2 Dynamic phenomenon: function calls

Function calls are a dynamic phenomenon. Consider the following code:

Whether or not the function call in line A happens, can only be decided at runtime.

Function calls form a dynamic tree (via dynamic calls).

11.7 Global variables and the global object

JavaScript’s variable scopes are nested. They form a tree:

  • The outermost scope is the root of the tree.
  • The scopes directly contained in that scope are the children of the root.

The root is also called the global scope . In web browsers, the only location where one is directly in that scope is at the top level of a script. The variables of the global scope are called global variables and accessible everywhere. There are two kinds of global variables:

  • They can only be created while at the top level of a script, via const , let , and class declarations.
  • They are created in the top level of a script, via var and function declarations.
  • The global object can be accessed via the global variable globalThis . It can be used to create, read, and delete global object variables.
  • Other than that, global object variables work like normal variables.

The following HTML fragment demonstrates globalThis and the two kinds of global variables.

Each ECMAScript module has its own scope. Therefore, variables that exist at the top level of a module are not global. Fig.  5 illustrates how the various scopes are related.

The global variable globalThis is the new standard way of accessing the global object. It got its name from the fact that it has the same value as this in global scope.

For example, in browsers, there is an indirection . That indirection is normally not noticable, but it is there and can be observed.

11.7.1.1 Alternatives to globalThis

Older ways of accessing the global object depend on the platform:

  • Global variable window : is the classic way of referring to the global object. But it doesn’t work in Node.js and in Web Workers.
  • Global variable self : is available in Web Workers and browsers in general. But it isn’t supported by Node.js.
  • Global variable global : is only available in Node.js.

11.7.1.2 Use cases for globalThis

The global object is now considered a mistake that JavaScript can’t get rid of, due to backward compatibility. It affects performance negatively and is generally confusing.

ECMAScript 6 introduced several features that make it easier to avoid the global object – for example:

  • const , let , and class declarations don’t create global object properties when used in global scope.
  • Each ECMAScript module has its own local scope.

It is usually better to access global object variables via variables and not via properties of globalThis . The former has always worked the same on all JavaScript platforms.

Tutorials on the web occasionally access global variables globVar via window.globVar . But the prefix “ window. ” is not necessary and I recommend to omit it:

Therefore, there are relatively few use cases for globalThis – for example:

  • Polyfills that add new features to old JavaScript engines.
  • Feature detection, to find out what features a JavaScript engine supports.

11.8 Declarations: scope and activation

These are two key aspects of declarations:

  • Scope: Where can a declared entity be seen? This is a static trait.
  • Activation: When can I access an entity? This is a dynamic trait. Some entities can be accessed as soon as we enter their scopes. For others, we have to wait until execution reaches their declarations.

Tbl.  1 summarizes how various declarations handle these aspects.

import is described in §27.5 “ECMAScript modules” . The following sections describe the other constructs in more detail.

For JavaScript, TC39 needed to decide what happens if you access a constant in its direct scope, before its declaration:

Some possible approaches are:

  • The name is resolved in the scope surrounding the current scope.
  • You get undefined .
  • There is an error.

Approach 1 was rejected because there is no precedent in the language for this approach. It would therefore not be intuitive to JavaScript programmers.

Approach 2 was rejected because then x wouldn’t be a constant – it would have different values before and after its declaration.

let uses the same approach 3 as const , so that both work similarly and it’s easy to switch between them.

The time between entering the scope of a variable and executing its declaration is called the temporal dead zone (TDZ) of that variable:

  • During this time, the variable is considered to be uninitialized (as if that were a special value it has).
  • If you access an uninitialized variable, you get a ReferenceError .
  • Once you reach a variable declaration, the variable is set to either the value of the initializer (specified via the assignment symbol) or undefined – if there is no initializer.

The following code illustrates the temporal dead zone:

The next example shows that the temporal dead zone is truly temporal (related to time):

Even though func() is located before the declaration of myVar and uses that variable, we can call func() . But we have to wait until the temporal dead zone of myVar is over.

11.8.2 Function declarations and early activation

In this section, we are using functions – before we had a chance to learn them properly. Hopefully, everything still makes sense. Whenever it doesn’t, please see §25 “Callable values” .

A function declaration is always executed when entering its scope, regardless of where it is located within that scope. That enables you to call a function foo() before it is declared:

The early activation of foo() means that the previous code is equivalent to:

If you declare a function via const or let , then it is not activated early. In the following example, you can only use bar() after its declaration.

11.8.2.1 Calling ahead without early activation

Even if a function g() is not activated early, it can be called by a preceding function f() (in the same scope) if we adhere to the following rule: f() must be invoked after the declaration of g() .

The functions of a module are usually invoked after its complete body is executed. Therefore, in modules, you rarely need to worry about the order of functions.

Lastly, note how early activation automatically keeps the aforementioned rule: when entering a scope, all function declarations are executed first, before any calls are made.

11.8.2.2 A pitfall of early activation

If you rely on early activation to call a function before its declaration, then you need to be careful that it doesn’t access data that isn’t activated early.

The problem goes away if you make the call to funcDecl() after the declaration of MY_STR .

11.8.2.3 The pros and cons of early activation

We have seen that early activation has a pitfall and that you can get most of its benefits without using it. Therefore, it is better to avoid early activation. But I don’t feel strongly about this and, as mentioned before, often use function declarations because I like their syntax.

11.8.3 Class declarations are not activated early

Even though they are similar to function declarations in some ways, class declarations are not activated early:

Why is that? Consider the following class declaration:

The operand of extends is an expression. Therefore, you can do things like this:

Evaluating such an expression must be done at the location where it is mentioned. Anything else would be confusing. That explains why class declarations are not activated early.

var is an older way of declaring variables that predates const and let (which are preferred now). Consider the following var declaration.

This declaration has two parts:

  • Declaration var x : The scope of a var -declared variable is the innermost surrounding function and not the innermost surrounding block, as for most other declarations. Such a variable is already active at the beginning of its scope and initialized with undefined .
  • Assignment x = 123 : The assignment is always executed in place.

The following code demonstrates the effects of var :

11.9 Closures

Before we can explore closures, we need to learn about bound variables and free variables.

11.9.1 Bound variables vs. free variables

Per scope, there is a set of variables that are mentioned. Among these variables we distinguish:

  • Bound variables are declared within the scope. They are parameters and local variables.
  • Free variables are declared externally. They are also called non-local variables .

Consider the following code:

In the body of func() , x and y are bound variables. z is a free variable.

11.9.2 What is a closure?

What is a closure then?

A closure is a function plus a connection to the variables that exist at its “birth place”.

What is the point of keeping this connection? It provides the values for the free variables of the function – for example:

funcFactory returns a closure that is assigned to func . Because func has the connection to the variables at its birth place, it can still access the free variable value when it is called in line A (even though it “escaped” its scope).

Static scoping is supported via closures in JavaScript. Therefore, every function is a closure.

11.9.3 Example: A factory for incrementors

The following function returns incrementors (a name that I just made up). An incrementor is a function that internally stores a number. When it is called, it updates that number by adding the argument to it and returns the new value.

We can see that the function created in line A keeps its internal number in the free variable startValue . This time, we don’t just read from the birth scope, we use it to store data that we change and that persists across function calls.

We can create more storage slots in the birth scope, via local variables:

11.9.4 Use cases for closures

What are closures good for?

For starters, they are simply an implementation of static scoping. As such, they provide context data for callbacks.

They can also be used by functions to store state that persists across function calls. createInc() is an example of that.

And they can provide private data for objects (produced via literals or classes). The details of how that works are explained in Exploring ES6 .

Troubleshooting and Fixing TypeError – Assignment to Constant Variable Explained

Introduction.

TypeError is a common error in JavaScript that occurs when a value is not of the expected type. One specific type of TypeError that developers often encounter is the “Assignment to Constant Variable” error. In this blog post, we will explore what a TypeError is and dive deep into understanding the causes of the “Assignment to Constant Variable” TypeError.

assignment to constant variable. in javascript

Causes of TypeError: Assignment to Constant Variable

The “Assignment to Constant Variable” TypeError is triggered when a developer attempts to modify a value assigned to a constant variable. There are a few common reasons why this error might occur:

Declaring a constant variable using the const keyword

One of the main causes of the “Assignment to Constant Variable” TypeError is when a variable is declared using the const keyword. In JavaScript, the const keyword is used to declare a variable that cannot be reassigned a new value. If an attempt is made to assign a new value to a constant variable, a TypeError will be thrown.

Attempting to reassign a value to a constant variable

Another cause of the “Assignment to Constant Variable” TypeError is when a developer tries to reassign a new value to a variable declared with the const keyword. Since constant variables are by definition, well, constant, trying to change their value will result in a TypeError.

Scoping issues with constant variables

Scoping plays an important role in JavaScript, and it can also contribute to the “Assignment to Constant Variable” TypeError. If a constant variable is declared within a specific scope (e.g., inside a block), any attempts to modify its value outside of that scope will throw a TypeError.

Common Scenarios and Examples

Scenario 1: declaring a constant variable and reassigning a value.

In this scenario, let’s consider a situation where a constant variable is declared, and an attempt is made to reassign a new value to it:

Explanation of the error:

When the above code is executed, a TypeError will be thrown, indicating that the assignment to the constant variable myVariable is not allowed.

Code example:

Troubleshooting steps:

  • Double-check the declaration of the variable to ensure that it is indeed declared using const . If it is declared with let or var , reassigning a value is allowed.
  • If you need to reassign a value to the variable, consider declaring it with let instead of const .

Scenario 2: Modifying a constant variable within a block scope

In this scenario, let’s consider a situation where a constant variable is declared within a block scope, and an attempt is made to modify its value outside of that block:

The above code will produce a TypeError, indicating that myVariable cannot be reassigned outside of the block scope where it is declared.

  • Ensure that you are referencing the constant variable within the correct scope. Trying to modify it outside of that scope will result in a TypeError.
  • If you need to access the variable outside of the block, consider declaring it outside the block scope.

Best Practices for Avoiding TypeError: Assignment to Constant Variable

Understanding when to use const vs. let.

In order to avoid the “Assignment to Constant Variable” TypeError, it’s crucial to understand the difference between using const and let to declare variables. The const keyword should be used when you know that the value of the variable will not change. If you anticipate that the value may change, consider using let instead.

Properly scoping constant variables

It’s essential to also pay attention to scoping when working with constant variables. Make sure that you are declaring the variables in the appropriate scope and avoid trying to modify them outside of that scope. This will help prevent the occurrence of the “Assignment to Constant Variable” TypeError.

Considerations for handling immutability

Immutability is a concept that is closely related to constant variables. Sometimes, using const alone may not be enough to enforce immutability. In such cases, you may need to use techniques like object freezing or immutable data structures to ensure that values cannot be modified.

In conclusion, the “Assignment to Constant Variable” TypeError is thrown when there is an attempt to modify a value assigned to a constant variable. By understanding the causes of this error and following best practices such as using const and let appropriately, scoping variables correctly, and considering immutability, you can write code that avoids this TypeError. Remember to pay attention to the specific error messages provided, as they can guide you towards the source of the problem and help you troubleshoot effectively.

By keeping these best practices in mind and understanding how to handle constant variables correctly, you can write cleaner and more reliable JavaScript code.

Related posts:

  • Mastering Assignment to Constant Variable – Understanding the Syntax and Best Practices
  • JavaScript Variable Types – Exploring the Differences Between var, let, and const
  • Understanding the Differences – const vs let vs var – Which One to Use?
  • Understanding Constant Variables in Java – A Complete Guide
  • Understanding Assignment to Constant Variable – Tips and Strategies for Effective Programming

How to use 'const' in JavaScript?

In JavaScript, the "const" keyword is used to declare a variable that cannot be reassigned a new value. Here's how to use "const" in JavaScript:

In this example, we declare a variable called "myConstant" and assign it the value of 10. Once you've declared a constant using "const", you cannot change its value. For example, if you try to reassign a new value to "myConstant", you'll get an error:

This is because "myConstant" is a constant variable and cannot be reassigned a new value.

You can also declare and assign multiple constant variables at once, like this:

It's important to note that while you cannot reassign a new value to a constant variable, the value itself can still be mutable. For example, if you declare a constant variable that contains an array or an object, you can still modify the contents of that array or object:

OK, can modify the contents of the array However, you cannot reassign a new value to "myArray":

In general, it's a good practice to use "const" by default when declaring variables, unless you know that you need to reassign the variable later. This can help prevent accidental reassignments and make your code more predictable.

MarketSplash

How To Declare A Variable In JavaScript: Basics Explained

Dive deep into the world of JavaScript variables. Whether you're a novice or a pro, understanding the differences between var, let, and const can reshape how you write and structure your code.

💡 KEY INSIGHTS

  • Using `let` for variable declaration provides block-level scope, crucial for managing variables in complex applications and preventing scope pollution.
  • `const` should be your default for declaring variables in JavaScript to enforce immutability and clarity of intent, especially in functional programming paradigms.
  • While `var` offers function-level scope , its usage is discouraged in modern JavaScript due to potential scope leaks and hoisting confusion.
  • When declaring objects or arrays, using `const` does not prevent modification of the object's properties or array's elements, allowing for controlled mutability.

In the vast world of programming, JavaScript stands out for its ubiquity and ease of use. One fundamental aspect of this language is declaring variables. Let's explore the nuances and best practices of this essential task together.

assignment to constant variable. in javascript

Understanding Variables in JavaScript

Types of variables: var, let, const, scope and lifetime of variables, best practices for declaring variables, variable naming conventions, examples of variable declaration, comparing var, let, and const, frequently asked questions, declaring variables, data types in javascript, variable initialization.

Variables in JavaScript serve as containers to store and manage data. They allow developers to label data with a descriptive name, so the data can be referred to and manipulated throughout the program.

Variables are foundational to any programming language. Think of them as labeled boxes, where each box can contain a specific type of data, such as a number, text, or even complex data structures like arrays.

In JavaScript, you can declare a variable using the var keyword, although the more modern practices recommend using let or const .

JavaScript has several data types, and variables can hold any of them:

  • String: Textual data. E.g., let text = "Hello, World!";
  • Number: Numeric data. E.g., let num = 42;
  • Boolean: True or false. E.g., let isTrue = true;
  • Null: Represents a null value.
  • Undefined: A variable that hasn’t been assigned a value.

After declaring a variable, it's essential to initialize it with a value. If not, the variable's value will be undefined .

Variables play a crucial role in structuring and organizing the code. Being adept at creating and managing them is a fundamental skill for JavaScript developers.

The var Keyword

The let keyword, the const keyword.

In JavaScript, the way you declare variables can impact their behavior, especially concerning scope and reassignment. The language offers three primary methods for variable declaration: var , let , and const .

Introduced in the earliest versions of JavaScript, var has been the conventional means to declare variables. However, it has its quirks. Variables declared with var are function-scoped, which means they are accessible within the function they are defined in or globally if declared outside any function.

However, if you omit var accidentally, it can result in a global variable.

Introduced with ES6 (ECMAScript 2015), let offers block-level scoping, which is more intuitive than the function-scoping of var . This means the variable is only available within the block it's declared in, such as loops or conditionals.

Also a product of ES6, const behaves similarly to let in terms of scoping. The significant difference is that once a value is assigned to a const variable, it cannot be reassigned.

However, note that for objects and arrays, the content can change, but the variable will always refer to the same initial object or array.

For a clearer distinction:

  • Use var if you're working with older JavaScript versions or legacy code.
  • Opt for let when you need a block-scoped variable with reassignment.
  • Choose const for block-scoped variables with constant values.

Understanding these variable types ensures more predictable and manageable code, allowing developers to harness the full potential of JavaScript's flexibility.

Always Declare Variables

Local scope, block-level scope, temporal dead zone.

The concept of scope is paramount when discussing variables in any programming language, and JavaScript is no exception. In essence, scope determines where a variable can be accessed or modified. Coupled with scope is the lifetime of a variable, indicating how long a variable remains in memory.

Global Scope

When a variable is declared outside any function, it's said to have a global scope , meaning it can be accessed from any part of the code. However, global variables remain in memory for the duration of the page lifecycle, which can sometimes lead to unintended side effects.

Variables declared inside a function have a local scope . They are created when the function starts and deleted when the function completes its execution, thus determining their lifetime.

With the introduction of let and const , JavaScript now supports block-level scope . Such variables exist only within the confines of a block, like inside loops or if statements.

An interesting aspect of let and const declarations is the so-called Temporal Dead Zone (TDZ). It's a period where the variable exists but cannot be accessed until it's initialized.

Grasping the nuances of variable scope and lifetime allows developers to write efficient and error-free code. It ensures variables are only alive when needed, reducing memory usage, and prevents accidental overwrites or unintended access.

Use Descriptive Names

Favor let and const over var, initialize variables, avoid global variables, case conventions.

When working with JavaScript, adhering to certain best practices when declaring variables can ensure your code remains clean, readable, and efficient. Let's explore some of these practices that can enhance your coding experience.

It's a good habit to always declare your variables before using them. Omitting the declaration can result in unintentional global variables which might lead to unpredictable behavior.

Choose variable names that reflect their purpose or the data they hold. Descriptive names make the code self-explanatory and reduce the need for comments.

With the modern features of JavaScript, it's advisable to use let and const for variable declarations due to their block-level scope and predictability.

Though JavaScript allows variable declaration without initialization, it's wise to initialize variables to avoid undefined values which might lead to logic errors.

Minimizing the use of global variables can prevent unintended interactions between different parts of the code. It's good practice to encapsulate variables within functions or blocks as much as possible.

Adopt a consistent naming convention. Camel case ( thisIsCamelCase ) is widely used in JavaScript for variable names, making them readable and consistent across projects.

In essence, while JavaScript offers flexibility in variable declaration, adhering to these best practices fosters more maintainable, understandable, and effective code. Remember, clarity and predictability are invaluable in the collaborative world of coding.

Pascal Case

Avoid using reserved words, prefix booleans.

Choosing the right name for a variable is a significant aspect of coding. Proper naming conventions not only make your code more readable but also convey the variable's purpose and function.

Camel case is one of the most popular naming conventions in JavaScript. In this style, the first word starts with a lowercase letter, and subsequent words are capitalized.

Pascal case is similar to camel case, but the first letter of every word is capitalized. It's often used for class names in object-oriented programming, but can be seen in other contexts too.

In snake case , words are separated by underscores and are usually all lowercase. This convention is less common in JavaScript but can be seen in other languages like Python.

As mentioned earlier, variable names should convey the variable's purpose or content. Avoid generic names like temp , data , or num . Instead, opt for more descriptive names that provide context.

JavaScript, like many languages, has a set of reserved words which shouldn't be used as variable names. Words like if , else , function , and return fall into this category.

For boolean variables, it's a good practice to use a prefix like is , has , or can to indicate their boolean nature.

Incorporating these naming conventions can greatly improve the readability and clarity of your code. When names are clear and consistent, both the writer and the reader benefit, leading to fewer errors and smoother collaborations.

Basic Declarations

Arrays and objects, multiple declarations, assigning functions, destructuring assignment, default values, variables with template literals.

Variable declaration is fundamental in JavaScript. By showcasing different examples, we aim to illustrate the versatility and options available in the language. Here are some exemplary instances of how variables can be declared in JavaScript.

The foundation of JavaScript variables starts with var , let , and const .

Variables can also hold complex data types like arrays and objects .

You can declare multiple variables in a single line, although it's essential to ensure clarity.

Variables can also hold functions , allowing for flexibility and dynamic programming.

Modern JavaScript allows for destructuring , a way to extract multiple values from data stored in objects and arrays.

With let and const , you can assign default values to variables if no value is provided.

Template literals in ES6 offer a more intuitive way to embed variables within strings.

Going through these examples provides a broad view of how JavaScript variables can be declared and assigned. With this knowledge, you can navigate and create efficient, clean, and optimized code structures.

Scope of var

Scope of let, constancy of const.

  • Best Use Cases

When diving into JavaScript, three keywords often pop up for variable declaration: var , let , and const . Each has its characteristics, uses, and peculiarities.

The var keyword declares a variable globally, or locally to an entire function, regardless of block scope. However, this can lead to unexpected issues, especially when used in loops.

Introduced in ES6, the let keyword declares a block-scoped local variable. This means the variable's scope is limited to the block, statement, or expression where it's defined.

The const keyword, also introduced in ES6, is used to declare variables whose values should not be reassigned. This does not mean the variable is immutable—just its assignment.

Both var and let declarations are hoisted to the top of their containing function or block, but only var is initialized with undefined .

Best Use Casesr

  • Use var if you're working with older JavaScript code or if you have a specific reason to use function-scoped variables.
  • let is a better choice for general variable declaration, especially when block scope is essential.
  • const should be the go-to for variables that must not be reassigned. This is especially true for constants and some objects or arrays that shouldn't be reassigned entirely.

Deciding between var , let , and const can shape the way you structure and write your JavaScript code. By understanding their nuances, you're better equipped to write efficient and bug-free code.

What's the Difference Between Undefined and Not Defined?

In JavaScript, if you try to use a variable that hasn't been declared, it's "not defined". But if a variable is declared and not assigned a value, it's "undefined".

Is var Completely Obsolete Now?

Not necessarily. While let and const are now more prevalent due to block scoping and other features, var still has its place, especially when dealing with legacy code or specific use cases where function scoping is preferred.

What's the Benefit of Block Scoping?

Block scoping, provided by let and const , gives developers finer control over variable lifetimes and visibility. It helps avoid potential bugs, especially in loops and conditionals.

To wrap things up, grasping the distinctions and intricacies of variable declaration in JavaScript is pivotal for effective coding. The right choice can lead to cleaner, more efficient, and bug-free scripts.

Let’s test your knowledge!

What's the Benefit of Block Scoping in JavaScript?

Continue learning with these javasript guides.

  • How To Effectively Use JavaScript Replace
  • Getting To Know JavaScript Slice In Detail
  • JavaScript Trim In Depth: Functions And Applications
  • Getting Acquainted With JavaScript Sleep Functions
  • A Closer Look At JavaScript Operators And Their Significance

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

IMAGES

  1. Everything about Constants in JavaScript

    assignment to constant variable. in javascript

  2. How to create a constant or non-reassignable variable in JavaScript

    assignment to constant variable. in javascript

  3. Javascript Tutorial

    assignment to constant variable. in javascript

  4. Declaring a Variable with const in JavaScript

    assignment to constant variable. in javascript

  5. A Simple Explanation of JavaScript Variables: const, let, var

    assignment to constant variable. in javascript

  6. Using the Const Variable Type in JavaScript

    assignment to constant variable. in javascript

VIDEO

  1. Assignment Statement and Constant Variable

  2. Javascript Variables

  3. constant variable in php #programming #coding

  4. How to define constant in php 2023

  5. Variable Assignment in Java

  6. JavaScript #2: способы объявления переменных и констант в стандарте ES6+

COMMENTS

  1. TypeError: Assignment to constant variable

    In JavaScript, variables declared with const are read-only and cannot be reassigned a new value after initialization. This behavior ensures that the variable remains constant throughout its scope. To fix this error, consider using the let keyword instead of const if you need to update the variable's value.

  2. TypeError: Assignment to Constant Variable in JavaScript

    To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const. Variables declared using the let keyword can be reassigned. The code for this article is available on GitHub. We used the let keyword to declare the variable in the example. Variables declared using let can be ...

  3. TypeError: invalid assignment to const "x"

    For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: js. const obj = { foo: "bar" }; obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'. But you can mutate the properties in a variable:

  4. const

    The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. You should understand const declarations ...

  5. JavaScript const

    Constant Objects and Arrays. The keyword const is a little misleading. It does not define a constant value. It defines a constant reference to a value. Because of this you can NOT: Reassign a constant value; Reassign a constant array; Reassign a constant object; But you CAN: Change the elements of constant array; Change the properties of ...

  6. How the let, const, and var Keywords Work in JavaScript

    How to Declare Variables in JavaScript. ... Assignment to constant variable. age = 78; // the age value is 78. There is a tricky part with const that you must be aware of. When an object is declared and assigned a value with const, you can still change the value of its properties. But you can not reassign another object value to the same variable.

  7. node.js

    Assignment to constant variable. Ask Question Asked 5 years, 4 months ago. Modified 3 years, 6 months ago. Viewed 94k times 11 i try to read the user input and sent it as a email. but when i run this code it gives me this error: Assignment to constant variable. Any help will be appreciate ...

  8. JavaScript Variables and Constants

    JavaScript Constants. A constant is a type of variable whose value cannot be changed. In JavaScript, we use the const keyword to create constants. For example, // assign 5 to x const x = 5; Once a constant is initialized, we cannot change its value. // assign 5 to x const x = 5; // assign 10 to x. x = 10;

  9. How to Declare a Constant Variable in JavaScript

    In JavaScript, you can declare a constant variable using the const keyword. The const keyword is used to create variables whose values should not be reassigned once they are initially set. Example: Here, pi is a constant variable, and its value is set to 3.14. Once a value is assigned to a constant variable using const, you cannot change that ...

  10. JavaScript const Keyword Explained with Examples

    The const keyword is used to declare a variable that can't be changed after its declaration. This keyword is short for constant (which means "doesn't change"), and it's used in a similar manner to the let and var keywords. You write the keyword, followed it up with a variable name, the assignment = operator, and the variable's value ...

  11. const

    Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared. The value of a constant cannot change through re-assignment, and it can't be redeclared.

  12. Constant Variables in JavaScript, or: When "const"

    In JavaScript, const does not mean constant, but one-time assignment. It's a subtle yet important distinction. Let's see what one-time assignment means: // We're declaring PI to be a constant variable. const PI = 3.141592653589793; // Any attempt to assign a new value to PI // fails because PI is a constant variable.

  13. TypeError: invalid assignment to const "x"

    A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword. Examples Invalid redeclaration. Assigning a value to the same constant name in the same block-scope will throw. const COLUMNS = 80

  14. Declaring a Variable with const in JavaScript

    Uncaught TypeError: Assignment to constant variable. Declaring an Array using JavaScript's const Keyword When you declare an array with the const keyword in JavaScript, you can still add, remove and change elements within the array.

  15. Variables and assignment • JavaScript for impatient programmers (ES2022

    Scope A is the (direct) scope of x.; Scopes B and C are inner scopes of scope A.; Scope A is an outer scope of scope B and scope C.; Each variable is accessible in its direct scope and all scopes nested within that scope. The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.. 11.4.1 Shadowing variables

  16. Troubleshooting and Fixing TypeError

    In order to avoid the "Assignment to Constant Variable" TypeError, it's crucial to understand the difference between using const and let to declare variables. The const keyword should be used when you know that the value of the variable will not change.

  17. JavaScript Error: Assignment to Constant Variable

    In JavaScript, const is used to declare variables that are meant to remain constant and cannot be reassigned. Therefore, if you try to assign a new value to a constant variable, such as: 1 const myConstant = 10; 2 myConstant = 20; // Error: Assignment to constant variable 3. The above code will throw a "TypeError: Assignment to constant ...

  18. How to use 'const' in JavaScript?

    In JavaScript, the "const" keyword is used to declare a variable that cannot be reassigned a new value. Here's how to use "const" in JavaScript: const myConstant = 10; In this example, we declare a variable called "myConstant" and assign it the value of 10. Once you've declared a constant using "const", you cannot change its value.

  19. Uncaught TypeError: Assignment to constant variable in javascript module

    2. Imports are read-only live bindings to the original variable in the exporting module. The "read-only" part means you can't directly modify them. The "live" part means that you can see any modifications made to them by the exporting module. If you have a module that needs to allow other modules to modify the values of its exports (which is ...

  20. How To Declare A Variable In JavaScript: Basics Explained

    Variable declaration is fundamental in JavaScript. By showcasing different examples, we aim to illustrate the versatility and options available in the language. Here are some exemplary instances of how variables can be declared in JavaScript. Basic Declarations. The foundation of JavaScript variables starts with var, let, and const.

  21. javascript

    You can't reassign a variable which declared as const. If it is an object, you can change its properties. If it is an object, you can change its properties. If it is an array, you can change its values, but still you can't reassign it.

  22. javascript

    Uncaught TypeError: Assignment to constant variable. I know I'm writing about a very easy problem, but I can't figure out what the solution might be. ... JavaScript Constants. 2. Javascript Constant Setting Variable. 0. jQuery variable assignment confusion. Hot Network Questions