1.4 — Variable assignment and initialization

Copy initialization is also used whenever values are implicitly copied or converted, such as when passing arguments to a function by value, returning from a function by value, or catching exceptions by value.

The modern way to initialize objects in C++ is to use a form of initialization that makes use of curly braces. This is called list initialization (or uniform initialization or brace initialization ).

Conversions that can be done without potential data loss are allowed.

Q: When should I initialize with { 0 } vs {}?

CS101: Introduction to Computer Science I

variable assignment vs declaration

Variables and Assignment Statements

Read this chapter, which covers variables and arithmetic operations and order precedence in Java.

5. Syntax of Variable Declaration

Syntax of variable deceleration.

The word  syntax  means the grammar of a programming language. We can talk about the syntax of just a small part of a program, such as the syntax of variable declaration.

There are several ways to declare variables:

  • This declares a variable, declares its data type, and reserves memory for it. It says nothing about what value is put in memory. (Later in these notes you will learn that in some circumstances the variable is automatically initialized, and that in other circumstances the variable is left uninitialized.)
  • This declares a variable, declares its data type, reserves memory for it, and puts an initial value into that memory. The initial value must be of the correct data type.
  • This declares  two  variables, both of the same data type, reserves memory for each, but puts nothing in any variable. You can do this with more than two variables, if you want.
  • This declares  two  variables, both of the same data type, reserves memory, and puts an initial value in each variable. You can do this all on one line if there is room. Again, you can do this for more than two variables as long as you follow the pattern.

If you have several variables of different types, use several declaration statements. You can even use several declaration statements for several variables of the same type.

Question 4:

Is the following correct?

Maker's Aid Logo

Maker's Aid

Declare vs. Assign in JavaScript

What’s the difference between declaring a constant or variable and assigning it a value? Here’s everything you need to know.

variable assignment vs declaration

You’re just getting started with JavaScript, and you want to learn the difference between declaring a constant or variable and assigning (or initializing) it.

To declare a constant or variable is to give it an identifier so that you can reference it. To assign a value to a variable is to store information in it.

This beginner’s guide will teach you how to declare constants and variables, how to assign them values, and more.

In JavaScript, you can create constants and variables—basically, objects that hold information—and give them values that you can use later in your code.

You create a constant or variable by declaring it with a const , let , or var statement.

Declare a Constant

The const statement is for constants:

Constants cannot be redeclared or reassigned.

Declare a Variable With Let

The let statement is for variables with a block scope:

Variables declared with the let statement cannot be redeclared but can be reassigned.

Declare a Variable With Var

And the var statement is for variable with a function scope or global scope:

Variables declared with the var statement can be redeclared and reassigned.

Once you’ve declared a constant or variable, you can assign it a value with the assignment operator (=) .

The first time you assign a value to a constant or variable is called “assignment” or “initialization.”

You can initialize a constant or variable at declaration:

You can also declare your constant or variable empty, then initialize it post-declaration:

The Difference Between Declaring and Assigning

To declare a constant or a variable is to create a data object and give a name, so that you can reference it later in your code. To assign a constant or variable, on the other hand, is to give it a value.

Another name for declaration, if oversimplified, could be “naming it.” And another name for assignment could be “storing information in it.”

To Redeclare

In JavaScript, certain types of data objects can be declared more than once, or “redeclared.”

Constants cannot be redeclared within the same scope:

Neither can variables declared with the let statement:

However, variables declared with the var statement can be redeclared:

To Reassign

In JavaScript, certain types of data objects can be assigned values more than once, or “reassigned.”

Constants cannot be reassigned within the same scope:

Variables declared with let or var , on the other hand, can be reassigned within the same scope:

Whether it is a good idea to redeclare and reassign in your code is the subject of heated debate in the JavaScript development community.

Summing It Up

constletvar
RedeclareNot possibleNot possiblePossible
ReassignNot possible within the same scopePossiblePossible

Thank you for reading this far and I hope this tutorial helped.

You now know the difference between declaring a constant or variable and assigning it a value. You also know when you can—and cannot—redeclare and reassign constants or variables depending on the type of statement that you used.

If you have any questions, be sure to leave a reply below.

Leave a comment Cancel reply

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

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

variable assignment vs declaration

Variables in Python

Variables in Python

Table of Contents

Variable Assignment

Variable types in python, object references, object identity, variable names, reserved words (keywords).

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Variables in Python

In the previous tutorial on Basic Data Types in Python , you saw how values of various Python data types can be created. But so far, all the values shown have been literal or constant values:

If you’re writing more complex code, your program will need data that can change as program execution proceeds.

Here’s what you’ll learn in this tutorial: You will learn how every item of data in a Python program can be described by the abstract term object , and you’ll learn how to manipulate objects using symbolic names called variables .

Free PDF Download: Python 3 Cheat Sheet

Take the Quiz: Test your knowledge with our interactive “Python Variables” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python variables and object references.

Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ):

This is read or interpreted as “ n is assigned the value 300 .” Once this is done, n can be used in a statement or expression, and its value will be substituted:

Just as a literal value can be displayed directly from the interpreter prompt in a REPL session without the need for print() , so can a variable:

Later, if you change the value of n and use it again, the new value will be substituted instead:

Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously:

The chained assignment above assigns 300 to the variables a , b , and c simultaneously.

In many programming languages, variables are statically typed. That means a variable is initially declared to have a specific data type, and any value assigned to it during its lifetime must always have that type.

Variables in Python are not subject to this restriction. In Python, a variable may be assigned a value of one type and then later re-assigned a value of a different type:

What is actually happening when you make a variable assignment? This is an important question in Python, because the answer differs somewhat from what you’d find in many other programming languages.

Python is a highly object-oriented language . In fact, virtually every item of data in a Python program is an object of a specific type or class. (This point will be reiterated many times over the course of these tutorials.)

Consider this code:

When presented with the statement print(300) , the interpreter does the following:

  • Creates an integer object
  • Gives it the value 300
  • Displays it to the console

You can see that an integer object is created using the built-in type() function:

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object.

For example:

This assignment creates an integer object with the value 300 and assigns the variable n to point to that object.

Variable reference diagram

The following code verifies that n points to an integer object:

Now consider the following statement:

What happens when it is executed? Python does not create another object. It simply creates a new symbolic name or reference, m , which points to the same object that n points to.

Python variable references to the same object (illustration)

Next, suppose you do this:

Now Python creates a new integer object with the value 400 , and m becomes a reference to it.

References to separate objects in Python (diagram)

Lastly, suppose this statement is executed next:

Now Python creates a string object with the value "foo" and makes n reference that.

Python variable reference illustration

There is no longer any reference to the integer object 300 . It is orphaned, and there is no way to access it.

Tutorials in this series will occasionally refer to the lifetime of an object. An object’s life begins when it is created, at which time at least one reference to it is created. During an object’s lifetime, additional references to it may be created, as you saw above, and references to it may be deleted as well. An object stays alive, as it were, so long as there is at least one reference to it.

When the number of references to an object drops to zero, it is no longer accessible. At that point, its lifetime is over. Python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. In computer lingo, this process is referred to as garbage collection .

In Python, every object that is created is given a number that uniquely identifies it. It is guaranteed that no two objects will have the same identifier during any period in which their lifetimes overlap. Once an object’s reference count drops to zero and it is garbage collected, as happened to the 300 object above, then its identifying number becomes available and may be used again.

The built-in Python function id() returns an object’s integer identifier. Using the id() function, you can verify that two variables indeed point to the same object:

After the assignment m = n , m and n both point to the same object, confirmed by the fact that id(m) and id(n) return the same number. Once m is reassigned to 400 , m and n point to different objects with different identities.

Deep Dive: Caching Small Integer Values From what you now know about variable assignment and object references in Python, the following probably won’t surprise you: Python >>> m = 300 >>> n = 300 >>> id ( m ) 60062304 >>> id ( n ) 60062896 Copied! With the statement m = 300 , Python creates an integer object with the value 300 and sets m as a reference to it. n is then similarly assigned to an integer object with value 300 —but not the same object. Thus, they have different identities, which you can verify from the values returned by id() . But consider this: Python >>> m = 30 >>> n = 30 >>> id ( m ) 1405569120 >>> id ( n ) 1405569120 Copied! Here, m and n are separately assigned to integer objects having value 30 . But in this case, id(m) and id(n) are identical! For purposes of optimization, the interpreter creates objects for the integers in the range [-5, 256] at startup, and then reuses them during program execution. Thus, when you assign separate variables to an integer value in this range, they will actually reference the same object.

The examples you have seen so far have used short, terse variable names like m and n . But variable names can be more verbose. In fact, it is usually beneficial if they are because it makes the purpose of the variable more evident at first glance.

Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters ( A-Z , a-z ), digits ( 0-9 ), and the underscore character ( _ ). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

Note: One of the additions to Python 3 was full Unicode support , which allows for Unicode characters in a variable name as well. You will learn about Unicode in greater depth in a future tutorial.

For example, all of the following are valid variable names:

But this one is not, because a variable name can’t begin with a digit:

Note that case is significant. Lowercase and uppercase letters are not the same. Use of the underscore character is significant as well. Each of the following defines a different variable:

There is nothing stopping you from creating two different variables in the same program called age and Age , or for that matter agE . But it is probably ill-advised. It would certainly be likely to confuse anyone trying to read your code, and even you yourself, after you’d been away from it awhile.

It is worthwhile to give a variable a name that is descriptive enough to make clear what it is being used for. For example, suppose you are tallying the number of people who have graduated college. You could conceivably choose any of the following:

All of them are probably better choices than n , or ncg , or the like. At least you can tell from the name what the value of the variable is supposed to represent.

On the other hand, they aren’t all necessarily equally legible. As with many things, it is a matter of personal preference, but most people would find the first two examples, where the letters are all shoved together, to be harder to read, particularly the one in all capital letters. The most commonly used methods of constructing a multi-word variable name are the last three examples:

  • Example: numberOfCollegeGraduates
  • Example: NumberOfCollegeGraduates
  • Example: number_of_college_graduates

Programmers debate hotly, with surprising fervor, which of these is preferable. Decent arguments can be made for all of them. Use whichever of the three is most visually appealing to you. Pick one and use it consistently.

You will see later that variables aren’t the only things that can be given names. You can also name functions, classes, modules, and so on. The rules that apply to variable names also apply to identifiers, the more general term for names given to program objects.

The Style Guide for Python Code , also known as PEP 8 , contains Naming Conventions that list suggested standards for names of different object types. PEP 8 includes the following recommendations:

  • Snake Case should be used for functions and variable names.
  • Pascal Case should be used for class names. (PEP 8 refers to this as the “CapWords” convention.)

There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.

In Python 3.6, there are 33 reserved keywords:

Python
Keywords
     

You can see this list any time by typing help("keywords") to the Python interpreter. Reserved words are case-sensitive and must be used exactly as shown. They are all entirely lowercase, except for False , None , and True .

Trying to create a variable with the same name as any reserved word results in an error:

This tutorial covered the basics of Python variables , including object references and identity, and naming of Python identifiers.

You now have a good understanding of some of Python’s data types and know how to create variables that reference objects of those types.

Next, you will see how to combine data objects into expressions involving various operations .

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About John Sturtz

John Sturtz

John is an avid Pythonista and a member of the Real Python tutorial team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Variables in Python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Python 3 Cheat Sheet (PDF)

🔒 No spam. We take your privacy seriously.

variable assignment vs declaration

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Initialization, declaration and assignment terms in Java

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

You must declare all variables before they can be used. Following is the basic form of a variable declaration − data type variable [ = value][, variable [ = value] ...] ;

Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

Following are valid examples of variable declaration and initialization in Java −

Arushi

Related Articles

  • Explain the variable declaration, initialization and assignment in C language
  • What is the difference between initialization and assignment of values in C#?
  • Difference between Definition and Declaration in Java.
  • Double brace initialization in Java
  • A static initialization block in Java
  • Compound assignment operators in Java\n
  • Rules For Variable Declaration in Java
  • A non-static initialization block in Java
  • Java variable declaration best practices
  • Interesting facts about Array assignment in Java
  • Class declaration with one method in Java
  • Reference static field after declaration in Java
  • Is there a difference between copy initialization and direct initialization in C++?
  • Can we declare final variables without initialization in java?
  • Trademark Assignment and Licensing

Kickstart Your Career

Get certified by completing the course

Was this page helpful?

Variable Declaration

let and const are two relatively new concepts for variable declarations in JavaScript. As we mentioned earlier , let is similar to var in some respects, but allows users to avoid some of the common “gotchas” that users run into in JavaScript.

const is an augmentation of let in that it prevents re-assignment to a variable.

With TypeScript being an extension of JavaScript, the language naturally supports let and const . Here we’ll elaborate more on these new declarations and why they’re preferable to var .

If you’ve used JavaScript offhandedly, the next section might be a good way to refresh your memory. If you’re intimately familiar with all the quirks of var declarations in JavaScript, you might find it easier to skip ahead.

var declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword.

As you might’ve figured out, we just declared a variable named a with the value 10 .

We can also declare a variable inside of a function:

and we can also access those same variables within other functions:

In this above example, g captured the variable a declared in f . At any point that g gets called, the value of a will be tied to the value of a in f . Even if g is called once f is done running, it will be able to access and modify a .

Scoping rules

var declarations have some odd scoping rules for those used to other languages. Take the following example:

Some readers might do a double-take at this example. The variable x was declared within the if block , and yet we were able to access it from outside that block. That’s because var declarations are accessible anywhere within their containing function, module, namespace, or global scope - all which we’ll go over later on - regardless of the containing block. Some people call this var -scoping or function-scoping . Parameters are also function scoped.

These scoping rules can cause several types of mistakes. One problem they exacerbate is the fact that it is not an error to declare the same variable multiple times:

Maybe it was easy to spot out for some experienced JavaScript developers, but the inner for -loop will accidentally overwrite the variable i because i refers to the same function-scoped variable. As experienced developers know by now, similar sorts of bugs slip through code reviews and can be an endless source of frustration.

Variable capturing quirks

Take a quick second to guess what the output of the following snippet is:

For those unfamiliar, setTimeout will try to execute a function after a certain number of milliseconds (though waiting for anything else to stop running).

Ready? Take a look:

Many JavaScript developers are intimately familiar with this behavior, but if you’re surprised, you’re certainly not alone. Most people expect the output to be

Remember what we mentioned earlier about variable capturing? Every function expression we pass to setTimeout actually refers to the same i from the same scope.

Let’s take a minute to consider what that means. setTimeout will run a function after some number of milliseconds, but only after the for loop has stopped executing; By the time the for loop has stopped executing, the value of i is 10 . So each time the given function gets called, it will print out 10 !

A common work around is to use an IIFE - an Immediately Invoked Function Expression - to capture i at each iteration:

This odd-looking pattern is actually pretty common. The i in the parameter list actually shadows the i declared in the for loop, but since we named them the same, we didn’t have to modify the loop body too much.

let declarations

By now you’ve figured out that var has some problems, which is precisely why let statements were introduced. Apart from the keyword used, let statements are written the same way var statements are.

The key difference is not in the syntax, but in the semantics, which we’ll now dive into.

Block-scoping

When a variable is declared using let , it uses what some call lexical-scoping or block-scoping . Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for -loop.

Here, we have two local variables a and b . a ’s scope is limited to the body of f while b ’s scope is limited to the containing if statement’s block.

Variables declared in a catch clause also have similar scoping rules.

Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared. While these variables are “present” throughout their scope, all points up until their declaration are part of their temporal dead zone . This is just a sophisticated way of saying you can’t access them before the let statement, and luckily TypeScript will let you know that.

Something to note is that you can still capture a block-scoped variable before it’s declared. The only catch is that it’s illegal to call that function before the declaration. If targeting ES2015, a modern runtime will throw an error; however, right now TypeScript is permissive and won’t report this as an error.

For more information on temporal dead zones, see relevant content on the Mozilla Developer Network .

Re-declarations and Shadowing

With var declarations, we mentioned that it didn’t matter how many times you declared your variables; you just got one.

In the above example, all declarations of x actually refer to the same x , and this is perfectly valid. This often ends up being a source of bugs. Thankfully, let declarations are not as forgiving.

The variables don’t necessarily need to both be block-scoped for TypeScript to tell us that there’s a problem.

That’s not to say that a block-scoped variable can never be declared with a function-scoped variable. The block-scoped variable just needs to be declared within a distinctly different block.

The act of introducing a new name in a more nested scope is called shadowing . It is a bit of a double-edged sword in that it can introduce certain bugs on its own in the event of accidental shadowing, while also preventing certain bugs. For instance, imagine we had written our earlier sumMatrix function using let variables.

This version of the loop will actually perform the summation correctly because the inner loop’s i shadows i from the outer loop.

Shadowing should usually be avoided in the interest of writing clearer code. While there are some scenarios where it may be fitting to take advantage of it, you should use your best judgement.

Block-scoped variable capturing

When we first touched on the idea of variable capturing with var declaration, we briefly went into how variables act once captured. To give a better intuition of this, each time a scope is run, it creates an “environment” of variables. That environment and its captured variables can exist even after everything within its scope has finished executing.

Because we’ve captured city from within its environment, we’re still able to access it despite the fact that the if block finished executing.

Recall that with our earlier setTimeout example, we ended up needing to use an IIFE to capture the state of a variable for every iteration of the for loop. In effect, what we were doing was creating a new variable environment for our captured variables. That was a bit of a pain, but luckily, you’ll never have to do that again in TypeScript.

let declarations have drastically different behavior when declared as part of a loop. Rather than just introducing a new environment to the loop itself, these declarations sort of create a new scope per iteration . Since this is what we were doing anyway with our IIFE, we can change our old setTimeout example to just use a let declaration.

and as expected, this will print out

const declarations

const declarations are another way of declaring variables.

They are like let declarations but, as their name implies, their value cannot be changed once they are bound. In other words, they have the same scoping rules as let , but you can’t re-assign to them.

This should not be confused with the idea that the values they refer to are immutable .

Unless you take specific measures to avoid it, the internal state of a const variable is still modifiable. Fortunately, TypeScript allows you to specify that members of an object are readonly . The chapter on Interfaces has the details.

let vs. const

Given that we have two types of declarations with similar scoping semantics, it’s natural to find ourselves asking which one to use. Like most broad questions, the answer is: it depends.

Applying the principle of least privilege , all declarations other than those you plan to modify should use const . The rationale is that if a variable didn’t need to get written to, others working on the same codebase shouldn’t automatically be able to write to the object, and will need to consider whether they really need to reassign to the variable. Using const also makes code more predictable when reasoning about flow of data.

Use your best judgement, and if applicable, consult the matter with the rest of your team.

The majority of this handbook uses let declarations.

Destructuring

Another ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network . In this section, we’ll give a short overview.

Array destructuring

The simplest form of destructuring is array destructuring assignment:

This creates two new variables named first and second . This is equivalent to using indexing, but is much more convenient:

Destructuring works with already-declared variables as well:

And with parameters to a function:

You can create a variable for the remaining items in a list using the syntax ... :

Of course, since this is JavaScript, you can just ignore trailing elements you don’t care about:

Or other elements:

Tuple destructuring

Tuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements:

It’s an error to destructure a tuple beyond the range of its elements:

As with arrays, you can destructure the rest of the tuple with ... , to get a shorter tuple:

Or ignore trailing elements, or other elements:

Object destructuring

You can also destructure objects:

This creates new variables a and b from o.a and o.b . Notice that you can skip c if you don’t need it.

Like array destructuring, you can have assignment without declaration:

Notice that we had to surround this statement with parentheses. JavaScript normally parses a { as the start of block.

You can create a variable for the remaining items in an object using the syntax ... :

Property renaming

You can also give different names to properties:

Here the syntax starts to get confusing. You can read a: newName1 as ” a as newName1 ”. The direction is left-to-right, as if you had written:

Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring:

Default values

Default values let you specify a default value in case a property is undefined:

In this example the b? indicates that b is optional, so it may be undefined . keepWholeObject now has a variable for wholeObject as well as the properties a and b , even if b is undefined.

Function declarations

Destructuring also works in function declarations. For simple cases this is straightforward:

But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the pattern before the default value.

The snippet above is an example of type inference, explained earlier in the handbook.

Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that C was defined with b optional:

Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expression is confusing. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself.

The spread operator is the opposite of destructuring. It allows you to spread an array into another array, or an object into another object. For example:

This gives bothPlus the value [0, 1, 2, 3, 4, 5] . Spreading creates a shallow copy of first and second . They are not changed by the spread.

You can also spread objects:

Now search is { food: "rich", price: "$$", ambiance: "noisy" } . Object spreading is more complex than array spreading. Like array spreading, it proceeds from left-to-right, but the result is still an object. This means that properties that come later in the spread object overwrite properties that come earlier. So if we modify the previous example to spread at the end:

Then the food property in defaults overwrites food: "rich" , which is not what we want in this case.

Object spread also has a couple of other surprising limits. First, it only includes an objects’ own, enumerable properties . Basically, that means you lose methods when you spread instances of an object:

Second, the TypeScript compiler doesn’t allow spreads of type parameters from generic functions. That feature is expected in future versions of the language.

using declarations

using declarations are an upcoming feature for JavaScript that are part of the Stage 3 Explicit Resource Management proposal. A using declaration is much like a const declaration, except that it couples the lifetime of the value bound to the declaration with the scope of the variable.

When control exits the block containing a using declaration, the [Symbol.dispose]() method of the declared value is executed, which allows that value to perform cleanup:

At runtime, this has an effect roughly equivalent to the following:

using declarations are extremely useful for avoiding memory leaks when working with JavaScript objects that hold on to native references like file handles

or scoped operations like tracing

Unlike var , let , and const , using declarations do not support destructuring.

null and undefined

It’s important to note that the value can be null or undefined , in which case nothing is disposed at the end of the block:

which is roughly equivalent to:

This allows you to conditionally acquire resources when declaring a using declaration without the need for complex branching or repetition.

Defining a disposable resource

You can indicate the classes or objects you produce are disposable by implementing the Disposable interface:

await using declarations

Some resources or operations may have cleanup that needs to be performed asynchronously. To accommodate this, the Explicit Resource Management proposal also introduces the await using declaration:

An await using declaration invokes, and awaits , its value’s [Symbol.asyncDispose]() method as control leaves the containing block. This allows for asynchronous cleanup, such as a database transaction performing a rollback or commit, or a file stream flushing any pending writes to storage before it is closed.

As with await , await using can only be used in an async function or method, or at the top level of a module.

Defining an asynchronously disposable resource

Just as using relies on objects that are Disposable , an await using relies on objects that are AsyncDisposable :

await using vs await

The await keyword that is part of the await using declaration only indicates that the disposal of the resource is await -ed. It does not await the value itself:

await using and return

It’s important to note that there is a small caveat with this behavior if you are using an await using declaration in an async function that returns a Promise without first await -ing it:

Because the returned promise isn’t await -ed, it’s possible that the JavaScript runtime may report an unhandled rejection since execution pauses while await -ing the asynchronous disposal of x , without having subscribed to the returned promise. This is not a problem that is unique to await using , however, as this can also occur in an async function that uses try..finally :

To avoid this situation, it is recommended that you await your return value if it may be a Promise :

using and await using in for and for..of statements

Both using and await using can be used in a for statement:

In this case, the lifetime of x is scoped to the entire for statement and is only disposed when control leaves the loop due to break , return , throw , or when the loop condition is false.

In addition to for statements, both declarations can also be used in for..of statements:

Here, x is disposed at the end of each iteration of the loop , and is then reinitialized with the next value. This is especially useful when consuming resources produced one at a time by a generator.

using and await using in older runtimes

using and await using declarations can be used when targeting older ECMAScript editions as long as you are using a compatible polyfill for Symbol.dispose / Symbol.asyncDispose , such as the one provided by default in recent editions of NodeJS.

Nightly Builds

How to use a nightly build of TypeScript

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Daniel Rosenwasser  (58)

Last updated: Jun 28, 2024  

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Why declare a variable in one line, and assign to it in the next?

I often see in C and C++ code the following convention:

I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I've learned not to dismiss so quickly the habits of veteran developers. So, is there a good reason for declaring in one line, and assigning afterwards?

Robert Harvey's user avatar

  • 15 +1 for "I've learned not to dismiss so quickly the habits of veteran developers." That's a wise lesson to learn. –  Wildcard Commented Nov 30, 2015 at 15:56

7 Answers 7

In C89 all declarations had to be be at the beginning of a scope ( { ... } ), but this requirement was dropped quickly (first with compiler extensions and later with the standard).

These examples are not the same. some_type val = something; calls the copy constructor while val = something; calls the default constructor and then the operator= function. This difference is often critical.

Some people prefer to first declare variables and later define them, in the case they are reformatting their code later with the declarations in one spot and the definition in an other.

About the pointers, some people just have the habit to initialize every pointer to NULL or nullptr , no matter what they do with that pointer.

orlp's user avatar

  • 1 Great distinction for C++, thanks. What about in plain C? –  Jonathan Sterling Commented May 7, 2011 at 20:35
  • 13 The fact that MSVC still doesn't support declarations except at the beginning of a block when it's compiling in C mode is the source of endless irritation for me. –  Michael Burr Commented May 7, 2011 at 22:03
  • 5 @Michael Burr: This is because MSVC doesn't support C99 at all. –  orlp Commented May 7, 2011 at 22:05
  • 4 "some_type val = something; calls the copy constructor": it may call the copy constructor, but the Standard allows the compiler to elide the default-construction of a tempory, copy construction of val and destruction of the temporary and directly construct val using a some_type constructor taking something as sole argument. This is a very interesting and unusual edge case in C++... it means there's a presumption about the semantic meaning of these operations. –  Tony Commented May 9, 2011 at 9:15
  • 2 @Aerovistae: for built-in types they are the same, but the same can not always be said for user-defined types. –  orlp Commented Oct 11, 2012 at 18:48

You have tagged your question C and C++ at the same time, while the answer is significantly different in these languages.

Firstly, the wording of the title of your question is incorrect (or, more precisely, irrelevant to the question itself). In both of your examples the variable is declared and defined simultaneously, in one line. The difference between your examples is that in the first one the variables are either left uninitialized or initialized with a dummy value and then it is assigned a meaningful value later. In the second example the variables are initialized right away.

Secondly, in C++ language, as @nightcracker noted in his answer these two constructs are semantically different. The first one relies on initialization while the second one - on assignment. In C++ these operations are overloadable and therefore can potentially lead to different results (although one can note that producing non-equivalent overloads of initialization and assignment is not a good idea).

In the original standard C language (C89/90) it is illegal to declare variables in the middle of the block, which is why you might see variables declared uninitialized (or initialized with dummy values) at the beginning of the block and then assigned meaningful values later, when those meaningful values become available.

In C99 language it is OK to declare variables in the middle of the block (just like in C++), which means that the first approach is only needed in some specific situations when the initializer is not known at the point of declaration. (This applies to C++ as well).

AnT stands with Russia's user avatar

  • 2 @Jonathan Sterling: I read your examples. You probably need to brush up on the standard terminology of C and C++ languages. Specifically, on the terms declaration and definition , which have specific meanings in these languages. I'll repeat it again: in both of your examples the variables are declared and defined in one line. In C/C++ the line some_type val; immediately declares and defines the variable val . This is what I meant in my answer. –  AndreyT Commented May 7, 2011 at 20:53
  • 1 I see what you mean there. You're definitely right about declare and define being rather meaningless the way I used them. I hope you accept my apologies for the poor wording, and poorly-thought-out comment. –  Jonathan Sterling Commented May 7, 2011 at 20:55
  • 1 So, if the consensus is that “declare” is the wrong word, I'd suggest that someone with a better knowledge of the standard than me edit the Wikibooks page. –  Jonathan Sterling Commented May 7, 2011 at 21:11
  • 2 In any other context declare would be the right word, but since declare is a well-defined concept , with consequences, in C and C++ you can not use it as loosely as you could in other contexts. –  orlp Commented May 7, 2011 at 21:15
  • 2 @ybungalobill: You are wrong. Declaration and definition in C/C++ is not mutually exclusive concepts. Actually, definition is just a specific form of declaration . Every definition is a declaration at the same time (with few exceptions). There are defining declarations (i.e. definitions) and non-defining declarations. Moreover, normally the therm declaration is used all the time (even if it is a definition), except for the contexts when the distinction between the two is critical. –  AndreyT Commented May 7, 2011 at 21:52

I think it's an old habit, leftover from "local declaration" times. And therefore as answer to your question: No I don't think there's a good reason. I never do it myself.

I said something about that in my answer to a question by Helium3 .

Basically, I say it's a visual aid to easily see what is changed.

Community's user avatar

The other answers are pretty good. There's some history around this in C. In C++ there's the difference between a constructor and an assignment operator.

I'm surprised no one mentions the additional point: keeping declarations separate from use of a variable can sometimes be a lot more readable.

Visually speaking, when reading code, the more mundane artifacts, such as the types and names of variables, are not what jump out at you. It's the statements that you're usually most interested in, spend most time staring at, and so there's a tendency to glance over the rest.

If I have some types, names, and assignment all going on in the same tight space, it's a bit of information overload. Further, it means that something important is going on in the space that I usually glance over.

It may seem a bit counter-intuitive to say, but this is one instance where making your source take up more vertical space can make it better. I see this as akin to why you shouldn't write jam-packed lines which do crazy amounts of pointer arithmetic and assignment in a tight vertical space -- just because the language lets you get away with such things doesn't mean you should do it all the time. :-)

asveikau's user avatar

In C, this was the standard practice because variables had to be declared at the start of the function, unlike in C++, where it could be declared anywhere in the function body to be used thereafter. Pointers were set to 0 or NULL, because it just made sure that the pointer pointed to no garbage. Otherwise, there's no significant advantage that I can think of, which compels anyone to do like that.

Vite Falcon's user avatar

Pros for localising variable definitions and their meaningful initialisation:

if variables are habitually assigned a meaningful value when they first appear in the code (another perspective on the same thing: you delay their appearance until a meaningful value is avaialable) then there's no chance of them accidentally being used with a meaningless or uninitialised value (which can easily happen is some initialisation is accidentally bypassed due to conditional statements, short-circuit evaluation, exceptions etc.)

can be more efficient

  • avoids overheads of setting initial value (default construction or initialisation to some sentinel value like NULL)
  • operator= can sometimes be less efficient and require a temporary object
  • sometimes (esp. for inline functions) the optimiser can remove some/all inefficiencies

minimising the scope of variables in turn minimises average number of variables concurrently in scope : this

  • makes it easier to mentally track the variables in scope, the execution flows and statements that might affect those variables, and the import of their value
  • at least for some complex and opaque objects, this reduces resource usage (heap, threads, shared memory, descriptors) of the program

sometimes more concise as you're not repeating the variable name in a definition then in an initial meaningful assignment

necessary for certain types such as references and when you want the object to be const

Arguments for grouping variable definitions:

sometimes it's convenient and/or concise to factor out the type of a number of variables:

the_same_type v1, v2, v3;

(if the reason is just that the type name is overly long or complex, a typedef can sometimes be better)

sometimes it's desirable to group variables independently of their usage to emphasise the set of variables (and types) involved in some operation:

type v1; type v2; type v3;

This emphasises the commonality of type and makes it a little easier to change them, while still sticking to a variable per line which facilitates copy-paste, // commenting etc..

As is often the case in programming, while there can be a clear empirical benefit to one practice in most situations, the other practice really can be overwhelmingly better in a few cases.

Tony's user avatar

  • I wish more languages would distinguish the case where code declares and sets the value of a variable which would never be written elsewhere, though new variables could use the same name [i.e. where behavior would be the same whether the later statements used the same variable or a different one], from those where code creates a variable that must be writable in multiple places. While both use cases will execute the same way, knowing when variables may change is very helpful when trying to track down bugs. –  supercat Commented Apr 28, 2014 at 22:50

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • Are there examples of triple entendres in English?
  • Google Search Console reports "Page with redirect" as "errors", are they?
  • Is there any other reason to stockpile minerals aside preparing for war?
  • Was Paul's Washing in Acts 9:18 a Ritual Purification Rather Than a Christian Baptism?
  • Is the FOCAL syntax for Alphanumeric Numbers ("0XYZ") documented anywhere?
  • How will the ISS be decommissioned?
  • Are Dementors found all over the world, or do they only reside in or near Britain?
  • How to bid a very strong hand with values in only 2 suits?
  • Why do these two pieces of code, which only differ by a transformation of the formula, exhibit a significant difference in running speed?
  • Cathay Pacific Online Booking: When to Enter Passport Details?
  • How to Pick Out Strings of a Specified Length
  • What is the term for when a hyperlink maliciously opens different URL from URL displayed when hovered over?
  • Is it this limit impossible or not exists?
  • Summation of arithmetic series
  • Why was the animal "Wolf" used in the title "The Wolf of Wall Street (2013)"?
  • Folk stories and notions in mathematics that are likely false, inaccurate, apocryphal, or poorly founded?
  • Rear shifter cable wont stay in anything but the highest gear
  • Does this double well potential contradict the fact that there is no degeneracy for one-dimensional bound states?
  • Viewport Shader Render different from 1 computer to another
  • Correlation for Small Dataset?
  • Why potential energy is not considered in the internal energy of diatomic molecules?
  • How can I take apart a bookshelf?
  • SMTP Header confusion - Delivered-To: and To: are different
  • Have children's car seats not been proven to be more effective than seat belts alone for kids older than 24 months?

variable assignment vs declaration

Julian Kühnel

Quick Tip: How to Declare Variables in JavaScript

Share this article

code on a screen

Difference between Declaration, Initialization and Assignment

Declaration types, accidental global creation, hoisting and the temporal dead zone, frequently asked questions (faqs) about javascript variable declaration.

When learning JavaScript one of the basics is to understand how to use variables. Variables are containers for values of all possible types, e.g. number, string or array (see data types ). Every variable gets a name that can later be used inside your application (e.g. to read its value).

In this quick tip you’ll learn how to use variables and the differences between the various declarations.

Before we start learning the various declarations, lets look at the lifecycle of a variable.

Variable lifecycle flowchart

  • Declaration : The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).
  • Initialization : When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.
  • Assignment : This is when a specific value is assigned to the variable.
Note : while var has been available in JavaScript since its initial releast, let and const are only available in ES6 (ES2015) and up. See this page for browser compatibility.

This declaration is probably the most popular, as there was no alternative until ECMAScript 6 . Variables declared with var are available in the scope of the enclosing function. If there is no enclosing function, they are available globally.

This will cause an error ReferenceError: hello is not defined , as the variable hello is only available within the function sayHello . But the following will work, as the variable will be declared globally – in the same scope console.log(hello) is located:

let is the descendant of var in modern JavaScript. Its scope is not only limited to the enclosing function, but also to its enclosing block statement. A block statement is everything inside { and } , (e.g. an if condition or loop). The benefit of let is it reduces the possibility of errors, as variables are only available within a smaller scope.

This will cause an error ReferenceError: hello is not defined as hello is only available inside the enclosing block – in this case the if condition. But the following will work:

Technically a constant isn’t a variable. The particularity of a constant is that you need to assign a value when declaring it and there is no way to reassign it. A const is limited to the scope of the enclosing block, like let .

Constants should be used whenever a value must not change during the applications running time, as you’ll be notified by an error when trying to overwrite them.

You can write all of above named declarations in the global context (i.e. outside of any function), but even within a function, if you forget to write var , let or const before an assignment, the variable will automatically be global.

The above will output Hello World to the console, as there is no declaration before the assignment hello = and therefore the variable is globally available.

Note: To avoid accidentally declaring global variables you can use strict mode .

Another difference between var and let / const relates to variable hoisting . A variable declaration will always internally be hoisted (moved) to the top of the current scope. This means the following:

is equivalent to:

An indication of this behavior is that both examples will log undefined to the console. If var hello; wouldn’t always be on the top it would throw a ReferenceError .

This behavior called hoisting applies to var and also to let / const . As mentioned above, accessing a var variable before its declaration will return undefined as this is the value JavaScript assigns when initializing it.

But accessing a let / const variable before its declaration will throw an error. This is due to the fact that they aren’t accessible before their declaration in the code. The period between entering the variable’s scope and reaching their declaration is called the Temporal Dead Zone – i.e. the period in which the variable isn’t accessible.

You can read more about hoisting in the article Demystifying JavaScript Variable Scope and Hoisting .

To reduce susceptibility to errors you should use const and let whenever possible. If you really need to use var then be sure to move declarations to the top of the scope, as this avoids unwanted behavior related to hoisting.

What is the difference between variable declaration and initialization in JavaScript?

In JavaScript, variable declaration and initialization are two distinct steps in the process of using variables. Declaration is the process of introducing a new variable to the program. It’s done using the var, let, or const keywords. For example, let x; Here, x is declared but not defined. It’s like telling the program, “Hey, I’m going to use a variable named x.” Initialization, on the other hand, is the process of assigning a value to the declared variable for the first time. For example, x = 5; Here, x is initialized with the value 5. It’s like telling the program, “The variable x I told you about earlier? It’s value is 5.”

Can I declare a variable without initializing it in JavaScript?

Yes, in JavaScript, you can declare a variable without initializing it. When you declare a variable without assigning a value to it, JavaScript automatically assigns it the value of undefined. For example, if you declare a variable like this: let x; and then try to log x to the console, you’ll get undefined because x has been declared but not initialized.

What happens if I use a variable without declaring it in JavaScript?

In JavaScript, if you use a variable without declaring it first, you’ll get a ReferenceError. This is because JavaScript needs to know about a variable before it can be used. If you try to use a variable that hasn’t been declared, JavaScript doesn’t know what you’re referring to and throws an error. For example, if you try to log x to the console without declaring x first, you’ll get a ReferenceError: x is not defined.

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

In JavaScript, var, let, and const are all used to declare variables, but they have different behaviors. var is function-scoped, meaning a variable declared with var is available within the function it’s declared in. let and const are block-scoped, meaning they’re only available within the block they’re declared in. Additionally, const is used to declare constants, or variables that can’t be reassigned after they’re initialized.

Can I redeclare a variable in JavaScript?

In JavaScript, whether you can redeclare a variable depends on how you initially declared it. If you declared a variable with var, you can redeclare it. However, if you declared a variable with let or const, you can’t redeclare it within the same scope. Attempting to do so will result in a SyntaxError.

What is hoisting in JavaScript?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This means that you can use variables and functions before they’re declared. However, only the declarations are hoisted, not initializations. If a variable is declared and initialized after using it, the variable will be undefined.

What is the scope of a variable in JavaScript?

The scope of a variable in JavaScript determines where that variable can be accessed from within your code. Variables declared with var have function scope, meaning they can be accessed anywhere within the function they’re declared in. Variables declared with let and const have block scope, meaning they can only be accessed within the block they’re declared in.

What is the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both special values that represent the absence of a value. However, they’re used in slightly different ways. undefined is the value assigned to a variable that has been declared but not initialized. null, on the other hand, is a value that represents no value or no object. It needs to be assigned to a variable explicitly.

Can I use special characters in variable names in JavaScript?

In JavaScript, variable names can include letters, digits, underscores, and dollar signs. They must begin with a letter, underscore, or dollar sign. Special characters like !, @, #, %, etc., are not allowed in variable names.

What is a global variable in JavaScript?

A global variable in JavaScript is a variable that’s declared outside of any function or block. Because it’s not tied to a function or block, a global variable can be accessed from anywhere in your code. However, global variables can lead to issues with naming conflicts and are generally best avoided when possible.

Julian is a passionate software developer currently focusing on frontend technologies and loves open source.

SitePoint Premium

JS Tutorial

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

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • Using const

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

They are automatically declared when first used:

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

From the examples you can guess:

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

Example using var

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

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

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

Example using let

Example using const, mixed example.

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

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

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

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

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

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

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

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

Variables are containers for storing values.

Advertisement

JavaScript Identifiers

All JavaScript variables must be identified with unique names .

These unique names are called identifiers .

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

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

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

JavaScript identifiers are case-sensitive.

The Assignment Operator

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

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

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

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

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

JavaScript Data Types

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

In programming, text values are called text strings.

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

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

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

Declaring a JavaScript Variable

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

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

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

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

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

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

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

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

One Statement, Many Variables

You can declare many variables in one statement.

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

A declaration can span multiple lines:

Value = undefined

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

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

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

Re-Declaring JavaScript Variables

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

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

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

This will not work:

JavaScript Arithmetic

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

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

Also try this:

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

Now try this:

JavaScript Dollar Sign $

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

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

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

JavaScript Underscore (_)

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

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

Test Yourself With Exercises

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

  • Site Feedback

variable assignment in declaration

Question and answer.

Tom Kyte

Thanks for the question, Steve.

Asked: March 17, 2005 - 9:51 am UTC

Last updated: March 18, 2005 - 8:03 am UTC

Version: 9.2.0.6

and Tom said...

Beware exceptions.

Alberto Dell'Era, March 17, 2005 - 2:33 pm UTC

Difference in exception handling

Scot, March 17, 2005 - 2:47 pm UTC

Hey...yeah...what Alberto said

Scot, March 17, 2005 - 2:50 pm UTC

Good to know.

Steve, March 17, 2005 - 3:26 pm UTC

:= vs. default

Matthias Rogel, March 18, 2005 - 2:37 am UTC

Steve, March 18, 2005 - 8:03 am UTC

more

More to Explore

Pl/sql demos.

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library

Expressions, declarations and statements

Expressions.

An expression is a sequence where operators or function calls are applied to operands (variables or values) to define the calculations and actions required by the script. Expressions in Pine almost always produce a result (exceptions are the functions study , fill , strategy.entry , etc., which produce side effects and will be covered later).

Here are some examples of simple expressions:

Variable declaration

Variables in Pine are declared with the special symbol = and an optional var keyword in one of the following ways:

<identifier> is the name of the declared variable, see Identifiers .

<type> can be one of the predefined keywords: float , int , bool , color , string , line or label . However, in most cases, an explicit type declaration is redundant because type is automatically inferred from the <expression> on the right of the = at compile time, so the decision to use them is often a matter of preference. For example:

In the first line of the example, the compiler cannot determine the type of the baseLine0 variable because na is a generic value of no particular type. The declaration of the baseLine1 variable is correct because its float type is declared explicitly. The declaration of the baseLine2 variable is also correct because its type can be derived from the expression float(na) , which is an explicit cast of na value to float type. The declarations of baseLine1 and baseLine2 are equivalent.

The var keyword is a special modifier that instructs the compiler to create and initialize the variable only once . This behavior is very useful in cases where a variable’s value must persist through the iterations of a script across successive bars. For example, suppose we’d like to count the number of green bars on the chart:

image

Without the var modifier, variable count would be reset to zero (thus losing it’s value) every time a new bar update triggered a script recalculation.

In Pine v3 the study “Green Bars Count” could be written without using the var keyword:

The v4 code is more readable and can be more efficient if, for example, the count variable is initialized with an expensive function call instead of 0 .

Examples of simple variable declarations:

Examples with type modifiers and var keyword:

Example, illustrating the effect of var keyword:

Variable assignment

A mutable variable is a variable which can be given a new value. The operator := must be used to give a new value to a variable. A variable must be declared before you can assign a value to it (see declaration of variables above ).

The type of a variable is identified at declaration time. From then on, a variable can be given a value of expression only if both the expression and the variable belong to the same type, otherwise a compilation error will occur.

Variable assignment example:

if statement

An if statement defines a block of statements to be executed when the if ’s conditional expression evaluates to true , and optionally, an alternative block to be executed when the expression is false .

General code form:

  • var_declarationX - this variable is assigned the value of the if statement as a whole.
  • condition - if the condition expression is true, the logic from the then block immediately following the if first line ( var_decl_then0 , var_decl_then1 , etc.) is used, if the condition is false, the logic from the else block ( var_decl_else0 , var_decl_else1 , etc.) is used.
  • return_expression_then , return_expression_else - the last expression from the then block or from the else block will determine the final value of the whole if statement.

The type of the returning value of the if statement is determined by the type of return_expression_then and return_expression_else . Their types must match. It is not possible to return an integer value from the then block if the else block returns a string value.

It is possible to omit the else block. In this case, if the condition is false, an empty value ( na , false , or "" ) will be assigned to the var_declarationX variable.

It is possible to use either multiple else if blocks or none at all.

The then , else if and else blocks are shifted by four spaces 1 . if statements can be nested by adding four more spaces:

It is possible and quite frequent to ignore the resulting value of an if statement ( var_declarationX = can be omited). This form is used when you need the side effect of the expression, for example in `strategy trading:

for statement

The for statement allows to execute a number of instructions repeatedly:

  • i - a loop counter variable.
  • from - start value of the counter.
  • to - end value of the counter. When the counter becomes greater than to (or less than to in the case where from > to ) the loop is stopped.
  • step - loop step. Optional. Default is 1. If from is greater than to , the loop step will automatically change direction; no need to use a negative step.
  • var_decl0 , … var_declN , return_expression - body of the loop. It must be indented by 4 spaces.
  • return_expression - returning value. When a loop is finished or broken, the returning value is assigned to var_declarationX .
  • continue - a keyword. Can only be used in loops. It jumps to the loop’s next iteration.
  • break - a keyword. Can be used only in loops. It exits the loop.

for loop example:

Variable sum is a mutable variable so a new value can be given to it by the operator := in the loop’s body. Note that we recommend using the built-in sma() function for simple moving averages, as it calculates faster.

Note that some built-in functions may behave unexpectedly in for loop. Let’s look at the following example:

While you may expect that sum will contain rma(close, 1) + rma(close, 2) , this is not so. It will contain rma(close, 1) + rma(close, 1) because once rma is initialized with length 1, this length is stored until the script is removed from chart. To avoid this you may use your own, stateless function implementation. This is the list of built-in functions which have the same behavior:

  • rma(source, length) : length is stateful.
  • ema(source, length) : length is stateful.
  • valuewhen(condition, source, occurrence) : occurrence is stateful.
  • rsi(x, y) : when y is of type integer and behaves like a length, y is stateful.

TradingView’s Pine Editor automatically replaces Tab with 4 spaces. ↩

Functions and annotations

Declaring functions.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

How to assign a value to a variable in a Django template?

e.g., given this template:

While testing it, it would be useful to define the value of the variable without touching the python code that invokes this template. So I'm looking for something like this

Does something like this exist in Django?

  • django-templates

Rob Bednark's user avatar

9 Answers 9

You can use the with template tag.

John's user avatar

  • 64 but can you change the variable's value in the with? –  David 天宇 Wong Commented Feb 16, 2014 at 10:31
  • 4 It seems you cannot declare a container (I've tried list and tuple) in a with clause –  Vladislav Ivanishin Commented Mar 18, 2015 at 1:58
  • 1 If you need to declare a list, use make_list. docs.djangoproject.com/en/1.9/ref/templates/builtins/#make-list –  MrValdez Commented Jul 1, 2016 at 7:55
  • 4 Jinja says it's {% set myvar=value %} why it doesn't work in django? –  holms Commented Mar 10, 2018 at 1:08
  • 15 @holms Because Django doesn't use Jinja :-) docs.djangoproject.com/en/1.7/topics/templates –  elimisteve Commented May 12, 2018 at 0:04

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py , views.py , etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.

Then in your template you can assign values to the context like this:

John R Perry's user avatar

  • 4 in my case after loop this returns old value :( –  holms Commented Mar 13, 2018 at 9:46
  • 8 In the latest version it appears that you can use simple_tag instead of assignment_tag (and it worked for me). –  Katharine Osborne Commented Mar 13, 2018 at 19:44
  • Issue I got with this solution is that it appears, that you cannot override values. –  Jakub Jabłoński Commented Mar 13, 2020 at 15:57
  • 1 if you want to use this technique to set a list instead of just a value, check this: stackoverflow.com/a/34407158/2193235 –  msb Commented Jun 13, 2020 at 1:45
  • 2 if you are setting the variable as an integer and you want to increment it (for example), you need to use add : {% define counter|add:1 as counter %} . Similarly for other operations. –  msb Commented Jun 13, 2020 at 1:47

An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

This will allow you to write something like this in your template:

Note that most of this was taken from here

Lundis's user avatar

  • How about assigning variables to other variables present in the context? And on a different note: allowing templates to arbitrarily assign context variables without checking if they exist already may have security implications. A more sensible approach in my opinion would be to check the context for the variable before attempting to assign it: –  user656208 Commented Aug 7, 2015 at 11:49
  • if context.get(self.var_name): raise SuspiciousOperation("Attempt to assign variable from template already present in context") –  user656208 Commented Aug 7, 2015 at 11:50

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates ). Because of this, the recommended way to change any variable is via touching the Python code.

djvg's user avatar

  • 8 Thanks for the pointer. From a perspective of a designer is it sometimes easier to quickly set a variable to test various states of a page while designing it. Not suggesting this practice to be used in a running code. –  Alexis Commented Jul 1, 2009 at 22:21
  • 3 the "with" tag is accepted in django1.0. So looks like they are finally amending their philosophy :). –  Evgeny Commented Dec 20, 2009 at 19:35
  • 4 As a matter of facts, the "with" tag is just for aliases. This may have a huge impact on performance (and on readability as well!) but it is not really setting a variable in traditional programming terms. –  rob Commented Dec 20, 2009 at 23:48

The best solution for this is to write a custom assignment_tag . This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/hello_world.py ):

Now you may use the get_addressee template tag in your templates:

Mr. Lance E Sloan's user avatar

  • 6 For folks using the newer Django versions, its called simple_tag now! Save the time to figure out why "register.." is not recognized in your code... –  kaya Commented Sep 1, 2018 at 9:25

Perhaps the default template filter wasn't an option back in 2009...

John Mee's user avatar

  • I must say that this is what I was looking! It can be also be used with with : {% with state=form.state.value|default:other_context_variable %} instead of other_context_variable we can also use any 'string_value' as well –  Saurav Kumar Commented Feb 7, 2018 at 9:48
  • But it will print it, and I need to save it for later use –  holms Commented Mar 10, 2018 at 1:18

Use the with statement .

I can't imply the code in first paragraph in this answer . Maybe the template language had deprecated the old format.

ramwin's user avatar

This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.

To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.

Sarang's user avatar

In your template you can do like this:

In your template-tags you can add a tag like this:

Ashish Gupta's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged django django-templates or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Viewport Shader Render different from 1 computer to another
  • Do I need to indicate 'solo' for wind/brass instruments in shared staff?
  • Could space habitats have large transparent roofs?
  • Determine the voltages Va and V1 for the circuit
  • In By His Bootstraps (Heinlein) why is Hitler's name Schickelgruber?
  • Have there been any scholarly attempts and/or consensus as regards the missing lines of "The Ruin"?
  • Why was the animal "Wolf" used in the title "The Wolf of Wall Street (2013)"?
  • Is it this limit impossible or not exists?
  • Was Paul's Washing in Acts 9:18 a Ritual Purification Rather Than a Christian Baptism?
  • Geometry question about a six-pack of beer
  • Can you help me to identify the aircraft in a 1920s photograph?
  • Are there examples of triple entendres in English?
  • Google Search Console reports "Page with redirect" as "errors", are they?
  • SMTP Header confusion - Delivered-To: and To: are different
  • Why do these two pieces of code, which only differ by a transformation of the formula, exhibit a significant difference in running speed?
  • Why can't LaTeX (seem to?) Support Arbitrary Text Sizes?
  • Does it matter if a fuse is on a positive or negative voltage?
  • Why is it 'capacité d'observation' (without article) but 'sens de l'observation' (with article)?
  • Summation of arithmetic series
  • Does this double well potential contradict the fact that there is no degeneracy for one-dimensional bound states?
  • How to Pick Out Strings of a Specified Length
  • No simple group or order 756 : Burnside's proof
  • How is Victor Timely a variant of He Who Remains in the 19th century?
  • Is arxiv strictly for new stuff?

variable assignment vs declaration

IMAGES

  1. Difference Between Variable Declaration vs Assignment vs Initialization?

    variable assignment vs declaration

  2. Variable Declaration and Assignment in Java

    variable assignment vs declaration

  3. Javascript variable declaration in function

    variable assignment vs declaration

  4. Variable Declaration and Assignment

    variable assignment vs declaration

  5. Declaration vs Initialization vs Invocation in Programming

    variable assignment vs declaration

  6. Understand Variable Declaration, Initialisation and Assignment in

    variable assignment vs declaration

VIDEO

  1. Variable Declaration

  2. Lecture 1 of JS (Introduction of JS, variables, and datatypes)

  3. JavaScript Hoisting Explained

  4. 6 storing values in variable, assignment statement

  5. Variables Declaration and Definition in C Programming Language

  6. Exercises on variable declaration, please remember to #subscribe #like #share #comment

COMMENTS

  1. Difference between declaration statement and assignment statement in C

    Declaration: int a; Assignment: a = 3; Declaration and assignment in one statement: int a = 3; Declaration says, "I'm going to use a variable named "a" to store an integer value."Assignment says, "Put the value 3 into the variable a." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.

  2. Java: define terms initialization, declaration and assignment

    assignment: throwing away the old value of a variable and replacing it with a new one. initialization: it's a special kind of assignment: the first.Before initialization objects have null value and primitive types have default values such as 0 or false.Can be done in conjunction with declaration. declaration: a declaration states the type of a variable, along with its name.

  3. 1.4

    int x; // define an integer variable named x int y, z; // define two integer variables, named y and z. Variable assignment. After a variable has been defined, you can give it a value (in a separate statement) using the = operator. This process is called assignment, and the = operator is called the assignment operator.

  4. Explain the variable declaration, initialization and assignment in C

    Variable Assignment. A variable assignment is a process of assigning a value to a variable. For example, int height = 40; int base = 31; Rules for defining variables. A variable may be alphabets, digits, and underscore. A variable name can start with an alphabet, and an underscore but, can't start with a digit. Whitespace is not allowed in ...

  5. PDF Resource: Variables, Declarations & Assignment Statements

    The concept of a variable is a powerful programming idea. It's called a variable because - now pay attention - it varies. When you see it used in a program, the variable is often written like this r = 255; (r is the variable and the whole thing is the assignment statement). You get the idea from such usage that a variable is like an ...

  6. Variables and Assignment Statements: Syntax of Variable Declaration

    Syntax of Variable Deceleration. The word syntax means the grammar of a programming language. We can talk about the syntax of just a small part of a program, such as the syntax of variable declaration. There are several ways to declare variables: dataType variableName; This declares a variable, declares its data type, and reserves memory for it.

  7. Declare vs. Assign in JavaScript

    To declare a constant or a variable is to create a data object and give a name, so that you can reference it later in your code. To assign a constant or variable, on the other hand, is to give it a value. Another name for declaration, if oversimplified, could be "naming it.". And another name for assignment could be "storing information ...

  8. Python Variable Assignment. Explaining One Of The Most Fundamental

    Declare And Assign Value To Variable. Assignment sets a value to a variable. To assign variable a value, use the equals sign (=) myFirstVariable = 1 mySecondVariable = 2 myFirstVariable = "Hello You" Assigning a value is known as binding in Python. In the example above, we have assigned the value of 2 to mySecondVariable.

  9. 5.4 Variable Initialization vs. Declaration vs. Assignment

    5.4.3 Declaration. Declaration is the point at where you create a variable. At this point, Java knows nothing info the variable, so it's necessary to specify the sort. This is and only time you need to specify which type since for all future time, Java can refer on this declaration to determine what and type is.

  10. Variables in Python

    In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ): Python. >>> n = 300. This is read or interpreted as " n is assigned the value 300 .".

  11. Variable Declaration and Assignment in JavaScript

    Destructuring assignment is commonly used to initialize variables in const, let, or var declarations, but it can also be used in regular assignment expressions (for assigning values to previously ...

  12. Initialization, declaration and assignment terms in Java

    Initialization declaration and assignment terms in Java - A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variab

  13. language design

    If you have closures, you need to precisely declare which scope a variable belongs to. Imagine a language without a declaration keyword, and implicit declaration through assignment (e.g. PHP or Python). Both of these are syntactically challenged with respect to closures, because they either ascribe a variable to the outermost or innermost ...

  14. TypeScript: Documentation

    Declaring a variable in JavaScript has always traditionally been done with the var keyword. var a = 10; As you might've figured out, we just declared a variable named a with the value 10. We can also declare a variable inside of a function: function f() {. var message = "Hello, world!";

  15. Why declare a variable in one line, and assign to it in the next?

    In both of your examples the variable is declared and defined simultaneously, in one line. The difference between your examples is that in the first one the variables are either left uninitialized or initialized with a dummy value and then it is assigned a meaningful value later. In the second example the variables are initialized right away.

  16. Quick Tip: How to Declare Variables in JavaScript

    var. Syntax: var x; // Declaration and initialization. x = "Hello World"; // Assignment // Or all in one var y = "Hello World"; This declaration is probably the most popular, as there was no ...

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

  18. variable assignment in declaration

    variable assignment in declaration Tom,Are there any issues to be aware of or drawbacks/gotchas to adding some logic, beyond a default value assignment, to the variable declaration section of a stored procedure as opposed to putting the logic in the body? e.g. v_todate date := trunc(nvl(pi_todate, to_date('1-JAN-2199','DD-MO

  19. Language / Variable declarations

    A variable's declaration mode determines how new values assigned to a variable will be saved. Declaration modes. Understanding the impact that declaration modes have on the behavior of variables requires prior knowledge of Pine Script™'s execution model. When you declare a variable, if a declaration mode is specified, it must come first.

  20. What distinguishes the declaration, the definition and the

    For a variable, a definition is a declaration which allocates storage for that variable. Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a ...

  21. Language / Expressions, declarations and statements

    Variable assignment. A mutable variable is a variable which can be given a new value. The operator := must be used to give a new value to a variable. A variable must be declared before you can assign a value to it (see declaration of variables above). The type of a variable is identified at declaration time.

  22. What's the difference between variable definition and declaration in

    var x is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation. var x = 1 is both declaration and definition but are separated with x being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).

  23. sh

    2. The function GetValue along with printing a string to stdout also returns a code 1. So assignment to the variable var1 from the function, though sets the value to foobar, sets an exit code 1 which is a non-zero code causing the part after the || to be invoked. But remember the same happens in the case with the declare, but the reason you see ...

  24. How to assign a value to a variable in a Django template?

    Create a template tag: The app should contain a templatetags directory, at the same level as models.py, views.py, etc.If this doesn't already exist, create it - don't forget the __init__.py file to ensure the directory is treated as a Python package.. Create a file named define_action.py inside of the templatetags directory with the following code: ...