JavaScript for the Complete Beginner | Part 2 — Variables

Last lesson we talked about why JavaScript is a good language to learn. Now we’re going to dive into JavaScript. To follow along, open this link in another window. I suggest that you minimize both pages so that each fits half the screen so that you don’t have to constantly jump back and forth.

Welcome to the Console

Every browser has a console that allows users to interact with the webpage. Though you can find a console in the developer tools of your browser, the link I provided will give us a uniform and clean slate on which to work. Try testing it out. type 2 + 2 and press enter. If you saw it return 4, great! It works. Let’s talk about variables.

Variables

If you’ve studied basic algebra, you should understand what a variable is. It’s a container for another value. x is probably the most popular variable name. When I say x + 2 = 3, I’m stating that we have an unknown number we’ve called x and that this unknown number plus two is equal to three. The main thing to understand here is that x is not referring to the letter x itself, it’s a placeholder we’ve placed there until we figure out what the unknown value is. JavaScript, like all programming languages, uses variables. An important part of being a good programmer is giving variables good names. E = mc² might work for a single equation, but a single JavaScript application might have thousands of variables. Don’t get lazy with your variables names.

Using camelCase 🐪

Different languages and people have different standards for naming variables. In JavaScript the standard is camelCase. That is, we leave the first letter lowercase, and if our variable is more than one word, we capitalize every following word instead of putting a space in between. camelCase is camelCased. amountOfIceCreamConsumed is camelCased. Programming languages don’t like spaces. Don’t use them in variable names.

Practice Time

Let’s go ahead and practice. Go to your console and type:

currentYear = 2020;
2 + 2;
// -> 4
currentYear - 10;
// -> 2010
currentYear = 1;
// -> 1

Declaring and Assigning Variables

Time to memorize some terms. When we create a variable for the first time, we need to declare it using a declaration like var before it:

var currentYear;
// -> undefined
var currentYear;
// -> undefined
currentYear = 2020;
// -> 2020

Summary

You declare a variable before you use it:

var newVariable;
// -> undefined
newVariable = 10;
// -> 10
var newVariable;
newVariable = 10;
// -> 10
//-OR-var newVariable = 10;
// -> 10

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store