• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

The Essential Skills and Qualities to Look for When Hiring React JS Developers

React JS has become one of the most popular JavaScript libraries for building user interfaces. Its flexibility, reusability, and efficiency have made it a go-to choice for many companies looking to develop robust web applications. As the demand for React JS developers continues to rise, it is crucial for businesses to know what skills and qualities to look for when hiring these professionals. In this article, we will discuss the essential skills and qualities that make a great React JS developer.

Strong Proficiency in JavaScript

When searching for a React JS developer, proficiency in JavaScript is a must-have skill. Since React JS is built on top of JavaScript, a deep understanding of the language is essential. A skilled developer should be well-versed in core JavaScript concepts such as variables, functions, arrays, objects, and control flow. They should also have knowledge of modern JavaScript features like arrow functions, destructuring assignment, promises, and async/await.

Experience with React Ecosystem

While having a solid foundation in JavaScript is important, familiarity with the React ecosystem is equally crucial. A competent React JS developer should have hands-on experience with various tools and libraries such as Redux (for state management), Next.js (for server-side rendering), and Jest (for testing). Understanding how these components work together within the React ecosystem will enable developers to create scalable and efficient applications.

Problem-Solving Skills

Another essential quality to look for when hiring a React JS developer is strong problem-solving skills. Developing complex web applications often involves encountering challenges along the way. A skilled developer should possess the ability to identify problems quickly and come up with effective solutions. They should be able to think critically and troubleshoot issues efficiently using debugging tools or by leveraging their knowledge of coding best practices.

Collaboration and Communication

While technical skills are crucial in any development role, collaboration and communication skills are equally important. A great React JS developer should be able to work effectively in a team environment, collaborating with designers, project managers, and other developers. Clear and concise communication is essential for understanding project requirements, discussing ideas, and providing progress updates. A developer who can effectively communicate technical concepts to non-technical stakeholders is an asset to any organization.

In conclusion, hiring a skilled React JS developer requires looking for a combination of technical skills and personal qualities. Proficiency in JavaScript, experience with the React ecosystem, strong problem-solving abilities, and effective collaboration and communication skills are all essential traits to seek out when hiring for this role. By finding developers who possess these skills and qualities, businesses can ensure the successful development of their React JS projects.

This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability.

MORE FROM ASK.COM

variable assignment js

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

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.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

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

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.

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Get full access to JavaScript: The Definitive Guide, 6th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Assignment Expressions

JavaScript uses the = operator to assign a value to a variable or property. For example:

The = operator expects its left-side operand to be an lvalue: a variable or object property (or array element). It expects its right-side operand to be an arbitrary value of any type. The value of an assignment expression is the value of the right-side operand. As a side effect, the = operator assigns the value on the right to the variable or property on the left so that future references to the variable or property evaluate to the value.

Although assignment expressions are usually quite simple, you may sometimes see the value of an assignment expression used as part of a larger expression. For example, you can assign and test a value in the same expression with code like this:

If you do this, be sure you are clear on the difference between the = and == operators! Note that = has very low precedence and parentheses are usually necessary when the value of an assignment is to be used in a larger expression.

The assignment operator has right-to-left associativity, which means that when multiple assignment operators appear in an expression, they are evaluated from right to left. Thus, you can write code like this to assign a single value to multiple variables:

Assignment with Operation

Besides the normal = assignment operator, JavaScript supports a number of other assignment operators that provide shortcuts by combining assignment with some other operation. For example, the += operator performs addition and assignment. The following expression:

is equivalent to this one:

As you might expect, the += operator works for numbers or strings. For numeric operands, it performs addition and assignment; for string operands, it performs concatenation and assignment.

Similar operators include -= , *= , &= , and so on. Table 4-3 lists them all.

Table 4-3. Assignment operators

In most cases, the expression:

where op is an operator, is equivalent to the expression:

In the first line, the expression a is evaluated once. In the second it is evaluated twice. The two cases will differ only if a includes side effects such as a function call or an increment operator. The following two assignments, for example, are not the same:

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

variable assignment js

  • Javascript Fundamentals

variable assignment js

In this lesson, we will discuss basic elements in programming, with a focus on the following key points:

  • What are variables and the assignment of variables in a programming language?
  • Working with variables and assignment of variables in JavaScript.

This lesson is intended for web and frontend engineers. For the general purpose version of this lesson, please click here .

During any real-life work, we need to store a piece of information somewhere and refer to it later. We encounter these situations while creating a program and doing computation as well, where we often need to store some information or data temporarily somewhere. For this specific purpose, variables are used. These variables can store almost any type of data, whether they are numbers, strings, or lists. Data is stored in variables by assigning data values to them. This lesson will expand on this topic and discuss in detail variables and their assignment.

As discussed above, variables can store and manipulate data. Data values can be assigned to a variable by using the assignment operator which is the equal sign (=). Once a value is assigned to the variable, it corresponds to that value unless it is reassigned. Suppose we assign a value 5 to a variable a . This concept can be visualized as below.

Variables

This ensures that whenever we use the variable a in our program, we will get a value of 5. Let's understand this with code examples in JavaScript.

Variables in JavaScript

Variables in JavaScript are commonly declared by using a var keyword, followed by a variable name, assignment operator (equals sign = ), and a corresponding value. For example, a variable of type int is declared as follows.

Since this code line was a statement, it will produce no output. It only created the variable number in memory and assigned it the value 10 . To check if the value was stored in the variable number , we use console.log() , which displays the variable value on the console.

This will display the value 10 , and we can see that the value was correctly assigned.

Note! We can declare variables in JavaScript without using the var keyword before the variable name as well. However, in that case, the variable, regardless of where you define it, will become a global variable .

Interesting! Let's explore further.

A global variable means that they can be accessed anywhere in the program-- that is, they can also be modified anywhere in the program (inside functions and classes, which we'll learn about in the next lessons). This may lead to a change in the value of the variable in places where you don't want to change it. Hence, to ensure that this does not happen, JavaScript provides additional keywords to declare variables. Since var keyword is more prone to errors, there are two other keywords let and const that can also be used for variable declaration.

Const and Let

The problem with just using var is that this is valid:

This example is easy to understand, but imagine a huge codebase with several thousand line files. If firstTime is declared on line 1, and then redeclared on line 1800, it can be easy to miss.

let and const are block-scoped. A block is simply a chunk of code wrapped by curly braces { and } . This means that any variables declared using either let or const are only available for use within the { and } symbols.

Important Rules while Creating Variables

Programming languages understand instructions only if they are given in a specified format (or syntax). When creating variables, we need to be careful of these rules, or the variables will not be created properly, and the program may give errors.

  • Variable names can be created using alphabetical letters (a-z and A-Z), digits (0-9), or underscore symbol (_). Special symbols are not allowed. For example, abc&def is an invalid variable name.
  • Variable names can begin with the underscore symbol or alphabetical letters only, not digits. For example, 123abc is an invalid variable name and will give you an error.
  • Variables in JavaScript are case-sensitive . This means that if we declare two variables score and Score with different values assigned to them, then they are two different variables (not the same variable!).
  • Every programming language has certain keywords , that define in-built functionality in the language. These should not be used as variable names. Since it has a different meaning in the language, declaring variables with already existing keyword names will cause an error. These keywords will be highlighted with a different color whenever you type them, so it is easy for you to distinguish. For example, new is a keyword in JavaScript, hence declaring a variable with that name would raise an error.
  • Be careful about the assignment of values to variables! JavaScript allows creating variables without assigning them values. However, if that same variable is used somewhere in the program without being assigned a value, it may lead to undefined behavior.

Now that we know how to create variables, let's see if we understood them properly.

Let's test your knowledge. Is this statement true or false?

Is the following code snippet a valid way to declare a variable in JavaScript?

Press true if you believe the statement is correct, or false otherwise.

Build your intuition. Is this statement true or false?

Is _name a valid variable name?

Reassigning variables

Values can be reassigned to variables in JavaScript (except const variables, which we will discuss later). When variables are reassigned, their value changes to that of the newer value specified, and the previous value is lost.

Reassignment of Variables

Let's look at an example.

Variables can be reassigned in JavaScript by assigning a new value to the variable without using the var keyword.

Initially, when creating the variable we used the var keyword, but when reassigning there is no need to use the keyword again. We only provide a different value than what was stored before. The value of a is reassigned from 10 to 34 .

Operations on Variables

Using variables in the program makes it easy for us to perform various operations on data. Different types of variables support different types of operations. For simplicity, let's consider the type integer. On this type of variable, all mathematical operations are valid.

Let's consider a code example.

This code block shows that if we have two integer variables, we can add them and get the result. Similarly, other mathematical operations such as subtraction, multiplication, and division are also supported.

Now let's consider if we had a variable of type string. In this case, the operations are defined differently. Here, a + symbol between two variables will join the two strings together. Consider the following example.

Here, the two strings are joined together to produce a new string. This operation is called concatenation . There are several other operations that we can perform on strings, integers, and other types of variables, but we will discuss them in later lessons.

Time for some practice questions!

Try this exercise. Fill in the missing part by typing it in.

What will be the final value of variable a below?

Write the missing line below.

Build your intuition. Click the correct answer from the options.

What will the following program output?

Click the option that best answers the question.

  • Will give an error

In this lesson, we talked about a basic concept in programming, about the creation of variables and assigning values to them. A useful tip for creating variables is to use meaningful names while creating them. If you have a lot of variables in your program and you don't name them properly, there is a high chance that you'll get confused about which variables were supposed to store what value!

One Pager Cheat Sheet

  • This lesson explains how to use variables and their assignment to store data in a programming language.
  • A variable a can be assigned a data value using the assignment operator equal sign (=), and for the duration of the program, it will correspond to that value unless reassigned .
  • Variables in JavaScript can be declared with the var keyword, and stored in memory with a value which can be displayed with console.log() . Additionally, let and const are also used to declare variables in order to avoid global variable modification.
  • Using let and const instead of var is a good way to prevent confusing variables in larger codebases because they are block-scoped and can only be used within specific { and } symbols.
  • Carefully following rules such as variable names only containing alphabetical letters, digits or underscore symbols, being aware of case-sensitivity and not using language-specific keywords will help to create variables correctly and avoid errors.
  • No, this code snippet is not valid for declaring a variable in JavaScript, as the syntax var <variable name> (for example, var myVariable ) is not followed.
  • No valid JavaScript variable name can contain characters, so var words: "Hello World!" is invalid, whereas _name is valid.
  • Variables can be reassigned in JavaScript by assigning a new value without using var , resulting in the change of their value .
  • Different types of variables can be used to perform different kinds of operations, such as mathematical operations for numbers and concatenation for strings.
  • The value of a has been changed from "Hello" to "World".
  • The code concatenates the strings stored in firstName and lastName in to a new variable name , which is then console.log ged to output AnnaGreen .
  • Creating variables with meaningful names is an important step in the programming process to avoid confusion of which variables is used to store what value.

Programming Categories

  • Basic Arrays Interview Questions
  • Binary Search Trees Interview Questions
  • Dynamic Programming Interview Questions
  • Easy Strings Interview Questions
  • Frontend Interview Questions
  • Graphs Interview Questions
  • Hard Arrays Interview Questions
  • Hard Strings Interview Questions
  • Hash Maps Interview Questions
  • Linked Lists Interview Questions
  • Medium Arrays Interview Questions
  • Queues Interview Questions
  • Recursion Interview Questions
  • Sorting Interview Questions
  • Stacks Interview Questions
  • Systems Design Interview Questions
  • Trees Interview Questions

Popular Lessons

  • All Courses, Lessons, and Challenges
  • Data Structures Cheat Sheet
  • Free Coding Videos
  • Bit Manipulation Interview Questions
  • Javascript Interview Questions
  • Python Interview Questions
  • Java Interview Questions
  • SQL Interview Questions
  • QA and Testing Interview Questions
  • Data Engineering Interview Questions
  • Data Science Interview Questions
  • Blockchain Interview Questions
  • Object-Oriented Design Principles
  • Linux Bash Commands Cheat Sheet
  • What are the Highest Paid Tech Jobs?
  • Matrix Chain Multiplication
  • Technical Recruiting: How to Work With Recruiters

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 .

Guru99

JavaScript Variable: Declare, Assign a Value with Example

James Hartman

Variables are used to store values (name = “John”) or expressions (sum = x + y).

Declare Variables in JavaScript

Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable like this:

Assign a Value to the Variable

You can assign a value to the variable either while declaring the variable or after declaring the variable.

Naming Variables

Though you can name the variables as you like, it is a good programming practice to give descriptive and meaningful names to the variables. Moreover, variable names should start with a letter and they are case sensitive. Hence the variables student name and studentName are different because the letter n in a name is different (n and N).

Try this yourself:

  • TypeScript Tutorial: What is, Interface, Enum, Array with Example
  • Difference Between =, ==, and === in JavaScript [Examples]
  • 13 BEST JavaScript Books for Beginners (2023 Update)
  • 19 Best FREE JavaScript IDE & Editor (2023 Update)
  • JavaScript String Format: Methods with EXAMPLES

JavaScript Variables

Variable means anything that can vary. In JavaScript, a variable stores data that can be changed later on.

Declare a Variable

In JavaScript, a variable can be declared using var , let , const keywords.

  • var keyword is used to declare variables since JavaScript was created. It is confusing and error-prone when using variables declared using var .
  • let keyword removes the confusion and error of var . It is the new and recommended way of declaring variables in JavaScript.
  • const keyword is used to declare a constant variable that cannot be changed once assigned a value.

Here, we will use the let keyword to declare variables. To declare a variable, write the keyword let followed by the name of the variable you want to give, as shown below.

In the above example, var msg; is a variable declaration. It does not have any value yet. The default value of variables that do not have any value is undefined .

You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.

In the above example, the msg variable is declared first and then assigned a string value in the next line.

You can declare a variable and assign a value to it in the same line. Values can be of any datatype such as string , numeric , boolean , etc.

Multiple variables can be declared in a single line, as shown below.

You can copy the value of one variable to another variable, as shown below.

JavaScript allows multiple white spaces and line breaks when you declare a variables.

Variable names are case-sensitive in JavaScript. You cannot declare a duplicate variable using the let keyword with the same name and case. JavaScript will throw a syntax error. Although, variables can have the same name if declared with the var keyword (this is why it is recommended to use let ).

JavaScript Variable Nameing Conventions

  • Variable names are case-sensitive in JavaScript. So, the variable names msg , MSG , Msg , mSg are considered separate variables.
  • Variable names can contain letters, digits, or the symbols $ and _.
  • A variable name cannot start with a digit 0-9.
  • A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.

Dynamic Typing

JavaScript is a loosely typed language. It means that you don't need to specify what data type a variable will contain. You can update the value of any type after initialization. It is also called dynamic typing.

Constant Variables in JavaScript

Use const keyword to declare a constant variable in JavaScript.

  • Constant variables must be declared and initialized at the same time.
  • The value of the constant variables can't be changed after initialized them.

The value of a constant variable cannot be changed but the content of the value can be changed. For example, if an object is assigned to a const variable then the underlying value of an object can be changed.

It is best practice to give constant variable names in capital letters to separate them from other non-constant variables.

Variable Scope

In JavaScript, a variable can be declared either in the global scope or the local scope.

Global Variables

Variables declared out of any function are called global variables. They can be accessed anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables of that function. They can only be accessed in the function where they are declared but not outside.

The following example includes global and local variables.

Learn global and local scope in JavaScript for more information.

Declare Variables without var and let Keywords

Variables can be declared and initialized without the var or let keywords. However, a value must be assigned to a variable declared without the var keyword.

The variables declared without the var keyword become global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.

It is Recommended to declare variable using the let keyword.

variable assignment js

  • Variables can be defined using let keyword. Variables defined without let or var keyword become global variables.
  • Variables should be initialized before accessing it. Unassigned variable has value undefined .
  • JavaScript is a loosely-typed language, so a variable can store any type value.
  • Variables can have local or global scope. Local variables cannot be accessed out of the function where they are declared, whereas the global variables can be accessed from anywhere.

A real-life analogy

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it.

For instance, the variable message can be imagined as a box labeled "message" with the value "Hello!" in it:

We can put any value in the box.

We can also change it as many times as we want:

When the value is changed, the old data is removed from the variable:

We can also declare two variables and copy data from one into the other.

A variable should be declared only once.

A repeated declaration of the same variable is an error:

So, we should declare a variable once and then refer to it without let .

It’s interesting to note that there exist so-called pure functional programming languages, such as Haskell , that forbid changing variable values.

In such languages, once the value is stored “in the box”, it’s there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can’t reuse the old one.

Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits.

Variable naming

There are two limitations on variable names in JavaScript:

  • The name must contain only letters, digits, or the symbols $ and _ .
  • The first character must not be a digit.

Examples of valid names:

When the name contains multiple words, camelCase is commonly used. That is: words go one after another, each word except first starting with a capital letter: myVeryLongName .

What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.

These names are valid:

Examples of incorrect variable names:

Variables named apple and APPLE are two different variables.

It is possible to use any language, including cyrillic letters, Chinese logograms and so on, like this:

Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we’re writing a small script, it may have a long life ahead. People from other countries may need to read it some time.

There is a list of reserved words , which cannot be used as variable names because they are used by the language itself.

For example: let , class , return , and function are reserved.

The code below gives a syntax error:

Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using let . This still works now if we don’t put use strict in our scripts to maintain compatibility with old scripts.

This is a bad practice and would cause an error in strict mode:

To declare a constant (unchanging) variable, use const instead of let :

Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so would cause an error:

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and clearly communicate that fact to everyone.

Uppercase constants

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:

  • COLOR_ORANGE is much easier to remember than "#FF7F00" .
  • It is much easier to mistype "#FF7F00" than COLOR_ORANGE .
  • When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00 .

When should we use capitals for a constant and when should we name it normally? Let’s make that clear.

Being a “constant” just means that a variable’s value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are calculated in run-time, during the execution, but do not change after their initial assignment.

For instance:

The value of pageLoadTime is not known prior to the page load, so it’s named normally. But it’s still a constant because it doesn’t change after assignment.

In other words, capital-named constants are only used as aliases for “hard-coded” values.

Name things right

Talking about variables, there’s one more extremely important thing.

A variable name should have a clean, obvious meaning, describing the data that it stores.

Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code was written by a beginner versus an experienced developer.

In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it’s much easier to find information that is well-labeled. Or, in other words, when the variables have good names.

Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.

Some good-to-follow rules are:

  • Use human-readable names like userName or shoppingCart .
  • Stay away from abbreviations or short names like a , b , c , unless you really know what you’re doing.
  • Make names maximally descriptive and concise. Examples of bad names are data and value . Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
  • Agree on terms within your team and in your own mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown .

Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.

And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.

As a result, their variables are like boxes into which people throw different things without changing their stickers. What’s inside the box now? Who knows? We need to come closer and check.

Such programmers save a little bit on variable declaration but lose ten times more on debugging.

An extra variable is good, not evil.

Modern JavaScript minifiers and browsers optimize code well enough, so it won’t create performance issues. Using different variables for different values can even help the engine optimize your code.

We can declare variables to store data by using the var , let , or const keywords.

  • let – is a modern variable declaration.
  • var – is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover subtle differences from let in the chapter The old "var" , just in case you need them.
  • const – is like let , but the value of the variable can’t be changed.

Variables should be named in a way that allows us to easily understand what’s inside them.

Working with variables

  • Declare two variables: admin and name .
  • Assign the value "John" to name .
  • Copy the value from name to admin .
  • Show the value of admin using alert (must output “John”).

In the code below, each line corresponds to the item in the task list.

Giving the right name

  • Create a variable with the name of our planet. How would you name such a variable?
  • Create a variable to store the name of a current visitor to a website. How would you name that variable?

The variable for our planet

That’s simple:

Note, we could use a shorter name planet , but it might not be obvious what planet it refers to. It’s nice to be more verbose. At least until the variable isNotTooLong.

The name of the current visitor

Again, we could shorten that to userName if we know for sure that the user is current.

Modern editors and autocomplete make long variable names easy to write. Don’t save on them. A name with 3 words in it is fine.

And if your editor does not have proper autocompletion, get a new one .

Uppercase const?

Examine the following code:

Here we have a constant birthday for the date, and also the age constant.

The age is calculated from birthday using someCode() , which means a function call that we didn’t explain yet (we will soon!), but the details don’t matter here, the point is that age is calculated somehow based on the birthday .

Would it be right to use upper case for birthday ? For age ? Or even for both?

We generally use upper case for constants that are “hard-coded”. Or, in other words, when the value is known prior to execution and directly written into the code.

In this code, birthday is exactly like that. So we could use the upper case for it.

In contrast, age is evaluated in run-time. Today we have one age, a year after we’ll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit “less of a constant” than birthday : it is calculated, so we should keep the lower case for it.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2023  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

IMAGES

  1. Learn JavaScript

    variable assignment js

  2. JavaScript Series Part 2: JavaScript Variables and Constants

    variable assignment js

  3. JavaScript Assignment Operators

    variable assignment js

  4. How to assign a string to a variable using if else in javascript?

    variable assignment js

  5. JavaScript variable assignment explained

    variable assignment js

  6. JS: Assigning values to multiple variables : r/learnjavascript

    variable assignment js

VIDEO

  1. 江蕙 落雨聲 周杰倫&方文山聯手創作精選

  2. TBB configuration in Visual Studio 2013

  3. JS variable Hoisting (22/7)

  4. What is variable in JS #codewithharry #apnacollge #freecodecamp

  5. Day 1

  6. Data Types and Variable Assignment 1

COMMENTS

  1. What Is a Qualitative Variable?

    Qualitative variables are those with no natural or logical order. While scientists often assign a number to each, these numbers are not meaningful in any way. Examples of qualitative variables include things such as color, shape or pattern.

  2. How to Assess and Evaluate React JS Developer Candidates: A Step-by-Step Guide

    When it comes to hiring React JS developers, it’s crucial to have a thorough assessment and evaluation process in place. With the rising popularity of React JS, finding the right developer for your project can be challenging.

  3. The Essential Skills and Qualities to Look for When Hiring React JS Developers

    React JS has become one of the most popular JavaScript libraries for building user interfaces. Its flexibility, reusability, and efficiency have made it a go-to choice for many companies looking to develop robust web applications.

  4. Assignment (=)

    The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is

  5. JavaScript Variables

    You declare a JavaScript variable with the var or the let keyword: var carName;. or: let carName;. After the declaration

  6. Assignment Expressions

    JavaScript uses the = operator to assign a value to a variable or property. For example: i = 0 // Set the variable i to 0. o . x = 1 // Set the property x

  7. Introduction to JavaScript Variables and Assignment

    Variables in JavaScript. Variables in JavaScript are commonly declared by using a var keyword, followed by a variable name, assignment operator (equals sign = )

  8. 11 Variables and assignment

    11 Variables and assignment · let declares mutable variables. · const indicates an immutable binding and that a variable never changes its value. · Scope A is

  9. JavaScript OR (||) variable assignment explanation

    It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "

  10. JavaScript Variable: Declare, Assign a Value with Example

    Variables are used to store values (name = "John") or expressions (sum = x + y). Before using a variable, you first need to declare it.

  11. JavaScript Variables (With Examples)

    In JavaScript, a variable can be declared using var , let , const keywords. ... Here, we will use the let keyword to declare variables. To

  12. Variable Declaration and Assignment in JavaScript

    Thus, the recommendation is to declare all variables using const , and only change them to let if you discover a need to allow their values to

  13. Variables

    To create a variable in JavaScript, use the let keyword. ... To be concise, we can combine the variable declaration and assignment into a single

  14. Understanding Different Variable Assignment Approaches in

    In JavaScript, there are multiple ways to assign values to variables. One common scenario where different assignment approaches come into