How to assign block of HTML code to a JavaScript variable

Topic: JavaScript / jQuery Prev | Next

Answer: Use the concatenation operator (+)

The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

You also need to escape the single-quotes which appears inside the content of HTML block — just replace the ' character with \' , as shown in the following example:

Related FAQ

Here are some more FAQ related to this topic:

  • How to add elements to DOM in jQuery
  • How to remove wrapper element but keep the text content intact using jQuery
  • How to bind click event to dynamically added HTML elements in jQuery

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.

Interactive Tools

BMC

  • Check Null Variable
  • Get Current URL
  • Change Span Text
  • Change Background Color
  • Add Class To HTML
  • Check Variable Exists
  • Remove Property
  • Adding Comment
  • Get HTML Tag ClassName
  • Assign HTML To JS Variable
  • Password validation in
  • Detect Screen Resolution
  • Automatically adjust iframe height
  • Create javascript progress
  • How to clear
  • Replace All Occurrences
  • Convert String to Array
  • Find SubString
  • Split String
  • Check Empty String
  • Replace Char in String
  • Object is Array
  • Check Value in Array
  • Remove Array Element
  • Check Object in Array
  • Remove Duplicate from Array
  • Object to JSON
  • Get Day-Month-Year

How to assign block of HTML code to a JavaScript variable?

Answer: using single quote and concatenation (+) operator.

JavaScript offers various ways to assign the HTML code to a JavaScript Variable. The easiest way to assign the HTML code to the JavaScript variable is using the concatenation operator. We just have to put the block of HTML code within the single quote and use plus(+) operator to combine multiline, and then assign this to JS variable. Using the single quotes, we can preserve the double quotes within the actual code HTML code.

Example: Using Single Quote and Concatenation (+) operator

In the given example, we have used the concatenation operator (+) and assigned the block of HTML code to a JavaScript variable.

Hello World! Welcome to Studytonight We at Studytonight believe that by widening the reach of education, by making it freely available, so much can be achieved.

Apart from the concatenation operator, we can also assign the block of HTML code to a JavaScript variable using the backticks (` `). The concept of backticks was introduced in ES6. We just have to put the block of HTML code within the backticks without using any concatenation operator and then assign it to a JavaScript variable. We will get the same output that we get when using the given block of HTML code without JavaScript.

Example: Using backticks (` `)

In the given example, we have used the backticks (` `) to assign the block of HTML code to the JavaScript variable. When we use backticks then there is no need to use the concatenation operator to concatenate the HTML code.

In this lesson, we have learned how to assign the HTML code to a JavaScript variable. Here, we have discussed two methods to assign the HTML code to the JavaScript variable. The first method is using the concatenation operator (+), we just have to put the HTML code inside the single quote and concatenate each line of code using the concatenation operator. In the second method, we have used the backticks (` `). We just have to put the block of HTML code inside the backticks.

  • ← Get HTML Tag ClassName ← PREV
  • Password validation in → NEXT →

C language

  • How to Use JavaScript Variable in HTML
  • JavaScript Howtos

JavaScript User Defined Variable Usage in HTML

Javascript variable loaded from prompt, create a tag element from script and variable access to html.

How to Use JavaScript Variable in HTML

JavaScript variables are often user-defined while coding, or you can use prompt to fetch data and store it in a variable for further use.

Here, we will show how to act upon a user-defined variable and use it in HTML, and the later demonstration will explain how the prompt can help us in this regard.

We are using jsbin for the code examples, and here you will see the p element is identified by the id output . Initially, the variable myPet is set to be Tobey , and the later simple line was executed in the webpage. getElementById finds the preferred id , and later the variables are passed in the inner.HTML format so the JavaScript variables can be used in the HTML .

Code Snippet:

user defined js variable in html

In this segment, we will see how we easily input value in the prompt window, and that directly is displayed in our loaded webpage.

prompt input

Here, we will create a p tag in the script, which will be accessible in the HTML body . The p.innerHTML is the key to passing the variable data towards the body tag.

create tag element to pass in html

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article - JavaScript Variable

  • How to Access the Session Variable in JavaScript
  • How to Check Undefined and Null Variable in JavaScript
  • How to Mask Variable Value in JavaScript
  • Why Global Variables Give Undefined Values in JavaScript
  • How to Declare Multiple Variables in a Single Line in JavaScript
  • How to Declare Multiple Variables in JavaScript

Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

Variable reassignment, variable assignment by reference, copying by reference, the spread operator to the rescue, are mutations bad, frequently asked questions (faqs) about javascript variable assignment and mutation.

Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they’re made out to be?

In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out the first chapter of my new book Learn to Code with JavaScript for free.

Let’s start by going back to the very basics of value types …

Every value in JavaScript is either a primitive value or an object. There are seven different primitive data types:

  • numbers, such as 3 , 0 , -4 , 0.625
  • strings, such as 'Hello' , "World" , `Hi` , ''
  • Booleans, true and false
  • symbols — a unique token that’s guaranteed never to clash with another symbol
  • BigInt — for dealing with large integer values

Anything that isn’t a primitive value is an object , including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.

Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number 3 to the variable bears :

A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.

variables like a box

An alternative way of thinking about what happens is as a reference, that maps the label bears to the value of 3 :

variables like a reference

If I assign the number 3 to another variable, it’s referencing the same value as bears:

variables referencing the same value

The variables bears and musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator, === :

The equality operator returns true if both variables are referencing the same value.

Some gotchas when working with objects

The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable ghostbusters :

Even though the variables ghostbusters and tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:

variables referencing different objects

When the const keyword was introduced in ES6, many people mistakenly believed that constants had been introduced to JavaScript, but this wasn’t the case. The name of this keyword is a little misleading.

Any variable declared with const can’t be reassigned to another value. This goes for primitive values and objects. For example, the variable bears was declared using const in the previous section, so it can’t have another value assigned to it. If we try to assign the number 2 to the variable bears , we get an error:

The reference to the number 3 is fixed and the bears variable can’t be reassigned another value.

The same applies to objects. If we try to assign a different object to the variable ghostbusters , we get the same error:

Variable reassignment using let

When the keyword let is used to declare a variable, it can be reassigned to reference a different value later on in our code. For example, we declared the variable musketeers using let , so we can change the value that musketeers references. If D’Artagnan joined the Musketeers, their number would increase to 4:

variables referencing different values

This can be done because let was used to declare the variable. We can alter the value that musketeers references as many times as we like.

The variable tmnt was also declared using let , so it can also be reassigned to reference another object (or a different type entirely if we like):

Note that the variable tmnt now references a completely different object ; we haven’t just changed the number property to 5.

In summary , if you declare a variable using const , its value can’t be reassigned and will always reference the same primitive value or object that it was originally assigned to. If you declare a variable using let , its value can be reassigned as many times as required later in the program.

Using const as often as possible is generally considered good practice, as it means that the value of variables remains constant and the code is more consistent and predictable, making it less prone to errors and bugs.

In native JavaScript, you can only assign values to variables. You can’t assign variables to reference another variable, even though it looks like you can. For example, the number of Stooges is the same as the number of Musketeers, so we can assign the variable stooges to reference the same value as the variable musketeers using the following:

This looks like the variable stooges is referencing the variable musketeers , as shown in the diagram below:

variables cannot reference another variable

However, this is impossible in native JavaScript: a variable can only reference an actual value; it can’t reference another variable . What actually happens when you make an assignment like this is that the variable on the left of the assignment will reference the value the variable on the right references, so the variable stooges will reference the same value as the musketeers variable, which is the number 3. Once this assignment has been made, the stooges variable isn’t connected to the musketeers variable at all.

variables referencing values

This means that if D’Artagnan joins the Musketeers and we set the value of the musketeers to 4, the value of stooges will remain as 3. In fact, because we declared the stooges variable using const , we can’t set it to any new value; it will always be 3.

In summary : if you declare a variable using const and set it to a primitive value, even via a reference to another variable, then its value can’t change. This is good for your code, as it means it will be more consistent and predictable.

A value is said to be mutable if it can be changed. That’s all there is to it: a mutation is the act of changing the properties of a value.

All primitive value in JavaScript are immutable : you can’t change their properties — ever. For example, if we assign the string "cake" to variable food , we can see that we can’t change any of its properties:

If we try to change the first letter to “f”, it looks like it has changed:

But if we take a look at the value of the variable, we see that nothing has actually changed:

The same thing happens if we try to change the length property:

Despite the return value implying that the length property has been changed, a quick check shows that it hasn’t:

Note that this has nothing to do with declaring the variable using const instead of let . If we had used let , we could set food to reference another string, but we can’t change any of its properties. It’s impossible to change any properties of primitive data types because they’re immutable .

Mutability and objects in JavaScript

Conversely, all objects in JavaScript are mutable, which means that their properties can be changed, even if they’re declared using const (remember let and const only control whether or not a variable can be reassigned and have nothing to do with mutability). For example, we can change the the first item of an array using the following code:

Note that this change still occurred, despite the fact that we declared the variable food using const . This shows that using const does not stop objects from being mutated .

We can also change the length property of an array, even if it has been declared using const :

Remember that when we assign variables to object literals, the variables will reference completely different objects, even if they look the same:

But if we assign a variable fantastic4 to another variable, they will both reference the same object:

This assigns the variable fantastic4 to reference the same object that the variable tmnt references, rather than a completely different object.

variables referencing the same object

This is often referred to as copying by reference , because both variables are assigned to reference the same object.

This is important, because any mutations made to this object will be seen in both variables.

So, if Spider-Man joins The Fantastic Four, we might update the number value in the object:

This is a mutation, because we’ve changed the number property rather than setting fantastic4 to reference a new object.

This causes us a problem, because the number property of tmnt will also also change, possibly without us even realizing:

This is because both tmnt and fantastic4 are referencing the same object, so any mutations that are made to either tmnt or fantastic4 will affect both of them.

This highlights an important concept in JavaScript: when objects are copied by reference and subsequently mutated, the mutation will affect any other variables that reference that object. This can lead to unintended side effects and bugs that are difficult to track down.

So how do you make a copy of an object without creating a reference to the original object? The answer is to use the spread operator !

The spread operator was introduced for arrays and strings in ES2015 and for objects in ES2018. It allows you to easily make a shallow copy of an object without creating a reference to the original object.

The example below shows how we could set the variable fantastic4 to reference a copy of the tmnt object. This copy will be exactly the same as the tmnt object, but fantastic4 will reference a completely new object. This is done by placing the name of the variable to be copied inside an object literal with the spread operator in front of it:

What we’ve actually done here is assign the variable fantastic4 to a new object literal and then used the spread operator to copy all the enumerable properties of the object referenced by the tmnt variable. Because these properties are values, they’re copied into the fantastic4 object by value, rather than by reference.

variables referencing different objects

Now any changes that are made to either object won’t affect the other. For example, if we update the number property of the fantastic4 variable to 5, it won’t affect the tmnt variable:

Changes don't affect the other object

The spread operator also has a useful shortcut notation that can be used to make copies of an object and then make some changes to the new object in a single line of code.

For example, say we wanted to create an object to model the Teenage Mutant Ninja Turtles. We could create the first turtle object, and assign the variable leonardo to it:

The other turtles all have the same properties, except for the weapon and color properties, that are different for each turtle. It makes sense to make a copy of the object that leonardo references, using the spread operator, and then change the weapon and color properties, like so:

We can do this in one line by adding the properties we want to change after the reference to the spread object. Here’s the code to create new objects for the variables donatello and raphael :

Note that using the spread operator in this way only makes a shallow copy of an object. To make a deep copy, you’d have to do this recursively, or use a library. Personally, I’d advise that you try to keep your objects as shallow as possible.

In this article, we’ve covered the concepts of variable assignment and mutation and seen why — together — they can be a real pain for developers.

Mutations have a bad reputation, but they’re not necessarily bad in themselves. In fact, if you’re building a dynamic web app, it must change at some point. That’s literally the meaning of the word “dynamic”! This means that there will have to be some mutations somewhere in your code. Having said that, the fewer mutations there are, the more predictable your code will be, making it easier to maintain and less likely to develop any bugs.

A particularly toxic combination is copying by reference and mutations. This can lead to side effects and bugs that you don’t even realize have happened. If you mutate an object that’s referenced by another variable in your code, it can cause lots of problems that can be difficult to track down. The key is to try and minimize your use of mutations to the essential and keep track of which objects have been mutated.

In functional programming, a pure function is one that doesn’t cause any side effects, and mutations are one of the biggest causes of side effects.

A golden rule is to avoid copying any objects by reference. If you want to copy another object, use the spread operator and then make any mutations immediately after making the copy.

Next up, we’ll look into array mutations in JavaScript .

Don’t forget to check out my new book Learn to Code with JavaScript if you want to get up to speed with modern JavaScript. You can read the first chapter for free. And please reach out on Twitter if you have any questions or comments!

What is the difference between variable assignment and mutation in JavaScript?

In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand, mutation refers to the process of changing the value of an existing variable. For example, if we later write x = 10; we are mutating the variable x by changing its value from 5 to 10.

How does JavaScript handle variable assignment and mutation differently for primitive and non-primitive data types?

JavaScript treats primitive data types (like numbers, strings, and booleans) and non-primitive data types (like objects and arrays) differently when it comes to variable assignment and mutation. For primitive data types, when you assign a variable, a copy of the value is created and stored in a new memory location. However, for non-primitive data types, when you assign a variable, both variables point to the same memory location. Therefore, if you mutate one variable, the change is reflected in all variables that point to that memory location.

What is the concept of pass-by-value and pass-by-reference in JavaScript?

Pass-by-value and pass-by-reference are two ways that JavaScript can pass variables to a function. When JavaScript passes a variable by value, it creates a copy of the variable’s value and passes that copy to the function. Any changes made to the variable inside the function do not affect the original variable. However, when JavaScript passes a variable by reference, it passes a reference to the variable’s memory location. Therefore, any changes made to the variable inside the function also affect the original variable.

How can I prevent mutation in JavaScript?

There are several ways to prevent mutation in JavaScript. One way is to use the Object.freeze() method, which prevents new properties from being added to an object, existing properties from being removed, and prevents changing the enumerability, configurability, or writability of existing properties. Another way is to use the const keyword when declaring a variable. This prevents reassignment of the variable, but it does not prevent mutation of the variable’s value if the value is an object or an array.

What is the difference between shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy of an object is a copy of the object where the values of the original object and the copy point to the same memory location for non-primitive data types. Therefore, if you mutate the copy, the original object is also mutated. On the other hand, a deep copy of an object is a copy of the object where the values of the original object and the copy do not point to the same memory location. Therefore, if you mutate the copy, the original object is not mutated.

How can I create a deep copy of an object in JavaScript?

One way to create a deep copy of an object in JavaScript is to use the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object into a JSON string, and the JSON.parse() method converts the JSON string back into an object. This creates a new object that is a deep copy of the original object.

What is the MutationObserver API in JavaScript?

The MutationObserver API provides developers with a way to react to changes in a DOM. It is designed to provide a general, efficient, and robust API for reacting to changes in a document.

How does JavaScript handle variable assignment and mutation in the context of closures?

In JavaScript, a closure is a function that has access to its own scope, the scope of the outer function, and the global scope. When a variable is assigned or mutated inside a closure, it can affect the value of the variable in the outer scope, depending on whether the variable was declared in the closure’s scope or the outer scope.

What is the difference between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables. var is function scoped, and if it is declared outside a function, it is globally scoped. let and const are block scoped, meaning they exist only within the block they are declared in. The difference between let and const is that let allows reassignment, while const does not.

How does JavaScript handle variable assignment and mutation in the context of asynchronous programming?

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

Darren loves building web apps and coding in JavaScript, Haskell and Ruby. He is the author of Learn to Code using JavaScript , JavaScript: Novice to Ninja and Jump Start Sinatra .He is also the creator of Nanny State , a tiny alternative to React. He can be found on Twitter @daz4126.

SitePoint Premium

Home » JavaScript Tutorial » JavaScript Variables

JavaScript Variables

Summary : in this tutorial, you’ll learn about JavaScript variables and how to use variables to store values in the application.

A variable is a label that references a value like a number or string. Before using a variable, you need to declare it.

Declare a variable

To declare a variable, you use the var keyword followed by the variable name as follows:

A variable name can be any valid identifier. By default, the message variable has a special value undefined if you have not assigned a value to it.

Variable names follow these rules:

  • Variable names are case-sensitive. This means that the message and Message are different variables.
  • Variable names can only contain letters, numbers, underscores, or dollar signs and cannot contain spaces. Also, variable names must begin with a letter, an underscore ( _ ) or a dollar sign ( $) .
  • Variable names cannot use the reserved words.

By convention, variable names use camelcase like message , yourAge , and myName .

JavaScript is a dynamically typed language. This means that you don’t need to specify the variable’s type in the declaration like other static-typed languages such as Java or C# .

Starting in ES6, you can use the let keyword to declare a variable like this:

It’s a good practice to use the let keyword to declare a variable. Later, you’ll learn the differences between var and let keywords . And you should not worry about it for now.

Initialize a variable

Once you have declared a variable, you can initialize it with a value. To initialize a variable, you specify the variable name, followed by an equals sign ( = ) and a value.

For example, The following declares the message variable and initializes it with a literal string "Hello" :

To declare and initialize a variable at the same time, you use the following syntax:

For example, the following statement declares the message variable and initializes it with the literal string "Hello" :

JavaScript allows you to declare two or more variables using a single statement. To separate two variable declarations, you use a comma ( , ) like this:

Since JavaScript is a dynamically typed language, you can assign a value of a different type to a variable. Although, it is not recommended. For example:

Change a variable

Once you initialize a variable, you can change its value by assigning a different value. For example:

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 labelled "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 sometime.

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 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 before 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 some constants are known before execution (like a hexadecimal value for red) and some constants 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 before the page load, so it’s named normally. But it’s still a constant because it doesn’t change after the 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 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-labelled. 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 , and c , unless you 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 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—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

How to display JavaScript variable value in HTML

by Nathan Sebhastian

Posted on Mar 28, 2021

Reading time: 3 minutes

js assign html to variable

There are three ways to display JavaScript variable values in HTML pages:

  • Display the variable using document.write() method
  • Display the variable to an HTML element content using innerHTML property
  • Display the variable using the window.alert() method

This tutorial will show you how to use all three ways to display JavaScript variables in HTML pages. Let’s start with using document.write() method.

Display JavaScript variable using document.write() method

The document.write() method allows you to replace the entire content of HTML <body> tag with HTML and JavaScript expressions that you want to be displayed inside the <body> tag. Suppose you have the following HTML element:

When you run document.write("Hello") method on the HTML piece above, the content of <body> will be replaced as follows:

Knowing this, you can display any JavaScript variable value by simply passing the variable name as the parameter to document.write() method:

The document.write() method is commonly used only for testing purposes because it will delete any existing HTML elements inside your <body> tag. Mostly, you would want to display a JavaScript variable beside your HTML elements. To do that, you need to use the next method.

Display JavaScript variable using innerHTML property.

Every single HTML element has the innerHTML property which holds the content of that element. The browser allows you to manipulate the innerHTML property by using JavaScript by simply assigning the property to a different value.

For example, imagine you have the following HTML <body> tag:

You can replace the content of <p> tag by first retrieving the element using its identifier. Since the element <p> has an id attribute with the value of greeting , you can use document.getElementById method to retrieve it and change its innerHTML property.

Here’s how you do it:

The content of <p> tag will be changed as follows:

Knowing this, you can simply wrap the space where you want your JavaScript variable to be displayed with a <span> element as follows:

The code above will output the following HTML:

And that’s how you can display JavaScript variable values using innerHTML property.

Display JavaScript variable using window.alert() method

The window.alert() method allows you to launch a dialog box at the front of your HTML page. For example, when you try running the following HTML page:

The following dialog box should appear in your browser:

The JavaScript alert box example

The implementation for each browser will slightly vary, but they all work the same. Knowing this, you can easily use the dialog box to display the value of a JavaScript variable. Simply pass the variable name to the alert() method as follows:

The code above will launch a dialog box that displays the value of the name variable.

Displaying JavaScript variables in HTML pages is a common task for web developers. Modern browsers allow you to manipulate the HTML content by calling on exposed JavaScript API methods.

The most common way to display the value of a JavaScript variable is by manipulating the innerHTML property value, but when testing your variables, you can also use either document.write() or window.alert() methods. You are free to use the method that suits you best.

Take your skills to the next level ⚡️

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

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

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

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

I'm a self-taught, passionate front-end developer who enjoys writing TypeScript and strives to become a better developer.

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

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 assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

<var>: The Variable element

The <var> HTML element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent.

This element only includes the global attributes .

Usage notes

Related elements.

Other elements that are used in contexts in which <var> is commonly used include:

  • <code> : The HTML Code element
  • <kbd> : The HTML Keyboard input element
  • <samp> : The HTML Sample Output element

If you encounter code that is mistakenly using <var> for style purposes rather than semantic purposes, you should either use a <span> with appropriate CSS or, an appropriate semantic element among the following:

Default style

Most browsers apply font-style to "italic" when rendering <var> . This can be overridden in CSS, like this:

Basic example

Here's a simple example, using <var> to denote variable names in a mathematical equation.

Overriding the default style

Using CSS, you can override the default style for the <var> element. In this example, variable names are rendered in bold, using Courier if it's available, otherwise it falls back to the default monospace font.

This HTML uses <var> to enclose the names of two variables.

Technical summary

Specifications, browser compatibility.

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

IMAGES

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

    js assign html to variable

  2. Declare & Assign values to variables in JavaScript

    js assign html to variable

  3. How to declare variables in different ways in JavaScript?

    js assign html to variable

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

    js assign html to variable

  5. How to Declare a Variable in Javascript (with Pictures)

    js assign html to variable

  6. How to Use Javascript Variable in HTML · DevPractical

    js assign html to variable

VIDEO

  1. Hexadecimal to Decimal

  2. PowerApps Components Tutorial Part 1

  3. JavaScript var let const Variable Keyword

  4. Javascript Variables

  5. Javascript

  6. Variable in JavaScript

COMMENTS

  1. how to assign a block of html code to a javascript variable

    I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution. First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

  2. html

    Let's say I have a variable called x in javascript. How can I set the value of a text input (HTML) to that variable? For example: The value of the input will now be Swag <input type="text" value="Swag" /> But if I want the value to be a javascript variable? How do I do? Something like this? (I am just guessing, trying to make my point clear)

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

  4. How do I use this JavaScript variable in HTML?

    To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.

  5. How to assign block of HTML code to a JavaScript variable

    Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( +) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code. You also need to escape the ...

  6. How to assign block of HTML code to a JavaScript variable?

    The easiest way to assign the HTML code to the JavaScript variable is using the concatenation operator. We just have to put the block of HTML code within the single quote and use plus (+) operator to combine multiline, and then assign this to JS variable. Using the single quotes, we can preserve the double quotes within the actual code HTML code.

  7. How to Use JavaScript Variable in HTML

    Create a Tag Element From Script and Variable Access to HTML. Here, we will create a p tag in the script, which will be accessible in the HTML body. The p.innerHTML is the key to passing the variable data towards the body tag. Code Snippet: p.innerHTML = myPet + ' is a ' + nameLength + ' letter name!'; Output:

  8. Storing the information you need

    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: js. let myName; let myAge; Here we're creating two variables called myName and myAge.

  9. A Guide to Variable Assignment and Mutation in JavaScript

    In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand ...

  10. JavaScript Variables

    Let's declare a variable, age, and use the assignment operator (the equals sign) to assign our value, 4, to this variable. We'll use the var keyword. var age = 4. Variables are how programmers give a name to a value so that we can reuse it, update it, or simply keep track of it. Variables can be used to store any JavaScript type.

  11. JavaScript Variables

    JavaScript allows you to declare two or more variables using a single statement. To separate two variable declarations, you use a comma (,) like this: let message = "Hello", counter = 100; Code language: JavaScript (javascript) Since JavaScript is a dynamically typed language, you can assign a value of a different type to a variable.

  12. Variables

    A variable is a "named storage" for data. We can use variables to store goodies, visitors, and other data. To create a variable in JavaScript, use the let keyword. The statement below creates (in other words: declares) a variable with the name "message": let message; Now, we can put some data into it by using the assignment operator =:

  13. How to display JavaScript variable value in HTML

    by Nathan Sebhastian. Posted on Mar 28, 2021. Reading time: 3 minutes. There are three ways to display JavaScript variable values in HTML pages: Display the variable using document.write() method. Display the variable to an HTML element content using innerHTML property. Display the variable using the window.alert() method.

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

  15. How to Declare Variables in JavaScript

    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:

  16. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  17. Declare a variable in javascript and use it in html [duplicate]

    I have big html document with various images with href and src. I want to declare their href and src so as to change only their var values. something like... <script> var imagehref = w...

  18. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  19. Destructuring assignment

    Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo. Assigning to new variable names and providing default values. A property can be both. Unpacked from an object and assigned to a variable with a different name. Assigned a default value in case the unpacked value is ...

  20. I want to assign javascript variable to html element inside javascript

    I'm trying to insert javascript variable value in html element inside javascript.. But it's not working properly.. following are my code.. window.onload = function() { var image=document. ... I want to assign javascript variable to html element inside javascript. Ask Question Asked 11 years, 10 months ago. Modified 11 years, 10 months ago.

  21. : The Variable element

    The HTML element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent. ... JavaScript. Learn to run scripts in the browser. Accessibility. Learn to make the web accessible to all. Plus ...