How to Declare Variables in JavaScript – var, let, and const Explained

Furkan Emin Can

Declaring variables is something you'll do all the time in JavaScript. And if you know the variable declaration process inside and out, you'll have the confidence to start writing great JS code.

Through this article, you will learn how to declare and mutate variables using var , let , and const , and you'll get a better understanding of the differences between them.

I will explain each concept in two parts:

  • Before ES6 ( var statement)
  • After ES6 ( let and const statements)

Let's dive into these different ways of declaring variables in JavaScript so you know how they work and when to use each one.

How to Declare Variables in JavaScript

When you declare variables in your app, the interpreter moves them to the top of their scope and allocates places in the memory before the execution starts. This process is called Hoisting .

1. How to declare variables with var in JavaScript:

When you declare a variable with var , it is hoisted and initialized in the memory as undefined before the code execution. So, you can access the variable before declaring it, but it returns undefined . This is sometimes called Declaration hoisting .

When the execution starts and reaches the line where the variable is declared, it replaces the value in memory with the value of the variable.

Under the hood, the code above behaves like this:

So we can use the strawberry variable before the declaration, but it returns undefined .

With this behavior, the program runs without errors. But in some cases, this can lead to unexpected results. We are only human, and on a busy day you might try to access a variable before declaring it. In a complex program, it can be hard to figure out where a strange undefined comes from.

2. How to declare variables with let and const in JavaScript:

When you declare a variable with let or const , it is also hoisted but it's allocated in the memory as uninitialized in the temporal dead zone . You cannot access variables in the temporal dead zone before you've declared them. So, if you try to access a variable before declaring it, the program throws a ReferenceError .

When the program reaches the line where the variable is declared, it initializes it with that value.

If you try to run this code snippet, you will see an error similar to the following one because we tried to access a variable in the temporal dead zone.

ReferenceError: Cannot access 'cherry' before initialization

This is a more predictable behavior than the behavior of the var statement.

So what do var , let , and const have in common?

In the previous two sections, you learned the process for declaring var , let , and const . In this section, we will look at the common concepts.

  • You can declare a variable with let and var without a value. In this case, the default value will be undefined .

This behavior is not valid for const because an initial value is required for it. If there is no initial value, the program throws a SyntaxError .

For the code above, an error gets thrown like this one:

"SyntaxError: Missing initializer in const declaration"

  • You can declare a chain of variables using the same statement. Put the statement at the beginning and separate each variable with a comma. This is valid for var , let , and const .

Nowadays, to declare variables, you'll want to use the ES6 statements let and const . You can think of var as the legacy method of doing this.

My recommendation is:

  • Use const as the default.
  • Use let if the variable will change in the future.
  • Don't use var if there is no particular use case.

JavaScript Variables and Scope

According to MDN :

The scope is the current context of execution in which values and expressions are "visible" or can be referenced.

In terms of variables, the scope is where certain variables are available. We can access variables that have been declared in a parent scope in a child scope, but it doesn't work the other way around.

Global Scope

Global Scope is the main scope that covers all the scopes in a script. Variables declared in the global scope are available in all scopes.

In the example above, we can access the grapes variable from all child scopes because it is declared in the global scope.

Functional Scope

Functional scope is the scope created with a function declaration. Variables declared in a functional scope are only available in that scope and cannot be accessed outside of it. The behavior of var , let , and const are the same in this case.

Here's an example:

In the example above, all three variables are only accessible in the functional scope of the createVariables function. If you try to access them outside of the functional scope the program throws a ReferenceError .

Block Scope

Block scope is the scope that is created with a pair of curly braces. Block scope is only valid for let and const , not var . When you declare a variable with var it is moved to the global scope or the nearest functional scope if it exists.

In the example above:

  • We can access the banana variable that we declared with const in the parent scope in the child scope.
  • We can access the carrot variable declared with var in the child scope in the parent scope because the program moves it to the global scope.
  • We can't access the lemon variable declared with let in the child scope in the parent scope because it cannot be accessed outside of the scope in which it's declared. If try to do that, the program throws a ReferenceError .

How to Mutate Variables in JavaScript

In this section, we'll talk about the var and let statements together, and then discuss how the const statement behaves. This is because the variables declared with var and let are mutable (that is, they can be changed), while variables declared with const are immutable.

1. Mutation in var and let statements

As I said, the variables declared with var and let are mutable, which means that you can assign new values to them. Here's what I mean:

In the example above, we mutated the pepper and apple variables, and they were assigned new values.

2. Mutation in const statement

Variables declared with const are immutable. So you cannot assign new values to them once you've declared them.

If you try to run the code snippet above, the program throws an error like this:

TypeError: Assignment to constant variable.

Objects are an exception for the immutability of the const statement because they have properties and methods, unlike primitives .

You cannot mutate them via assignment but can mutate them via their methods and property assignment. Here's an example:

In the code example above,

  • We added two new fruits to the fruits array via property assignment, and used the push method of the Array object.
  • We added a new fruit to the fruitEmojiMap object via property assignment.

A little note: you can use the [Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) method to achieve complete immutability for objects.

How to Redeclare Variables in JavaScript

Redeclaring a variable with the same name in the same scope is likely something you don't want to do intentionally, and I've never found a real use case for it.

But strangely, we can redeclare variables declared with var using the same name in the same scope. This is another error-prone characteristic of the var statement. Fortunately, this behavior was changed with the let and const statements.

1. How to redeclare variables with var

You can redeclare a variable declared with var in the same scope or child-parent scopes. The variable will be affected in the global scope, or functional scope if it is declared in a function.

So even if you redeclare a variable in the child scope, the variable will change in all scopes where that variable is available.

In the example above, we declared a new pepper variable in the block scope and assigned it a different value. This affects the variable in the global scope and we lose access to the previous variable.

This behavior tends to cause big problems. Because someone working in the same codebase may unintentionally declare a variable using the same name used before.

The process is a bit different if you make the redeclaration in a function. The variable outside of the function remains the same and the variable inside the function cannot affect it. As I said, variables declared with var in a function are in functional scope and don't affect the outside.

In the example above, even though we declared a new variable using the same name as the onion variable inside a function, the onion variable declared in the global scope remained the same.

2. How to redeclare variables with let and const

You cannot redeclare variables declared with let or const in the same scope. If you try to do so, the program throws a SyntaxError .

In the example above, we tried to redeclare the eggplant variable in the same scope, and the program threw the following error:

SyntaxError: Identifier 'eggplant' has already been declared

But you can redeclare variables using let and const in child scopes. Because the variables declared with let and const are block scope and don't affect the parent scopes.

In the example above, we declared two carrot variables. The first one is in the global scope and the second one is in the block scope with a different value. The variable in the global scope remains the same and the variable in the block scope is a standalone new variable.

The downside is that we lost access to the carrot variable declared in the global scope, in the block scope. If we need this variable in the future we can't access the variable.

So, most of the time, it is better to declare a variable with a unique name.

3. How to Redeclare Variables by Mixing Statements

Briefly, you shouldn't mix statements. This section is intended to give you information rather than really show you how the process is done.

You cannot create variables by mixing statements using the same name in the same scope. If you try it, the program throws a SyntaxError .

In the example above, we tried to redeclare the banana variable declared with const with var , but the program threw an error similar to the one below:

SyntaxError: Identifier 'banana' has already been declared

Also, you cannot declare a variable with var using the same name as one already declared in a parent scope using let or const . As I said, var is global scope and affects the variable declared in parent scopes unless it is inside a function.

In the example above, we tried to redeclare the pineapple variable in two places:

  • In the function, which we did successfully.
  • But in the child block scope, the program threw the following error:

SyntaxError: Identifier 'pineapple' has already been declared

These days, let and const are the default choice for variable declaration in JavaScript. But you might still encounter the var statement, especially in older apps. So you'll need to know how to handle it.

In this guide, you have learned the differences between var , let , and const . We also talked about hoisting and scope in variable declaration.

See you in the next one!

Stay in Touch

You can connect with me on Twitter , and you can read more tutorials like this one on my blog here .

Hello, I'm Furkan Emin Can. I'm a self-taught, passionate front-end developer who enjoys writing TypeScript and strives to become a better developer. In my free time, I love practicing calisthenics and enjoy reading programming blogs that help me improve my skills.

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

13 Variables and assignment

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 .

13.1  let

Variables declared via let are mutable:

You can also declare and assign at the same time:

13.2  const

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

13.2.1  const and immutability

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.

13.2.2  const and loops

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:

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

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

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

13.5 (Advanced)

All remaining sections are advanced.

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

13.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).

13.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).

13.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:

Global declarative variables are normal variables.

  • They can only be created while at the top level of a script, via const , let , and class declarations.

Global object variables are stored in properties of the so-called global object .

  • 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. Figure 13.1 illustrates how the various scopes are related.

Figure 13.1: The global scope is JavaScript’s outermost scope. It has two kinds of variables: object variables (managed via the global object ) and normal declarative variables . Each ECMAScript module has its own scope which is contained in the global scope.

13.7.1  globalThis [ES2020]

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 (script scope, not module scope).

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

13.7.1.1 Alternatives to globalThis

The following global variables let us access the global object on some platforms:

  • window : The classic way of referring to the global object. But it doesn’t work in Node.js and in Web Workers.
  • self : Available in Web Workers and browsers in general. But it isn’t supported by Node.js.
  • global : Only available in Node.js.
Main browser threadWeb WorkersNode.js

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

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

Table 13.1 summarizes how various declarations handle these aspects.

ScopeActivationDuplicatesGlobal prop.
Blockdecl. (TDZ)
Blockdecl. (TDZ)
Block (*)start
Blockdecl. (TDZ)
Modulesame as export
Functionstart, partially

Table 13.1: Aspects of declarations:

  • “Duplicates” describes if a declaration can be used twice with the same name (per scope).
  • “Global prop.” describes if a declaration adds a property to the global object, when it is executed in the global scope of a script.
  • TDZ means temporal dead zone (which is explained later).

(*) Function declarations are normally block-scoped, but function-scoped in sloppy mode .

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

13.8.1  const and let : temporal dead zone

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.

13.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 “Callable values” (§27) .

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.

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

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

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

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

13.8.4  var : hoisting (partial early activation)

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 :

13.9 Closures

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

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

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

13.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:

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

Using Global Variables in Node.js

node js variable assignment

​Hey guys, in today's article I want to talk about global variables in Node. This article is aimed at developers who are at a beginner to intermediate skill level working with Node. If you have never heard of global variables or worked with them, no need to worry. This article will get you up and running in no time with everything you need to know about global variables.

  • What are Global Variables?

Global variables are very similar, if not identical, to regular variables. Global variables can be initialized with a value, that value can be changed, and they can even be cleared out like a regular variable. The difference between a regular variable and a global variable comes down to their scope. When you create a variable in a JavaScript file, that variable only exists in the scope that it was declared in. Now what do I mean by this? In the code below, you can see an example of two different variables with different scopes.

In the code snippet above, we can see that there are two variables, fileScope and localScope . The variable fileScope can be changed or called from anywhere within this file, whereas the localScope variable only exists inside the function doSomething() . I'm sure at this point you are wondering what this has to do with global variables. When we talk about global variables, they exist for all of the files in a program meaning they have global scope for the program.

The reason this is possible is because JavaScript programs share a global namespace between all of the files in the program. To put it another way, imagine that your program is a giant file or container that has "imported" all the other JavaScript files. You then declare a variable in this large container file, that variable now has scope throughout the whole program. If you are not sure what a namespace is or you want to find out more about them, check out this article to learn more.

  • How to Declare and Use a Global Variable

Now that we have a better understanding of what a global variable in Node is, let's talk about how we actually set up and use a global variable. To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value. Next, we change the value of globalString , and then finally we set it to undefined.

What I have not talked about yet is another way that you can make a variable global. The reason I have excluded this is because it is not a proper way of setting up a variable. If you declare a variable in a file without using the keyword var and then assign a value to it, the global object will set a property for this variable. This process essentially turns it into a globally accessible variable. I strongly advise against using this method though as it is not the proper way to go about creating globals. It is also important to note that if you set the 'use strict' directive, Node will disable implicit globals and you will likely end up with an error at runtime rather than a working script.

  • Practical Use Cases for Global Variables

Now, you might be thinking to yourself that you want to go off and create global variables now that you know more about them. I am going to strongly caution against creating global variables for a few very important reasons.

The first reason is that when you create a global variable, it exists throughout the lifetime of the application. When a variable persists through the lifetime of the app it means that it is there, in memory, occupying resources while the app is running.

Second, traditionally using global variables can cause concurrency issues. If multiple threads can access the same variable and there are no access modifiers or fail-safes in place, it can lead to some serious issues of two threads attempting to access and use the same variable. However , while this is the case in other languages, it is not necessarily the case for Node.js as it is strictly a single-threaded environment. While it is possible to cluster Node processes, there is no native way to communicate between them.

The last reason I am going to talk about is that using globals can cause implicit coupling between files or variables. Coupling is not a good thing when it comes to writing great code. When writing code, we want to make sure that it is as modular and reusable as possible, while also making sure it is easy to use and understand. Coupling pieces of your code together can lead to some major headaches down the road when you are trying to debug why something isn't working.

If you want to know more about why globals are not recommended, you can check out this great article called Global Variables Are Bad .

If you feel confused as to the purpose of global variables, fear not. We are going to take a look at a few of the global variables that are built into Node and try to get a better understanding of why they are global and how they are used. In fact, you have probably used a few of them already without even realizing that they are global objects!

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If you take a look at the above code block you will probably see at least one instance you have used before, console.log() . According to the Node documentation, the console object is a global that has a few methods allowing developers to do things such as printing a log or an error. Digging deeper into the docs we can see that console is really a global instance that is configured to write to process.stdout and process.stderr .

This brings us to the next statement that you see in the code block above, the process object. If you have put up a production build of a Node application, then you have likely had to set the port for the environment variable. The environment variable env is a part of the process object which is another global. You can access variables on the process object in any file in your project because it is global. If this object was not global, the console object would not be accessible from any file either, remember it is really an object that refers back to the process object.

​ setInterval is another function that you may have seen before if you ever had reason to delay an operation before executing it. setTimeout and setImmediate are similar in nature to setInterval and are both global functions as well. These three functions are a part of the timer module which exposes a global API allowing you to call these functions without requiring a timer in your files explicitly.

​All of the above mentioned use cases are built into Node and are global for a reason. The process object is global because it provides information about the current running Node process and therefore should be available from any file without having to require it. The same can be said of the timer module which contains a number of functions that are important and should be accessible anywhere without having to require it. If you would like to learn more about the existing global objects built into Node, I encourage you to visit the official documentation on Globals .

​I know that was quite a bit of information, so thank you for sticking it out. All of the above information was found in the documentation on Node's website . Please feel free to ask questions and give comments in the comment section below. Until next time guys!

You might also like...

  • Node.js Websocket Examples with Socket.io
  • Neural Networks in JavaScript with Brain.js
  • Simplify Regular Expressions with RegExpBuilderJS
  • Message Queueing in Node.js with AWS SQS

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Sam is an iOS developer who loves working with Swift and is currently doing freelance iOS work. When not coding, he can be found playing video games on Steam or writing articles.

In this article

node js variable assignment

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

Vendor Alerts with Ping Bot

Get detailed incident alerts about the status of your favorite vendors. Don't learn about downtime from your customers, be the first to know with Ping Bot.

Supabase

© 2013- 2024 Stack Abuse. All rights reserved.

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

Dianne Pena

Node.js Environment Variables: How to Set Them Properly

Share this article

Node.js Environment Variables: How to Set Them Properly

Understanding Environment Variables in Node.js

Accessing environment variables in node.js, setting environment variables in node.js, working with .env files, managing default and required environment variables, best practices for environment variables in node.js.

Ever struggled with managing different configurations in your Node.js applications? Ever wanted a centralized and organized way to handle secrets like API keys and database credentials? Look no further! Environment variables are here to save the day. In this article, we’ll dive into the world of environment variables in Node.js, exploring their benefits, use cases, and best practices for managing them effectively.

We’ll guide you through setting up, accessing, and organizing environment variables, as well as using them across different environments and integrating them into npm scripts. By the end of this post, you’ll have a solid understanding of how environment variables can make your life as a Node.js developer easier.

What are environment variables?

Why use environment variables in node.js, common use cases for environment variables, the process.env object, reading an environment variable, handling non-string types, setting environment variables within a script, setting environment variables from the command line, why use .env files, installing and configuring the dotenv package, loading custom environment variables from .env files, setting default values for environment variables, handling required environment variables without default values, avoiding hardcoding values, keeping sensitive data secure, organizing environment variables in a config module.

Environment variables in Node.js serve as a source of configuration and secrets, allowing for easier debugging and maintenance of your applications. By externalizing app-specific settings, environment variables provide a single source of truth, making it simple to:

  • run your application on different machines or environments without having to modify the code itself
  • keep sensitive information, such as API keys or database credentials, separate from your code
  • customize the behavior of your application based on the environment it’s running in

Using environment variables can greatly improve the flexibility and security of your Node.js applications.

Environment variables are named values that can be used to configure applications and processes, allowing for easy customization and portability. In the context of Node.js, environment variables provide a way to store and manage configurations, such as API keys, database credentials, and other settings, outside of your code.

Accessing these variables throughout your application code becomes straightforward with the process.env property, allowing you to tailor your app’s functioning according to various environments.

Using environment variables in Node.js offers several advantages, including:

  • improved security, by storing sensitive information outside of the codebase
  • adaptability in configuring the application for various environments
  • scalability in managing configuration settings
  • easier collaboration with other developers or teams

Storing your configuration settings in environment variables lets you operate your application universally, eliminating the need to alter the code or rebuild it. This enhances the application’s encapsulation and maintainability.

Environment variables are extremely versatile and can be used in a variety of scenarios. Some common use cases include configuring API keys, database credentials, and adjusting application behavior based on all the environment variables.

Environment-specific behavior can be particularly useful, allowing you to activate or deactivate certain features or adapt your application’s behavior according to the environment it’s running in, such as development, testing, or production.

Accessing environment variables in Node.js is simple and straightforward, thanks to the process.env object. This global object contains key–value pairs of environment variables, with the values stored as strings.

The process.env object is a global object that holds all environment variables as key–value pairs, with values stored as strings. When the Node.js process starts, it reads the environment variables set by the parent process or the operating system and stores them in the process.env object. This makes it easy to access and use these variables throughout your application code.

To read an environment variable in Node.js, simply access the corresponding property on the process.env object. For example, suppose you have an environment variable named MY_VARIABLE . In that case, you can access its value using process.env.MY_VARIABLE . Keep in mind that the values read from environment variables are always strings, so if you need a different type, you’ll have to convert the value to the appropriate type.

Since environment variables are stored as strings, you might need to parse or convert them to their intended data type. For example, you can use JSON.parse for objects or parseInt for numbers. Appropriate management of non-string types ensures your application functions as intended, preventing potential problems related to data type inconsistencies.

Setting environment variables in Node.js can be done within a script or from the command line, allowing for easy customization and configuration of your application. We’ll delve into both methods in this section and provide examples to help you commence.

To set an environment variable within a Node.js script, you can assign a value to a property on the process.env object. For example, if you want to set an environment variable named MY_VARIABLE with the value my_value , you can use the syntax process.env.MY_VARIABLE = 'my_value' . This facilitates effortless tailoring of your application’s behavior and configurations right within your code.

Another way to set environment variables in Node.js is from the command line. On Linux and macOS, you can use the export command, while on Windows, you can use the set command.

For example, to set the MY_VARIABLE environment variable to my_value , you can run export MY_VARIABLE='my_value' on Linux and macOS or set MY_VARIABLE=my_value on Windows. This approach allows you to set environment variables before running your Node.js script, making it easy to customize your application’s behavior and configurations.

Managing environment variables directly within your code or from the command line can become cumbersome, especially for large applications with numerous variables. That’s where .env files come into play. In this section, we’ll explore the advantages of using .env files, the procedure for installing and setting up the dotenv package, and the method for loading custom environment variables from .env files into your Node.js application.

.env files provide a convenient way to store and manage environment variables for your Node.js application, keeping them organized and easily accessible. By storing environment variables in a .env file, you can keep your application’s configuration settings and sensitive information, such as API keys and database credentials, separate from your codebase. This helps keep your code clean and maintainable while ensuring sensitive data is not accidentally exposed to the public.

To load environment variables from a .env file, you’ll need to install and configure the dotenv package. The dotenv package is an npm package that enables you to read environment variables from a .env file into your Node.js app.

To install the dotenv package, run npm install dotenv in your project directory. Then, create a .env file in the root directory of your application and add your environment variables, one per line.

Once you’ve installed and configured the dotenv package, you can load custom environment variables from your .env file into your Node.js application. The dotenv package provides a config() function that reads the environment variables from your .env file and makes them available in your application through the process.env object.

This enables smooth access to, and utilization of, custom environment variables throughout your application, easing configuration management and enhancing the maintainability of your code by using process global variable.

In some cases, you might want to set default values for certain environment variables or ensure that specific variables are set before your application runs. In this section, we’ll discuss how to manage default and required environment variables in Node.js, including setting default values and handling cases where required variables are missing.

Setting default values for environment variables can be done using the OR operator, like so: process.env.MY_VARIABLE || 'default_value' . However, be cautious when using default values, as they can lead to unexpected behavior and make debugging more difficult.

If your application relies on a specific configuration, it’s generally better to ensure that the environment variables are properly set before running your application.

For required environment variables without default values, you can use methods like assert.ok() or similar to ensure they’re properly set before continuing your application’s execution. Managing instances where required environment variables are absent helps prevent errors and guarantees the correct functioning of your application, even if certain variables aren’t supplied.

Now that we’ve covered the ins and outs of environment variables in Node.js, it’s essential to follow best practices to ensure your application is secure, maintainable, and efficient.

This section, we’ll outline some of the optimal practices for managing environment variables in Node.js, including strategies to avoid hardcoding values, maintaining the security of sensitive data, and arranging variables in a config module.

Hardcoding values in your Node.js application can lead to difficulties in managing and maintaining your code. By using environment variables to store and manage configurations and settings, you can keep your code clean, maintainable, and easily adjustable for different environments and use cases. This helps ensure your application is easy to update, debug, and deploy, making your development process more efficient and effective.

Sensitive data, such as API keys and database credentials, should be stored in environment variables to keep them secure and separate from your codebase. This ensures that sensitive data isn’t accidentally exposed through your source code or version control system, helping to protect your application and user data from unauthorized access.

By organizing your environment variables in a config module, you can make them easily accessible and maintainable throughout your Node.js application. This allows you to centralize your application’s configuration settings, making it easier to update and manage them as your application evolves.

Additionally, a config module can help ensure that your environment variables are used consistently across your application, reducing the risk of configuration errors and making your code more maintainable.

In this article, we’ve explored the world of environment variables in Node.js, covering their benefits, use cases, and best practices for managing them effectively. We’ve seen how environment variables can help improve the security, maintainability, and flexibility of your Node.js applications, making it easier to run your app in different environments without having to modify the code itself.

As you continue your journey with Node.js, remember the importance of managing your application configurations and settings using environment variables. By following the best practices outlined above, you’ll be well on your way to building secure, maintainable, and efficient Node.js applications that can be easily deployed and run in a variety of environments.

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

SitePoint Premium

How to read environment variables from Node.js

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.

The below code runs app.js and set USER_ID and USER_KEY .

That will pass the user USER_ID as 239482 and the USER_KEY as foobar . This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

Note: process does not require a "require", it's automatically available.

Here is an example that accesses the USER_ID and USER_KEY environment variables, which we set in above code.

In the same way you can access any custom environment variable you set.

Node.js 20 introduced experimental support for .env files .

Now, you can use the --env-file flag to specify an environment file when running your Node.js application. Here's an example .env file and how to access its variables using process.env .

In your js file

Run app.js file with environment variables set in .env file.

This command loads all the environment variables from the .env file, making them available to the application on process.env

Also, you can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files.

Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Storing the information you need — Variables

  • Overview: JavaScript first steps

After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.

Prerequisites: A basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective: To gain familiarity with the basics of JavaScript variables.

Tools you need

Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see What are browser developer tools for more information on how to access this tool).

What is a variable?

A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.

Variable example

Let's look at an example:

In this example pressing the button runs some code. First, it changes the text on the button itself. Second, it shows a message of the number of times the button has been pressed. The number is stored in a variable. Each time the user presses the button, the number in the variable will increment by one.

Without a variable

To understand why this is so useful, let's think about how we'd write this example without using a variable to store the count. It would end up looking something like this:

You may not fully understand the syntax we are using (yet!), but you should be able to get the idea. Without a variable, we don't have a way of knowing how many times the button have been clicked. The message to the user will quickly be irrelevant when no information can be remembered.

Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

One special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.

A screenshot of three 3-dimensional cardboard boxes demonstrating examples of JavaScript variables. Each box contains hypothetical values that represent various JavaScript data types. The sample values are "Bob", true and 35 respectively.

Declaring a variable

To use a variable, you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword let followed by the name you want to call your variable:

Here we're creating two variables called myName and myAge . Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.

Note: In JavaScript, all code instructions should end with a semicolon ( ; ) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message — try typing in

Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there is a box, but it has no value inside it.

Initializing a variable

Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign ( = ), followed by the value you want to give it. For example:

Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console — try these again:

You can declare and initialize a variable at the same time, like this:

This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.

A note about var

You'll probably also see a different way to declare variables, using the var keyword:

Back when JavaScript was first created, this was the only way to declare variables. The design of var is confusing and error-prone. So let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var , fixing its issues in the process.

A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our let reference page ).

For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:

Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.

This works because of hoisting — read var hoisting for more detail on the subject.

Hoisting no longer works with let . If we changed var to let in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it results in confusing, harder to understand code.

Secondly, when you use var , you can declare the same variable as many times as you like, but with let you can't. The following would work:

But the following would throw an error on the second line:

You'd have to do this instead:

Again, this is a sensible language decision. There is no reason to redeclare variables — it just makes things more confusing.

For these reasons and more, we recommend that you use let in your code, rather than var . Unless you are explicitly writing support for ancient browsers, there is no longer any reason to use var as all modern browsers have supported let since 2015.

Note: If you are trying this code in your browser's console, prefer to copy & paste each of the code blocks here as a whole. There's a feature in Chrome's console where variable re-declarations with let and const are allowed:

Updating a variable

Once a variable has been initialized with a value, you can change (or update) that value by giving it a different value. Try entering the following lines into your console:

An aside on variable naming rules

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

  • You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
  • Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.
  • Don't use numbers at the start of variables. This isn't allowed and causes an error.
  • A safe convention to stick to is lower camel case , where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
  • Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
  • Variables are case sensitive — so myage is a different variable from myAge .
  • One last point: you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like var , function , let , and for as variable names. Browsers recognize them as different code items, and so you'll get errors.

Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar — keywords .

Good name examples:

Bad name examples:

Try creating a few more variables now, with the above guidance in mind.

Variable types

There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.

You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:

Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.

Booleans are true/false values — they can have two values, true or false . These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

Whereas in reality it would be used more like this:

This is using the "less than" operator ( < ) to test whether 6 is less than 3. As you might expect, it returns false , because 6 is not less than 3! You will learn a lot more about such operators later on in the course.

An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

Once these arrays are defined, you can access each value by their location within the array. Try these lines:

The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.

To learn more, see our article on Arrays .

In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

Try entering the following line into your console:

To retrieve the information stored in the object, you can use the following syntax:

For more on this topic, see the Introducing JavaScript objects module.

Dynamic typing

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).

For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:

Even if the value enclosed in quotes is just digits, it is still a string — not a number — so be careful:

Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof — this returns the data type of the variable you type after it. The first time it is called, it should return string , as at that point the myNumber variable contains a string, '500' . Have a look and see what it returns the second time you call it.

Constants in JavaScript

As well as variables, you can declare constants. These are like variables, except that:

  • you must initialize them when you declare them
  • you can't assign them a new value after you've initialized them.

For example, using let you can declare a variable without initializing it:

If you try to do this using const you will see an error:

Similarly, with let you can initialize a variable, and then assign it a new value (this is also called reassigning the variable):

Note that although a constant in JavaScript must always name the same value, you can change the content of the value that it names. This isn't a useful distinction for simple types like numbers or booleans, but consider an object:

You can update, add, or remove properties of an object declared using const , because even though the content of the object has changed, the constant is still pointing to the same object:

When to use const and when to use let

If you can't do as much with const as you can with let , why would you prefer to use it rather than let ? In fact const is very useful. If you use const to name a value, it tells anyone looking at your code that this name will never be assigned to a different value. Any time they see this name, they will know what it refers to.

In this course, we adopt the following principle about when to use let and when to use const :

Use const when you can, and use let when you have to.

This means that if you can initialize a variable when you declare it, and don't need to reassign it later, make it a constant.

Test your skills!

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: variables .

By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Is variable assignment synchronous in nodejs?

Say we have

How do we know it won't print an undefined variable z?

  • If it is asynchronous, is there a function used to assign values to variables with a callback so we can be certain of their values when using them.
  • If it is synchronous, then when loading modules like

Wouldn't that be pretty slow when you load a few of them in one script?

SirKaliKook's user avatar

  • 1 Possible duplicate of Are JavaScript functions asynchronous? . This thread should clear up any questions you have. –  Robert Moskal Commented May 11, 2016 at 1:30
  • So nodejs is just normal javascript? I thought the entire point was that it is executed asynchronously. That still doesn't answer my question of whether it is slow to load multiple requires in one script. –  SirKaliKook Commented May 11, 2016 at 1:49
  • ruben.verborgh.org/blog/2012/08/13/… –  jack blank Commented May 11, 2016 at 1:58
  • when you load modules with require most of the time it is not over the network (The files are on the server) so it wont be a long time. You might be thinking about requesting over the network which has latency. –  jack blank Commented May 11, 2016 at 2:06

Yes, it is.

Actually, any sequence of statements is executed synchronously.

You may be getting confused with the following type of situation:

Here, LongRunningAsyncTask cannot return its result, since it is not yet known. Therefore, x probably won't be what you want, which is why, assuming LongRunningAsyncTask is implemented in callback style, you need to write

or if LongRunningAsyncTask returns a promise, then

or using async functions:

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged node.js or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Is there anything that stops the majority shareholder(s) from destroying company value?
  • Miracle Miracle Octad Generator Generator
  • Which translation of Psalm 113:9 is closest to the original?
  • Idiomatic alternative to “going to Canossa”
  • Matrix with \guilsinglright, \guilsinglleft and \textlquill, \textrquill
  • Visualizing histogram of data on unit circle?
  • Chord definition misunderstanding
  • Why do combinatorists care about Kazhdan–Lusztig polynomials?
  • Would it take less thrust overall to put an object into higher orbit?
  • Op Amp Feedback Resistors
  • Does my AC vent air from the room to outside?
  • Can I use rear (thru) axle with crack for a few rides, before getting a new one?
  • Do mini-humans need a "real" Saturn V to reach the moon?
  • How can I push back on my co-worker's changes that I disagree with?
  • Version of Dracula (Bram Stoker)
  • How do I do calculations with a sliding window while being memory-efficient?
  • Do cities usually form at the mouth of rivers or closer to the headwaters?
  • One IO to control two LEDs. When one is lit, the other is not
  • Short story in which the protagonist shrinks to the size of his model train set and is run over by one of his trains
  • How to extract code into library allowing changes without workflow overhead
  • If physics can be reduced to mathematics (and thus to logic), does this mean that (physical) causation is ultimately reducible to implication?
  • Are there any original heat shield tiles on any of the retired space shuttles that flew to space?
  • "Knocking it out of the park" sports metaphor American English vs British English?
  • Multi Wire Branch Circuit for Kitchen Small Appliances Circuit, AFCI and GFCI required

node js variable assignment

IMAGES

  1. Using Environment Variables in Node.js for App Configuration and

    node js variable assignment

  2. Setup environment variables with Node.js + Dotenv Tutorial

    node js variable assignment

  3. Node js environment variables windows

    node js variable assignment

  4. Node.js Global Variable

    node js variable assignment

  5. NodeJS : Using Variable In JSON node.js

    node js variable assignment

  6. Node.js REPL (READ, EVAL, PRINT, LOOP)

    node js variable assignment

COMMENTS

  1. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

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

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

  4. var

    In both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not added as properties to the global object. The list that follows the var keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment ...

  5. How to Declare Variables in JavaScript

    This is because the variables declared with var and let are mutable (that is, they can be changed), while variables declared with const are immutable. 1. Mutation in var and let statements. As I said, the variables declared with var and let are mutable, which means that you can assign new values to them. Here's what I mean:

  6. Variables and assignment

    The following global variables let us access the global object on some platforms: window: The classic way of referring to the global object. But it doesn't work in Node.js and in Web Workers. self: Available in Web Workers and browsers in general. But it isn't supported by Node.js. global: Only available in Node.js.

  7. Using Global Variables in Node.js

    To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.

  8. Variable Scope in Modern JavaScript

    If you are using NodeJS then the top-level scope is not the same as the global scope. If you use var foobar in a NodeJS module it is local to that module. To define a global variable in NodeJS we need to use the global namespace object, global. global.foobar = 'Hello World!'; // This is a global variable in NodeJS

  9. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...

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

  11. JavaScript Assignment

    Create your own server using Python, PHP, React.js, Node.js, Java, C#, etc. How To's. Large collection of code snippets for HTML, CSS and JavaScript. CSS Framework. Build fast and responsive sites using our free W3.CSS framework ... The Exponentiation Assignment Operator raises a variable to the power of the operand.

  12. 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). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs.

  13. Node.js

    Node.js ... Redirecting...

  14. Node.js variable declaration and scope

    5. As mentioned in the document. var something inside an Node.js module will be local to that module. So, it is going to be different as the var testContext is in module context and the context of this is global. You can alternatively, use: global.testContext = 15; function testFunction() {. console.log(this.testContext);

  15. Logical OR assignment (||=)

    x ||= y. Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x ...

  16. Node.js Environment Variables: How to Set Them Properly

    Setting environment variables within a script. To set an environment variable within a Node.js script, you can assign a value to a property on the process.env object. For example, if you want to ...

  17. Node.js

    How to read environment variables from Node.js. The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started. The below code runs app.js and set USER_ID and USER_KEY. That will pass the user USER_ID as 239482 and the USER_KEY as foobar.

  18. node.js

    Assignment to constant variable. Ask Question Asked 5 years, 8 months ago. Modified 4 months ago. Viewed 96k times 11 I try to read the user input and send it as a email. But when I run this code it gives me this error: Assignment to constant variable. ... node.js; nodemailer; or ask your own question. The Overflow Blog Battling ticket bots and ...

  19. Storing the information you need

    Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof — this returns the data type of the variable you type after it. The first time it is called, it should return string, as at that point the myNumber variable contains a string, '500'.Have a look and see what it returns the second time ...

  20. How to manage environment variables in Node.js

    You can also set environment variables directly from the command line when you run your Node.js application. For example, you can use the set keyword on Windows or the export keyword on Linux or Mac to set a variable, like this: export NODE_ENV=production. Then, you can run your Node.js application with the variable set, like this: node app.js.

  21. Is variable assignment synchronous in nodejs?

    9. Is variable assignment synchronous in nodejs? Yes, it is. Actually, any sequence of statements is executed synchronously. You may be getting confused with the following type of situation: var x = LongRunningAsyncTask(); console.log(x); Here, LongRunningAsyncTask cannot return its result, since it is not yet known.