Andy from Webcrunch

Subscribe for email updates:

How to REALLY Learn JavaScript Series: Part 2 Variables, Datatypes & Operators
Portrait of Andy Leverenz
Andy Leverenz

February 6, 2015

Last updated November 5, 2023

How to REALLY Learn JavaScript Series: Part 2 Variables, Datatypes & Operators

Today I continue the series on how to REALLY learn JavaScript. I will dive into some aspects of JavaScript that makes it a truly dynamic programming language. Knowing these fundamentals will help you create more complex applications and interactivity within your webpages over time.

This article will cover JavaScript variables and operators. In case you missed the first article of the series be sure to check it out.

Variables

Think of variables like boxes that hold your stuff when you’re moving. You keep the items inside for the sake of being able to move more at once. You can add and remove items as well as a swap for new items if needed. All of these things can be achieved with code as well.

To declare a variable you will make use of the var keyword. Each var keyword is followed by a name you can make up to describe what it is you are declaring.

var myName = 'Andy';

With each declaration, you assign it a property that can be a string of text, a number, or a boolean (true or false). You can also assign variables to functions which I will explain at another time.

Every line in JavaScript should end in a semi-colon. This indicates where a line in the code ends. If these aren’t including your code simply won’t work.

Naming

Variables can be named nearly anything you can think of though there are some restrictions to keep in mind. Below are some basic naming standards within the language.

  • Don’t start a variable name with a numeral. Numbers can be within a variable name but not at the beginning:
var 1password = 'What?'; // illegal
var cutiepie22 = 'Ha!'; // legal
  • You cannot have a mathematical operator in any part of a variable name. Any operator is expected by JavaScript to perform an operation as opposed to being assigned to something like a typical variable:
var sun+day = 'last day of the week'; // illegal
var 3*fast = 'That's fast'; // illegal
  • You cannot use any punctuation in a variable name besides an underscore character:
var my_name = 'Andy'; // legal
var bigBear# = 'Yogi'; // illegal
  • JavaScript has its own keywords that are reserved for the language thus you cannot use them as variable names. I won’t list all of them but you can find them here.
var string = 'A new string of text'; // illegal
var function = function(){ document.write("this won't work")}; // illegal 
var theWindow = 'Is awfully ugly'; // legal
  • Never include spaces in variable names. Like ever.
  • JavaScript is a case-sensitive language. If you capitalize on a character it needs to remain that way to be considered the same variable.

myName MyName byname Myname are all different variable names. Watch your punctuation!

Declaration of Independence or Something Like That

After declaring a variable you give it a name like so:

var myDog = 'Reese';

After the declaration, you can now use the variable myDog to retrieve the value. If you decide to later change the variable you can do so by writing:

var myDog = 'Reese';
my dog = 'Chloe';

The equals(=) sign is an assigner. It is what assigns any variable to a value you supply. This in return gives you the ability to use the variable over and over wherever you please in your scripts.


Datatypes

Variables can be assigned a few different types of values. The datatypes within JavaScript are strings, numbers, booleans, arrays, and objects. I will uncover more about each as I make progress in this series.

Strings

Strings are essentially a group of words surrounded by quotation marks. The quotation marks tell JavaScript that the text within is indeed a string data type.

var myName = 'Andy';

Numbers

Numbers are well, numbers. No quotes are needed. You can write to them as is. Simple enough.

var myAge = '27';

Booleans

Boolean is a fancy word for True or False or 1 or 0 to get all nerdy about it. No quotes are needed when writing True or False.

var myQuestion = false;

Arrays

An Array is a structure that allows you to store multiple values in one single reference. These values can be any other data type. Arrays are great for collecting data as well as outputting data. More on this later.

var myArray = ['Andy', 27, 'false'];

To call back an array you would write something that looks like this:

myArray[0] or myArray[1]

Calling this would return the value that is indexed within the Array. myArray[0] would return Andy as a result and myArray[1] would return 27, etc...

Arrays can be tricky. The index I speak of has a starting point of zero. Humans typically start counting from one but computers start from zero. The more you make use of arrays the more this becomes very easy to understand.

Objects

Objects are pretty much anything in JavaScript and can be stored in a variable. In fact, all of the examples I have written in this article so far are objects. Crazy right? Don’t worry, I’ll dive deeper into objects as we progress in this series. Hang tight!

var myHeading = document.querySelector('h1');

Why Variables?

So why are variables need in JavaScript? Pretty much so you can do anything interesting in programming. Variables make it all happen even though their job is a simple one. If values couldn’t change or be re-assigned then you can forget creating a dynamic situation like a personalized greeting upon visiting a website or counting the number of unique visitors who come to a specific page on a website with services like Google Analytics.


Operators

Operators you might use in everyday life. These were the fundamentals you likely learned back in grade school when taking your first mathematics class. Along with the basics, JavaScript adds a few more to the puzzle.

An operator is a mathematical symbol that can act on two values(or variables)and produce a result. Check out some examples below.

Add/Concatenate ( + )

The addition of concatenation operator (+) is used to add two numbers together or join two types of data like strings for example.

5 + 4; // Numbers

"Hello" + "Friend!"; // Strings

Subtract ( - )

The subtract operator is what you’d expect. Subtract numbers like you would in basic math operations.

5 - 2; // Wow that's tough huh?

// How about a real world example
var myAge = 27;
var myRetirementAge = 67;

document.write(myRetirementAge - myAge); // should return 40

Multiple ( * )

Multiply numbers or values using the basic operation you once used in grade school.

5 * 4; // Multiply in JavaScript is an asterisk and not an "x"

Divide ( / )

Yet another operator that does what you would expect. Divide numbers or values to get the remainder.

100 / 10;

Assignment ( = )

The assignment operator is often mistaken for an equals sign used in basic math. The assignment operator actually assigns a value to a variable. The value changes each time you assign it.

var myName = 'Andy';
myName = 'Dave';

document.write(myName); // Dave

Identity ( === )

The identity operator is commonly used during some type of test. If for instance, you were trying to check and see if an unknown value matched another you can use this operator to help you figure it out. If it matches the boolean ‘true’ will be output and if it doesn’t match like the example below the boolean ‘false’ will output.

var myNum = 7;
document.write(myNum === 3); // false

Not Equal To ( !, !== )

Often times you may need to check for inequality as opposed to equality like with the identity operator ( === ) above. If that is the case JavaScript provides a handy operator for just this reason.

var myNum = 10;
document.write(!myNum === 10);

The basic expression above is true, but the comparison returns false because I have negated it with the Not Equal operator (!).

Below I am testing to make sure myNum is NOT equal to 10. This returns false because it is equal to 10.

var myNum = 10;
document.write(myNum !== 10); // false

More Advanced Operators

I covered what a basic assignment operator was prior to this section but along with the basic operator, I can add additional operators to perform short cuts with my code. Say for instance you would like to add two values together and assign them to a variable. You might think you need a couple of lines of JavaScript to get this done but in reality, you only need one.

Basic Assignment ( = )

a = b // a = b

Addition Assignment ( += )

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable.

a += b // a = a + b

var oranges = 6;
var apples = 4;

oranges +=2 // 8
apples +=3 // 7

Subtraction Assignment ( -= )
The subtraction assignment operator subtracts the value of the right operand to a variable and assigns the result to the variable.

a -= b // a = a - b

var oranges = 6;
var apples = 4;

oranges -=2 // 4
apples -=3 // 1

Multiplication Assignment ( *= )
The multiplication assignment operator multiplies the value of the right operand to a variable and assigns the result to the variable.

a *= b // a = a * b

var oranges = 6;
var apples = 4;

oranges *=2 // 12
apples *=3 // 12

Division Assignment ( /= )
The division assignment operator divides the value of the right operand to a variable and assigns the result to the variable.

a /= b // a = a / b

var oranges = 6;
var apples = 4;

oranges /=2 // 3
apples /=3 // 1.3333333333333333

Remainder Assignment ( %= )
The remainder assignment operator divides the value of a variable of the right operand and assigns the remainder to the variable.

a %= b // a = a %= b

var oranges = 6;
var apples = 4;

oranges %=2 // 0
apples %=3 //  1

Things to Remember

Remember that not all operators play nice together. Adding different types of data can return some unexpected results at times. Be sure you are defining the right values to be equated.

An example is using a string for a number instead of just the number. Luckily JavaScript is smart enough to catch this error and still perform the operation you originally wrote.

12 - '6'; // 6  incorrect way to write it but still works
12 - 6; //   6  correct way

If you try to add strings together thinking they are numbers you will also get unexpected results.

javascript'12' + '12'; // 1212
12 + 12; // 24

Striving for clean code will benefit you in the long term by not allow yourself to make simple mistakes like this that could be costly.

Wrapping Up

We’ve come a long way but there is still plenty to uncover with this series. Be sure to check out the first post of the series if you haven’t read it yet. Up next, I will cover JavaScript conditionals and functions. I hope you are excited!

The Series So Far

Link this article
Est. reading time: 9 minutes
Stats: 386 views

Categories

Collection

Part of the Beginner JavaScript collection