JavaScript variables hold a wide variety of information and can be used with virtually any data type. Here's how to use variables to store numbers, text strings, objects, and more. Credit: pathdoc/Shutterstock Without variables, programming languages are next to useless. Fortunately, JavaScript’s variable system is incredibly powerful and versatile. This article shows you how to use JavaScript variables to store numbers, text strings, objects, and other data types. Once you’ve stored this information, you can use it anywhere in your program. All about JavaScript variables Here’s what you’ll learn in this article: What is a user-defined variable in JavaScript? Data types in JavaScript variables How to create JavaScript variables How to store data types in JavaScript variables Tips for naming JavaScript variables Dynamic typing and JavaScript variables How to work with string variables What you need to know about variable scope What is a user-defined variable in JavaScript? All JavaScript programming happens in an environment like a web browser, Node, or Bun.js. Each of these environments has its own set of pre-defined variables like window and console. These variables are not user-defined because they are set by the environment. Another kind of variable is the user-defined variable defined by other developers, such as in third-party frameworks or libraries you use. Then there are variables you create while writing your programs, using the let and const keywords. These are defined by you, the user. This article is about how to create your own user-defined variables. Data types in JavaScript variables Variables hold a wide variety of information temporarily. The JavaScript data types that can be stored in a variable include: Numeric values, or “numbers”: Variables hold numbers, which can be used in simple or complex mathematical computations. Example: 2 + 2 = 4. Character strings: A string is a collection of text, such as “JavaScript” or “My name is Mudd.” True/False values: The Boolean data type, which has only values of true or false. Objects: Variables can hold JavaScript objects or user-defined objects. JavaScript variables can hold a few other kinds of data, but these are by far the most commonly used types. How to create JavaScript variables Several JavaScript instructions are used to create variables, but the most basic way to create a variable manually is with the equals (=) assignment operator: VariableName = value The first argument is the name of the variable. Variable names can be very long, but there are restrictions on the characters you can use. We’ll discuss these in detail soon. In practice, variables should be declared using either the let or const statements: let myVariable = “foo”; const myOtherVariable = 42; Both let and const restrict the visibility of the variable to the current code block. The const statement creates a “constant” variable, which cannot be changed. When possible, use const for cleaner code. The second argument is the variable’s content. You can put all sorts of data into a variable, including a number, a string, a math expression (such as 2 + 2), and various other things. In JavaScript, variables are dynamically typed, so the same variable can hold any kind of data. How to store data types in JavaScript variables Let’s take a look at how to store the most common data types in JavaScript variables. Storing numbers in JavaScript variables A number is one or more digits stored in the computer in such a way that JavaScript can perform mathematical calculations with them. JavaScript supports both integers and floating-point values. To place a number in a variable, just provide the variable name, the equals sign (aka the variable assignment operator), and the value you want to use. For example, the following code places the number 10 in a variable named myVar: let myVar = 10; JavaScript makes it easy to deal with numbers. You can freely mix and match floats. For example, myVar = 10 * .3 is okay. Storing strings in JavaScript variables A string is one or more text characters arranged in memory in a single-file fashion. Strings can contain numbers (digits), letters, punctuation, or a combination of these. You cannot perform math calculations on strings (it will return NaN if you try, for Not a Number). Strings are assigned to JavaScript variables by being enclosed in a set of quotes, which can be single or double: "I am a string" or 'I am a string' Unlike some languages, JavaScript makes no distinction between the two forms of quotation marks. Here is an example of how to place a string into a variable: let myVar = "This is JavaScript"; Storing Boolean values in JavaScript variables There are only two Boolean values: true or false. Some programming languages don’t have a separate set of Boolean values; instead, they use 0 for false, and 1 or -1 (or any other non-zero value) for true. JavaScript lets you use these numbers to represent true and false but, in addition, reserves the words true and false to refer to the Boolean true and false values. You can think of the Boolean true/false values as being equivalent to on/off or yes/no. To assign a Boolean value to a variable, enter the word true or false without quotes. Here’s an example: let myVar = true; JavaScript “coerces” variables to Boolean when testing to true/false. Additionally, a variety of “falsy” and “truthy” variables exist in this vein. We’ve mentioned 0 and 1, which naturally map to false and true. In fact, any number other than 0 is coerced to true. Another coerced value is the empty string (false) and a string holding a value (true): if (“”) alert(“test”); // does not display alert Another common use is to establish the falseness of undefined and null: if (null) alert(“test”) // does not display alert Storing objects in JavaScript variables Variables can contain objects, which are containers for other values and are incredibly useful in many scenarios. There are two kinds of object variables in JavaScript: Variables that contain built-in browser-related objects—window, document, and so on. These are references to objects you did not create. They are like copies, but the copies change if the original changes. In some cases, changing the object in the variable affects the original JavaScript object. Variables that contain user-defined objects represent the actual object. A change to the object in the variable changes only that object. To assign a JavaScript object to a variable, provide the name of the object, as in: myVar = window;; To assign a new copy of a user-defined object to a variable, use the new statement and provide the name of the object function: let myVar = new myObject(); Or, you could use an object literal: let myVar = { name: “My Object” } Tips for naming JavaScript variables JavaScript offers a great deal of latitude when it comes to naming variables. JavaScript variable names can be almost unlimited in length, although for practical reasons you’ll probably want to keep your variable names under 10 or 15 characters. Shorter variable names are easier to type and remember. Here are more tips to keep in mind when naming your variables: Variable names should consist of letters only, without spaces. You can use numbers as long as the name doesn’t start with a digit. For example, myVar1 is okay but 1MyVar is not. Don’t use punctuation characters in variable names, with one xception: the underscore character ( _ ). So, the variable my_Var is okay, but my*Var is not. Variables can begin with the underscore character. Variable names are case sensitive. The variable MyVar is considered not the same variable as myVar, myVar, and other variations. It is conventional to use camelCase for JavaScript variable names, for example: thisIsMyVariable. Avoid obscure abbreviations. An abbreviation like msg is okay because most people know it is short for “message.” Less common abbreviations should be avoided. Dynamic typing and JavaScript variables Unlike some other programming languages, JavaScript does not require you to explicitly define the type of variable you want to create. This JavaScript behavior is sometimes called loose data typing, more formally known as dynamic or weak typing. JavaScript’s loose data typing differs from C and Java, which both use strict data typing. What this means is that in JavaScript, you don’t need to declare a variable type. JavaScript will happily use the same variable for numbers, strings, and objects. (Part of TypeScript’s power is that it adds a strongly typed layer on top of JavaScript.) Assigning variables with let and const Good JavaScript uses the let and const keywords to declare variables. Here’s an example: let myVar = "This is a variable"; const myConst = “This is a constant”; You’ll still see var in some older code. If possible, refactor it to use let. (Though doing that is sometimes not straightforward if the variable is used as a global.) You’ll also see variables declared without a keyword declaration—for instance, myVar = “foo”. That’s just bad style! You can also use the let statement with a variable name to declare the variable but not define a value for it: let yVar; In this case, you’ve defined myVar in memory but have yet to assign a value to it. Later, you will be able to use the variable. Working with string variable limits String variable limits were once a common problem in front-end JavaScript. These days, the limit on how long a JavaScript string variable can be is dependent on the engine you are running in—whether it be Chrome, Edge, Node, Bun, etc. In general, you won’t run into problems with string variable limits. You can create longer strings by “piecing” them together. After assigning a string to each variable, you combine them using the plus (+) character. This is called concatenation. The following example shows how concatenation works: let myVar = "This is the start " + of how you " + " can build strings"; You can also use interpolation, which makes it easier to incorporate variables into a string: let name = “John Lennon”; let myVar = “The song Across the Universe was written by ${name}.”; What you need to know about variable scope The scope of a variable has nothing to do with optics or mouthwash, but rather the extent to which a variable is visible to other parts of a JavaScript program. In the old days, var would hoist a variable to the top of the scope. In modern JavaScript, let and const behave more in line with other languages, keeping the variable within the current code block. The current block is encompassed by curly braces, as shown here: let myFunction = function() { let foo = "bar"; if (true){ let foo = "baz"; } console.log(foo); // outputs “bar” } In this example, the console will output “bar”. Thefoo defined inside the if block is held within that block. Global variables are a common source of logic errors, so keeping a variable in the smallest scope is always good practice. Conclusion Although variables are a fairly simple aspect of JavaScript, they are also universal and essential. Knowing how to work with them is like mastering the basic moves of a martial art: practice pays off. You never really leave the basics behind; you just get better at making them work for you. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos