Declare and Use Variables in JavaScript

Spread the love

Variables are fundamental building blocks of a JavaScript program. They are names that represent entities that are stored in memory. In JavaScript, variables can contain almost anything. They can contain numbers, objects, booleans, strings, functions, arrays and varieties and combinations of those things. When you declare a variable, it’s a name that references those things in memory. In other words, you get the entity and manipulate it with variables.

They allow you to combine data and change them with various operators. We can add, subtract, multiply and divide numbers. Also, we can concatenate strings, call functions, and together they can combine useful results for programmers and users.

Variables have data types in JavaScript. Numbers, objects, booleans and strings are all types. There’s also the undefined type which is unique in JavaScript which represents variables that has no value set to them or haven’t been defined yet. Because variables can have different types, they can be converted into different data types when necessary. For example, strings that has numerical content only can be converted into a number and vice versa. We can do that with various operators and functions, like + to convert strings to numbers and toString function convert number to strings.

Declaring Variables

Declaring variables is the most basic part of a JavaScript program. We need to declare any variables that we’re going to use by using various keywords. In modern JavaScript, we should use the let keyword to declare variables. We use let because it allows us to declare block scoped variables, which means that if it’s declared in a function or class, then it cannot be changed outside of there. To use let to declare a variable, we put:

let a = 1;

The equal sign is the assignment operator. The value on the right side is set to the variable on the left side. So in this case, the variable a has the value 1. This declares primitive types, but we can also assign an object to a variable, like so:

let a = { num: 1 };

You might also have heard of the var keyword, but we shouldn’t use it since the scope isn’t constant. Any function or other code that’s in the declared in the same level as the variable declared with var or anything nested inside those entities can modify a variable declared with var , which can’t happen to variables declared with let .

We can also assign one variable to another variable. For instance, we can write:

let a = 1
let b = a // 1

The above example has a set to 1 then b is assigned to a which is assigned the value 1. b will get the value of 1 from a .

const is a keyword that we declare constants with. JavaScript constants cannot be assigned a new value after it’s set. However, we can modify the values inside an object set with const . So we cannot write:

const a = { num: 1};
a = 2; // error

but, we can write:

const a = { num: 1 };
a.num = 2;

The value of a will then be {num: 2} . const is very useful since it’s very hard to accidentally overwrite the value of your object in this case.

We can also declare global variables if 'use strict' is not added on top of our code. We declare global variables by writing a = 1; , which declares a in the global scope. This means that code written anywhere can modify it. This is the same as attaching a to the window object, so a = 1 is the same as window.a = 1 . It’s too easy to accidentally overwrite the value of a , so we should never declare global variables, unless you’re using something in the window object.

Variable Naming

Variables can be named in many ways. There are a few rules which apply when naming variables. They can start with upper or lower case letter, an underscore or a dollar sign. Variables in JavaScript are case sensitive, so a is not the same as A . Also, they cannot contain spaces. You can name variables as long as you want, but making them too long will probably confuse other developers reading your code.

Variable names can’t be the same reserved keywords which are listed below:

  • abstract
  • else
  • instanceof
  • switch
  • boolean
  • enum
  • int
  • synchronized
  • break
  • export
  • interface
  • this
  • byte
  • extends
  • long
  • throw
  • case
  • false
  • native
  • throws
  • catch
  • final
  • new
  • transient
  • char
  • finally
  • null
  • true
  • class
  • float
  • package
  • try
  • const
  • for
  • private
  • typeof
  • continue
  • function
  • protected
  • var
  • debugger
  • goto
  • public
  • void
  • default
  • if
  • return
  • volatile
  • delete
  • implements
  • short
  • while
  • do
  • import
  • static
  • with
  • double
  • in
  • super

Data Types

JavaScript variables has data types, which classifies the kind of data stored by its content. They distinguish one kind of data from another. For example, words are not the same as numbers. However, JavaScript is a loosely typed language, which means that different kinds of data to one variable. This means that we have to be careful when we’re comparing variables and when we’re manipulating them to not be manipulating the wrong kinds of data. This also means that when data is being compared, they’re automatically converted to the same type if possible for comparison.

JavaScript has give basic types of data. It has the number, string, boolean, NaN, and undefined types.

Number Type

Variable of type number stores numbers as the name suggests. JavaScript numbers can range from 5e-324 (-5 followed by 324 zeroes) to 1.7976931348623157e+308 ( same as 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000).

You can declare number variables by writing:

let x = 1;

We can convert variables of any types to number. If you convert a number to a number you still get a number. The Number function allows us to convert variables of any type to a number is possible. If it can’t, the NaN is returned, which means that the variable being converted isn’t a number.

Strings with numerical content can be converted to a number.

Number(“1”) // returns number 1

Text strings that can’t be converted to numbers return the value NaN:

Number(“duck”) // returns NaN

The Boolean value true returns the number 1:

Number(true) // returns 1

The Boolean value false returns the number 0:

Number(false) // returns 0

Other falsy values, which means that if they’re converted into a boolean, they’ll return false , also converted to 0. Falsy values in JavaScript include empty string (“”), 0, false, null, and undefined .

For example,

Number(‘’) // returns 0
Number(null) // returns 0
Number(undefined) // returns 0
Number(0) // returns 0

The + sign in front of a variable does the same thing as the Number function, so we can write:

+“1” // returns number 1
+“duck” // returns NaN
+‘’ // returns 0
+null // returns 0
+undefined // returns 0
+0 // returns 0

When you’re manipulating variables that may contain numerical values, then convert them to numbers first before combining them. However, when you’re multiply or diving 2 variables where one or both is a string, then JavaScript will convert them both to numbers before doing the operations. So, for example:

'2'*'2' // 4
'2'/2 // 1

But of course this won’t work if one or both strings don’t have numerical only content. For example: 'duck'*'goose' will return NaN since both of them aren’t numbers.

String Type

String types are variables that can store any characters. It can store letters, numbers, punctuation, and special escape characters to represent certain characters. The escape characters include:

  • ’ — single quote
  • ” — double quote
  • — backslash
  • n — new line
  • r — carriage return
  • t — tab
  • b — backspace
  • f — form feed

We can declare strings by writing:

let a  = 'string';

Single quotes and double quotes are the same. However, if you want to use quotes inside a string then you either have to use a different kind from the ones you use to wrap the string or use the slash character to escape the quote so that the JavaScript interpreter knows that it’s quotation mark and not a string delimiter. For example, we write:

let a = ""This is a string in quotes"";


let a = "'This is a string in quotes'";

Template Strings

Modern JavaScript also have template strings, starting from the 2015 and on. This is very handy since we can put variables inside strings so that our strings can have variables without having to concatenate them. We declare template strings with the backtick character, which is the character on your keyboard below the Escape key. We put variables inside our string by writing ${a} , where a is a variable.

For example, we can write:

let a = 1;
let b = `There is ${a} chicken.` // There is 1 chicken.

Boolean Type

Boolean type variables can only contain the values true or false . We declare it like so:

let a = true;

Variables of other types can be converted to boolean type. Almost everything converts to true except the following:

  • NaN
  • undefined
  • 0 (numeric value zero)
  • -0
  • “” (empty string)
  • false

NaN Type

NaN stands for not a number. Anything that can’t be converted or evaluated to a number will be NaN . For example, we cannot take a square root of a negative number and we can’t convert a non-numerical string into a number.

Undefined Type

A variable with the undefined type means that the variable has no value set to them or haven’t been defined yet.

These are the basic ways that JavaScript variables are declared and used in JavaScript. With these operations we can do a lot more than just declaring and assigning variables as we learn more about other parts of JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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