TagNumbers

Variables in JavaScript

In the last post, we talked about conditionals and conditions in JavaScript. We also talked about control flow and Boolean data types in JavaScript.  In this post, we will be building upon all of the subsequent posts and finally talk about variables in JavaScript.

We’ve already seen variables in a few of the examples from before; anytime we typed in the keyword var followed by a symbolic name, such as x or test, we were making use of a variable. So what exactly are variables in JavaScript? A good metaphor for variables is to think of them as labels on containers that hold pieces of data. These labels let you refer to the stored data or the stuff inside the containers when you call them later in the code. Though we haven’t talked about objects yet in JavaScript, we can call the actual container an object in this case.

Declaring and Assigning a Variable

When we declare a variable we follow this syntax: var toast. Try typing this into your console. This statement, var toast is telling the compiler that the word toast, is going to be used as a label to refer to data (note: an empty or unassigned variable always has a value of undefined). In this variable, we can store any of the six basic data types of JavaScript, a string, a Boolean, a number, a null, an undefined or an object.

toastTo assign data to a variable we use the equal sign = like this, toast = 10; and now the variable toast refers to the number 10. If we type in the variable name toast in the compiler now, it should return the number 10. We can also reassign the variable toast to another piece of data like the string "burnt" by simply inputting, toast = "burnt"; into the console. Now, the variable toast will no longer refer to the number 10 but it will instead refer to "burnt".

haskellThe fact that we can reassign our variables in JavaScript makes these variables mutable. In some other languages, mainly functional programming languages like Haskell and Clojure, variables are immutable and are not subject to being reassigned. The ability to reassign variables has its advantages and disadvantages which we will talk about later. While some people might refer to JavaScript as an impure functional programming language, any variable created using the keyword var is mutable.

Rules for Variables

Like anything else in programming, variables in JavaScript are subject to different rules. For example, we can declare as many variables as we like using a structure like this: var a, b, c, d, e, f;.  We can declare and assign variables on the same line: var z = 10; and declare and assign multiple variables on the same line var firstName = "john", lastName = "doe", age = 27;. We can use this last example to easily organize a sentence string: firstName + " " + lastName " is " + age " " years old!" which will output "john doe is 27 years old!" in our console.

You may also use basic operators and methods while assigning data to a variable in JavaScript: var x = 12 + 10; will give us the value 22 as the variable x. You may also concatenate strings, use division, multiplication, or subtraction while assigning a variable. var x = 5 * 2 + 10 +"3"; is a valid declaration and assignment statement in JavaScript and x will have a value of 203.

2nd-variableThere is a set of characters and keywords that should not be used in the name of a variable in JavaScript. You should not use a numeral as your first character in a variable name: 123a is not a valid name for a variable. You also can’t use any of the reserved keywords that are functions or operators in JavaScript as a variable name (a complete list is below this post).  Also, variables are case sensitive in JavaScript; the variable FirstName is different from the variable firstName and the variable A is different from a.

Special Characters and Naming

You may use special characters in variables but the general rule is to avoid them unless there is a specific reason to use one. You may use an underscore _ or an at @ sign to start a variable in JavaScript but idiomatically, you should only use them if you can’t avoid doing so. It is fine to use an underscore _ in the middle of a variable and many people do this. we could rewrite our firstName variable as first-name or first_name and they would be perfectly acceptable.

In programming in general, there is a specific naming philosophy called camel case. In camel case you use a lowercase letter for the first word in the variable and an uppercase letter for every word there after. firstName and lastName follow the camel case naming convention. coolBlackCat is another example of this camel case convention. Pick which ever naming convention you prefer but keep things consistent, if you plan to use camel case in your program then don’t change to underscores or dashes in the middle.

Overview

In today’s post, we talked about variables and the basic rules of variables in JavaScript. We also looked at syntax rules and naming conventions. In our next post, we will start to talk about switch statements to flesh out our ability to use control flow in our programs.

List of Reserved Keywords in JavaScript:

AbstractBooleanbreakbytecase
catchcharclassconstcontinue
debuggerdefaultdeletedodouble
elseenumexportextendsfalse
finalfinallyfloatforfunction
gotoifimplementsimportin
instanceofintinterfacelongnative
newnullpackageprivateprotected
publicreturnshortstaticsuper
switchsynchronizedthisthrowthrows
transienttruetrytypeofvar
voidvolatilewhilewith

Manipulating Numbers in JavaScript

In the last post, we left off with the statement that JavaScript has six different basic types in it.  In this post, we will be focusing on one out of those six: Numbers. We will also go over some of the ways that we can manipulate numbers in the JavaScript console and in our programs. There will be more coding in this post so make sure to open your JavaScript console so that you can follow along. You should try entering all of the examples presented as well as anything else that strikes your curiosity and see what happens; when learning a new language it’s important to explore and use the concepts. Repetition is key to learning any new skill.

Numbers and Arithmetic

arithmeticIn every programming language, the handling of numbers is very important and this is just as true in JavaScript. Because JavaScript is untyped or dynamically typed, its interpreter considers all numbers as though they were double-precision floating point numbers. This allows us to dynamically move from integers to floats and back again. This is also why when manipulating numbers in JavaScript you will often encounter rather strange bugs as well as solutions that make little sense. Luckily, JavaScript has built-in methods that help correct some of these problems. (more on this later.)

In JavaScript, you have basic arthritic operators; addition +, subtraction -, multiplication *, division /, modulus %, increment ++, and decrement --.  You can enter an expression like 2 * 3 into the console and get 6 in return.

You may also assign numbers to variables in JavaScript. To assign a variable, you use the keyword var then the “symbol” of the variable you wish to use and you use an equal sign to assign the variable. For instance, var x = 42; will assign the number 42 to the variable x (note: in the console the semi-colon at the end of a line is not required but you should get into the habit of using one). If you now type x/3 you will get a return value of 14 because the value 42 is stored in the variable x (there will be more on variables later).

Rules and Regulations

There are some rules that are worth explaining when it comes to numbers and arithmetic in JavaScript. An integer in JavaScript is considered accurate up to 15 digits; once you go past 15 digits, some compilers will try to use scientific notation to express the number and others might try to round the number up or down.  For example, 9999999999999999 is rounded up to 10000000000000000 when entered into the console. Ultimately, you will most likely not use numbers that have this many digits because they are simply inaccurate.

console-1Decimal numbers may have up to 17 decimal places before they start to lose their accuracy.  On the same note, floating point arithmetic is pretty imprecise, to begin with in JavaScript. Try entering var x = 0.3 + 0.6 and then see what the value of x is. There are various ways around these little idiosyncrasies; for instance, var x = (0.3*10+0.6*10)/10; will give you a more accurate response. Also, division by 0 will not generate NaN, (short for Not a Number)Null, or undefined but rather infinity or -infinity depending on the values used.

You may enter a hexadecimal as a number and the compiler will automatically convert it back to decimal notation; var x = 0xEEE; will produce an integer. JavaScript also follows its own version of the order of operations. If you type 1+2*3; into the console you would think you would get 6, however, because JavaScript prioritizes multiplication over addition, you receive 7 instead.  Multiplication * and division / have higher precedence than addition + and subtraction - in JavaScript and you may change this precedence at will by using parenthesis.

Weird Basic Operators

The other three basic operators Modulus %, Increment ++ and decrement -- are very strong for certain types of programs. For those of us who did not take an advanced math class in college, a modulus of two numbers is basically the remainder of those two numbers when they are divided. Any fraction that equals a decimal number will have a non-zero modulus or remainder (this is useful for finding primes etc). For example, 30%13 will equal 4, with 30/13 equaling 2 remainder 4 or 2.30769230769…

Incrementing (and Decrementing) are used all the time in programs. When you increment (or decrement) a number you add (or subtract) a set amount to it. In the case of the operators ++ and -- you are just adding (or subtracting) 1 from each number.  If we type var z = 20; and then type ++z; into the console, it will show us 21. If we then look at the value of z, we will see that z has also been changed to 21. However, if we place the operator after the variable, z-- we will get a return value of 21 but z will have changed to 20. This happens because z returns it’s assigned value, 21 in this case before subtracting 1 from it and reassigning the new value to z.  In our original ++z, the incrementation happens before the value of z is returned, thus the new value of z is returned after z is already reassigned. This difference may seem trivial at first but as we build upon our knowledge of programming it will become rather important for sorting through more complex structures and functions.

Closing

Today’s post covered the basic operators of numbers as well as the basic properties of numbers in JavaScript.  Feel free to ask any questions if you do not fully understand any of the topics discussed here (there was a lot of content in this post to swallow at once).   Also, feel free to try anything you want to see what happens; if you come across something that wasn’t explained in the post, comment and you will receive an answer.   In our next post we will talk about three of the other types in JavaScript: Strings, Null and Undefined.