Using Variables and Conditionals in JavaScript

Using Variables and Conditionals in JavaScript

All programming languages have a need for variables, for without them, we wouldn’t be able to get much done! Variables will allow us to keep track of all kinds of data such as a customer email, the position of an image, or the text from a form. It can hold whatever we need it to for our programs to work. The variable is the named container or small piece of computer memory that holds our data. Moving beyond variables, we’ll start looking at conditional statements. Let’s take a closer look!


Creating JavaScript Variables

Any of the following are valid variable declarations:

The keyword var is part of the JavaScript language and is used to declare a variable. We simply use the keyword var followed by the name we want to use to identify our spot in memory which will hold our data. We are free to name our variables anything we want, so go crazy! Be sure to use something descriptive that may describe what you would like to contain inside. Actually, we can name it almost anything, but keep these points in mind:

Variables are written as one word and can be made up of letters, numbers, underscores, or $ signs. There are no spaces and the order of numbers is important. For example:

will not work, however

will work just fine.

Reserved Names

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

Assigning Values to Variables

Upon declaration, our variables will be undefined. Many times, if we are creating a variable, we will also assign a value in the same step.

The = sign is the assignment operator. It is an instruction or command, it does not hold the traditional equals meaning!

note: We have been talking a lot about that var keyword, and if you have done some JavaScript programming you will know that sometimes, you see variables defined with no var keyword. What is that all about?! Well, this is another area, much like semicolon insertion, where JavaScript is attempting to allow you to be sloppy. Resist the urge! If there is no var keyword present, JavaScript will look for an existing variable of that name and if it doesn’t find one, will create it. By leaving off var, you can encounter unexpected results, and make debugging more difficult than it needs to be.

Case Sensitive Variables

JavaScript Variables are also case sensitive. This is important! If you have a variable in your program such as y = 10, and then later on in the program you need to update that value say to 100, if you mistake the case like so Y = 100, no errors will be thrown and you will have no idea that you just created a second variable with the value of 100, and your first variable will remain at 10! It pays to be careful with your JavaScript case.

Multiple Variable Declaration

You can declare several variables at once by separating with commas:

You can also assign multiple values in a similar way:

Weak Typing

In a language like C, on which JavaScript borrows some of its syntax, you need to specify the type a variable will hold upon declaration. JavaScript has no such requirement and this is what is called, a weakly typed language, the same as PHP. With a weak type system, you simply declare your variable and then assign whatever you want to it. This could be a string, number, boolean, object, function, or array.

x starts as undefined

x now contains the number 200

x now contains the string hello

x is now true

x is now false

Undefined

undefined means a variable has been declared but has not yet been assigned a value.

Null

null is an assignment value. It can be assigned to a variable as a representation of no value.

Number

JavaScript has a single number type. Internally, it is represented as 64-bit floating point. Unlike many other programming languages, there is no separate integer type, so 7 and 7.0 are the same value. This is a nice feature since we do not need to worry about overflow in integers. This helps to avoid numeric type errors.

String

A string can use single or double quotes. I prefer to use single quotes in my JavaScript, and double quotes in JSON. This way, it help to lessen confusion between the two. All characters in JavaScript are 16 bits wide. JavaScript does not have a character type. To represent a character, just make a string with one character in it. A cool feature in JavaScript stings is the length property. You can find a strings length by doing something like

Booleans

true or false


Conditional Code

Beyond very basic JavaScript one line commands, we need to start being able to ask questions in our code, and run blocks of code that only execute under specific conditions. The first conditional we’ll look at is the oh so reliable and popular if statement.

We need to get some terminology straight at this time as well in the form of parentheses, brackets, and braces.

( these are parentheses! )
[ these are brackets! ]
{ these are braces }

These guys always come in pairs, an opening will always have a closing.

We can see the if statement puts a condition within parentheses, followed by some code contained between braces. The code between the braces only runs if the condition between the parentheses is true! In this example there is only one JavaScript statement to run, however you could include thousands of statements in between those braces to run! That would likely not happen though 🙂

The condition between parentheses must evaluate to either true or false. All conditions must boil down to simply true or false.

Equality in JavaScript

If in the condition you are asking if something is equal to something else, you will never use the single = sign! As we already discussed in variables, the = is used only to assign a value. It reads right to left in a sense. Take this value on the right of the = sign and assign it to the name on the left of the =.

double equals

A comparison using the double-equals operator will return true if the two things being compared are equal. There is a bit of a catch with the double-equals though, and that is if the comparison being made is between two different types of values, type coercion is the result. This can cause some strange things to happen:

triple equals

This is why the masters of JavaScript recommend to use the triple-equals operator as this type coercion is avoided. If we rerun the example using the triple-equals, we’ll get something more along the lines of what we might expect:

Here is a nifty little example using the triple-equals operator in addition to an if conditional:

javascript conditional if statement

We can also make use of if else conditional statements like so:

In this example we’ll make use of an if else if else

Just like other programming languages, you can make use of the switch statement as well:

Try running this code in your firebug console and see what day it is for you!