Monday, May 20, 2024

Person-defined variables in JavaScript | InfoWorld

With out variables, programming languages are subsequent to ineffective. Happily, JavaScript’s variable system is extremely highly effective and versatile. This text reveals you the way to use JavaScript variables to retailer numbers, textual content strings, objects, and different knowledge varieties. As soon as you’ve got saved this data, you should use it anyplace in your program.

All about JavaScript variables

Here is what you will be taught on this article:

  • What’s a user-defined variable in JavaScript?
  • Knowledge varieties in JavaScript variables
  • The best way to create JavaScript variables
  • The best way to retailer knowledge varieties in JavaScript variables
  • Suggestions for naming JavaScript variables
  • Dynamic typing and JavaScript variables
  • The best way to work with string variables
  • What it’s worthwhile to find out about variable scope

What’s a user-defined variable in JavaScript?

All JavaScript programming occurs in an atmosphere like an internet browser, Node, or Bun.js. Every of those environments has its personal set of pre-defined variables like window and console. These variables aren’t user-defined as a result of they’re set by the atmosphere. One other form of variable is the user-defined variable outlined by different builders, resembling in third-party frameworks or libraries you utilize. Then there are variables you create whereas writing your packages, utilizing the let and const key phrases. These are outlined by you, the person. This text is about the way to create your individual user-defined variables.

Knowledge varieties in JavaScript variables

Variables maintain all kinds of data briefly. The JavaScript knowledge varieties that may be saved in a variable embody:

  • Numeric values, or “numbers”: Variables maintain numbers, which can be utilized in easy or advanced mathematical computations. Instance: 2 + 2 = 4.
  • Character strings: A string is a group of textual content, resembling “JavaScript” or “My identify is Mudd.”
  • True/False values: The Boolean knowledge kind, which has solely values of true or false.
  • Objects: Variables can maintain JavaScript objects or user-defined objects.

JavaScript variables can maintain just a few other forms of knowledge, however these are by far essentially the most generally used varieties.

The best way to create JavaScript variables

A number of JavaScript directions are used to create variables, however essentially the most fundamental solution to create a variable manually is with the equals (=) project operator:

VariableName = worth

The primary argument is the identify of the variable. Variable names will be very lengthy, however there are restrictions on the characters you should use. We’ll focus on these intimately quickly.

In follow, variables ought to be declared utilizing both the let or const statements:

let myVariable = “foo”; 
const myOtherVariable = 42;

Each let and const prohibit the visibility of the variable to the present code block. The const assertion creates a “fixed” variable, which can’t be modified. When potential, use const for cleaner code.

The second argument is the variable’s content material. You may put all types of knowledge right into a variable, together with a quantity, a string, a math expression (resembling 2 + 2), and varied different issues. In JavaScript, variables are dynamically typed, so the identical variable can maintain any form of knowledge.

The best way to retailer knowledge varieties in JavaScript variables

Let’s check out the way to retailer the most typical knowledge varieties in JavaScript variables.

Storing numbers in JavaScript variables

A quantity is a number of digits saved within the pc in such a approach that JavaScript can carry out mathematical calculations with them. JavaScript helps each integers and floating-point values. To put a quantity in a variable, simply present the variable identify, the equals signal (aka the variable project operator), and the worth you need to use. For instance, the next code locations the quantity 10 in a variable named myVar:

let myVar = 10;

JavaScript makes it straightforward to cope with numbers. You may freely combine and match floats. For instance, myVar = 10 * .3 is okay.

Storing strings in JavaScript variables

A string is a number of textual content characters organized in reminiscence in a single-file vogue. Strings can comprise numbers (digits), letters, punctuation, or a mix of those. You can not carry out math calculations on strings (it’ll return NaN should you attempt, for Not a Quantity). Strings are assigned to JavaScript variables by being enclosed in a set of quotes, which will be single or double:

"I'm a string"


'I'm a string'

In contrast to some languages, JavaScript makes no distinction between the 2 types of citation marks. Right here is an instance of the way to place a string right into a variable:

let myVar = "That is JavaScript";

Storing Boolean values in JavaScript variables

There are solely two Boolean values: true or false. Some programming languages haven’t got a separate set of Boolean values; as an alternative, they use 0 for false, and 1 or -1 (or every other non-zero worth) for true. JavaScript allows you to use these numbers to characterize true and false however, as well as, reserves the phrases true and false to check with the Boolean true and false values.

You may consider the Boolean true/false values as being equal to on/off or sure/no. To assign a Boolean worth to a variable, enter the phrase true or false with out quotes. Here is an instance:

let myVar = true;

JavaScript “coerces” variables to Boolean when testing to true/false. Moreover, quite a lot of “falsy” and “truthy” variables exist on this vein. We’ve talked about 0 and 1, which naturally map to false and true. In actual fact, any quantity aside from 0 is coerced to true. One other coerced worth is the empty string (false) and a string holding a worth (true):

if (“”) alert(“take a look at”); // doesn't show alert

One other frequent use is to ascertain the falseness of undefined and null:

if (null) alert(“take a look at”) // doesn't show alert

Storing objects in JavaScript variables

Variables can comprise objects, that are containers for different values and are extremely helpful in lots of eventualities. There are two sorts of object variables in JavaScript:

  • Variables that comprise built-in browser-related objects—window, doc, and so forth. These are references to things you didn’t create. They’re like copies, however the copies change if the unique modifications. In some instances, altering the item within the variable impacts the unique JavaScript object.
  • Variables that comprise user-defined objects characterize the precise object. A change to the item within the variable modifications solely that object.

To assign a JavaScript object to a variable, present the identify of the item, as in:

myVar = window;;

To assign a brand new copy of a user-defined object to a variable, use the new assertion and supply the identify of the item perform:

let myVar = new myObject();

Or, you may use an object literal:

let myVar = {
  identify: “My Object”

Suggestions for naming JavaScript variables

JavaScript presents a substantial amount of latitude in terms of naming variables. JavaScript variable names will be nearly limitless in size, though for sensible causes you will most likely need to preserve your variable names below 10 or 15 characters. Shorter variable names are simpler to kind and keep in mind.

Listed below are extra ideas to remember when naming your variables:

  • Variable names ought to encompass letters solely, with out areas. You should utilize numbers so long as the identify would not begin with a digit. For instance, myVar1 is okay however 1MyVar is just not.
  • Do not use punctuation characters in variable names, with one xception: the underscore character ( _ ). So, the variable my_Var is okay, however my*Var is just not. Variables can start with the underscore character.
  • Variable names are case delicate. The variable MyVar is taken into account not the identical variable as myVar, myVar, and different variations.
  • It’s standard to make use of camelCase for JavaScript variable names, for instance: thisIsMyVariable.
  • Keep away from obscure abbreviations. An abbreviation like msg is okay as a result of most individuals know it’s quick for “message.” Much less frequent abbreviations ought to be prevented.

Dynamic typing and JavaScript variables

In contrast to another programming languages, JavaScript doesn’t require you to explicitly outline the kind of variable you need to create. This JavaScript habits is typically known as free knowledge typing, extra formally referred to as dynamic or weak typing. JavaScript’s free knowledge typing differs from C and Java, which each use strict knowledge typing.

What this implies is that in JavaScript, you need not declare a variable kind. JavaScript will fortunately use the identical variable for numbers, strings, and objects. (A part of TypeScript’s energy is that it provides a strongly typed layer on prime of JavaScript.) 

Assigning variables with let and const

Good JavaScript makes use of the let and const key phrases to declare variables. Here is an instance:

let myVar = "This can be a variable";
const myConst = “This can be a fixed”;

You will nonetheless see var in some older code. If potential, refactor it to make use of let. (Although doing that’s typically not easy if the variable is used as a worldwide.) You’ll additionally see variables declared with out a key phrase declaration—as an example, myVar = “foo”. That’s simply dangerous model!

You too can use the let assertion with a variable identify to declare the variable however not outline a worth for it:

let yVar;

On this case, you’ve got outlined myVar in reminiscence however have but to assign a worth to it. Later, it is possible for you to to make use of the variable.

Working with string variable limits

String variable limits had been as soon as a standard downside in front-end JavaScript. Nowadays, the restrict on how lengthy a JavaScript string variable will be relies on the engine you’re working in—whether or not it’s Chrome, Edge, Node, Bun, and so on. Normally, you received’t run into issues with string variable limits.

You may create longer strings by “piecing” them collectively. After assigning a string to every variable, you mix them utilizing the plus (+) character. That is known as concatenation. The next instance reveals how concatenation works:

let myVar = "That is the beginning " + of the way you " + " can construct strings";

You too can use interpolation, which makes it simpler to include variables right into a string:

let identify = “John Lennon”;
let myVar = “The track Throughout the Universe was written by ${identify}.”;

What it’s worthwhile to find out about variable scope

The scope of a variable has nothing to do with optics or mouthwash, however quite the extent to which a variable is seen to different components of a JavaScript program. Within the outdated days, var would hoist a variable to the highest of the scope. In fashionable JavaScript, let and const behave extra consistent with different languages, protecting the variable inside the present code block. The present block is encompassed by curly braces, as proven right here:

let myFunction = perform() {
    let foo = "bar";
    if (true){
        let foo = "baz";
    console.log(foo); // outputs “bar”

On this instance, the console will output “bar”.  Thefoo outlined contained in the if block is held inside that block. International variables are a standard supply of logic errors, so protecting a variable within the smallest scope is at all times good follow.


Though variables are a reasonably easy side of JavaScript, they’re additionally common and important. Understanding the way to work with them is like mastering the fundamental strikes of a martial artwork: follow pays off. You by no means actually go away the fundamentals behind; you simply get higher at making them give you the results you want.

This story, “Person-defined variables in JavaScript” was initially revealed by


Copyright © 2024 IDG Communications, Inc.

Related Articles


Please enter your comment!
Please enter your name here

Stay Connected

- Advertisement -spot_img

Latest Articles