Skip to Content

Variables and Operators

You can think of variables as “storage containers” for data in your code.

the concept of variables in coding as boxes labeled "birthday" that store and provide access to data, specifically a date "16-09-2003"

A variable is a “named storage” for data. You can use variables to store goodies, visitors, and other data.

Declaring Variables

To create a variable in JavaScript, use the let keyword.

The statement below creates (in other words: declares) a variable with the name “message”:

let message;

Now, you can put some data into it by using the assignment operator = (equals):

let message; // store the string 'Hello' in the variable named message message = 'Hello';

To be concise, you can combine the variable declaration and assignment into a single line:

let message = 'Hello';

Knowledge Check

What is the purpose of using the let keyword in JavaScript?

  • Select an answer to view feedback.

Constants

To declare a constant (unchanging) variable, use const instead of let:

const myBirthday = '16-09-2003';

Variables declared using const are called “constants.” They cannot be reassigned. An attempt to do so would cause an error:

const myBirthday = '16-09-2003'; myBirthday = '01-01-2001'; // error, can't reassign the constant!

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and communicate that fact to everyone.

Knowledge Check

What is the result of attempting to reassign a const declared variable in JavaScript?

  • Select an answer to view feedback.

Naming Variables

There are two limitations on variable names in JavaScript:

  1. The name must contain only letters, digits, or the symbols $ and _.
  2. The first character must not be a digit.

Examples of valid names:

let userName; let test123;

What is interesting - the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.

These names are valid, but not recommended:

let $ = 1; // declared a variable with the name "$" let _ = 2; // and now a variable with the name "_" console.log($ + _); // 3

Examples of incorrect variable names:

let 1a; // cannot start with a digit let my-name; // hyphens '-' aren't allowed in the name

Knowledge Check

Which of the following is a valid JavaScript variable name?

  • Select an answer to view feedback.

Operators

Numbers are the building blocks of programming logic! In fact, it is hard to think of any useful programming task that does not involve at least a little basic math… so knowing how numbers work is obviously quite important. Luckily, it’s also fairly straightforward.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
**Exponentiation5 ** 3 = 125
/Division6 / 3 = 2
%Modulus5 % 3 = 2

Practice Exercise

Given the table of operators above, write a simple program snippet that demonstrates the use of each operator with the variable x initialized to 10.

Knowledge Check

What is the result of applying the modulus operator to x where x = 10?

  • Select an answer to view feedback.

String Operations

Let’s meet the features of JavaScript operators that are beyond school arithmetics.

Usually, the plus operator + sums numbers.

But, if the binary + is applied to strings, it merges (concatenates) them:

let s = "my" + "string"; console.log(s); // mystring

Note that if any of the operands is a string, then the other one is converted to a string too.

For example:

console.log(1 + '2'); // '12' console.log('1' + 2); // '12'

See, it doesn’t matter whether the first operand is a string or the second one.

Here is a more complex example:

console.log(2 + 2 + '1') // "41" and not "221"

Here, operators work one after another. The first + sums two numbers, so it returns 4, then the next + adds the string 1 to it, so it is like 4 + '1' = '41'.

console.log('1' + 2 + 2) // "122" and not "14"

Here, the first + concatenates the string and the number, so it returns '12', then the next + adds 2 to it, so it is like '12' + 2 = '122'.

The binary + is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.

Here is the demo for subtraction and division:

console.log( 6 - '2' ); // 4, converts '2' to a number console.log( '6' / '2' ); // 3, converts both operands to numbers

Knowledge Check

console.log('3' + 2 - 1);

Considering the behavior of the + operator with mixed data types in JavaScript, what will be the output of the above code snippet?

  • Select an answer to view feedback.

Number Conversion

The plus + exists in two forms: the binary form that you used in the last challenge and the unary form.

The unary plus or, in other words, the plus operator + applied to a single value, does not do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.

For example:

// No effect on numbers let x = 1; console.log( +x ); // 1 let y = -2; console.log( +y ); // -2 // Converts non-numbers console.log( +"12" ); // 12 console.log( +"" ); // 0

The need to convert strings to numbers arises very often. For example, if you are getting values from HTML form fields, they are usually strings. What if you want to sum them?

The binary plus would add them as strings:

let apples = "2"; let oranges = "3"; alert( apples + oranges ); // "23", the binary plus concatenates strings

If you want to treat them as numbers, you need to convert and then sum them:

let apples = "2"; let oranges = "3"; // both values converted to numbers before the binary plus alert( +apples + +oranges ); // 5 // the longer variant, but also valid alert( Number(apples) + Number(oranges) ); // 5

From a mathematician’s standpoint, the abundance of pluses may seem strange. But from a programmer’s standpoint, there is nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.

Knowledge Check

Given the explanation of unary and binary + operators in JavaScript, how can you correctly sum the string values '2' and '3' as numbers using unary +?

  • Select an answer to view feedback.

Precedence

If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.

From earlier education, you may know that the multiplication in the expression 1 + 2 * 2 should be calculated before the addition. That is exactly the precedence thing. The multiplication is said to have a higher precedence than the addition.

Parentheses override any precedence, so if you are not satisfied with the default order, you can use them to change it. For example, write (1 + 2) * 2.

There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the larger number executes first. If the precedence is the same, the execution order is from left to right.

Here is an extract from the precedence table (you do not need to remember this, but note that unary operators are higher than corresponding binary ones):

PrecedenceNameSign
14unary plus+
14unary negation-
13exponentiation**
12multiplication*
12division/
11addition+
11subtraction-
2assignment=

Knowledge Check

When dealing with multiple operators in a JavaScript expression, which statement is true regarding the order of execution?

  • Select an answer to view feedback.

Special Operators

Increasing or decreasing a number by one (increment/decrement) is among the most common numerical operations.

So, there are special operators for it:

  • Increment ++ increases a variable by 1:
let counter = 2; // works the same as counter = counter + 1, but is shorter counter++; console.log(counter); // 3
  • Decrement -- decreases a variable by 1:
let counter = 2; // works the same as counter = counter - 1, but is shorter counter--; console.log(counter); // 1

The operators ++ and -- can be placed either before or after a variable.

  • When the operator goes after the variable, it is in “postfix form”: counter++.
  • The “prefix form” is when the operator goes before the variable: ++counter.

Both of these statements do the same thing: increase counter by 1.

Is there any difference? Yes, but you can only see it if you use the returned value of ++/--.

Let’s clarify. As you know, all operators return a value. Increment/decrement is no exception. The prefix form returns the new value while the postfix form returns the old value (prior to increment/decrement).

To see the difference, here is an example:

let counter = 1; let a = ++counter; // (*) console.log(a); // 2

To summarize:

  • If the result of increment/decrement is not used, there is no difference in which form to use:
let counter = 0; counter++; ++counter; console.log( counter ); // 2, the lines above did the same

If you would like to increase a value and immediately use the result of the operator, you need the prefix form:

let counter = 0; console.log( ++counter ); // 1

If you would like to increment a value but use its previous value, you need the postfix form:

let counter = 0; console.log( counter++ ); // 0 console.log( counter ); // 1

Knowledge Check

let counter = 1; console.log(2 * ++counter); // Statement A let counter = 1; console.log(2 * counter++); // Statement B

What are the outputs of the two console.log statements in the JavaScript code above?

  • Select an answer to view feedback.