Giter Club home page Giter Club logo

fewpjs-js-fundamentals-variables's Introduction

JavaScript Fundamentals: JavaScript Variables

Learning Goals

  • Define a variable
  • Name variables in JavaScript
  • Initialize variables in JavaScript
  • Identify when to use const, let, and var for declaring variables

Introduction

Previously, we saved some information into a variable. "Saving" to a variable allows us to save a result so we can use it again later. Storing calculations to temporary storage places is the heart of making efficient programs. It's a simple idea that has powerful consequences--but for the moment, let's look at the options we have when it comes to storing information.

Define a Variable

A variable is a container in which we can store values for later retrieval.

Imagine a box that can hold any type of data: a number, string, boolean, object — even an undefined. We take some data that we want to store, place it inside the box, and hand the box off to the JavaScript engine, which stores it in memory. All done! Our data is safely cached until we need to access it again.

But wait! When we ask for the data back, how will the JavaScript engine know which box to retrieve? We need to assign a name to our variable — a label for our box — so that we can tell the engine exactly which piece of stored data we want to access.

Name Variables in JavaScript

Variable names in JavaScript can sometimes be complicated, but if you follow these three rules you'll be fine:

  • Start every variable name with a lowercase letter. Variable names starting with a number are not valid.
  • Don't use spaces — camelCaseYourVariableNames (see the camel humps?) instead of snake_casing_them (like the underscore is a snake that swallowed the words).
  • Don't use JavaScript reserved words or future reserved words.

It's important to note that case matters, so javaScript, javascript, JavaScript, and JAVASCRIPT are four different variables.

Initialize Variables in JavaScript

The var reserved word is the classic way to declare a variable. It's been around since the inception of JavaScript, and it's what you will encounter in any pre-ES2015 code.

Creating new variables in JavaScript is really a two-step process. First, we declare the variable:

var pi;
//=> undefined

The JavaScript engine sets aside a chunk of memory to store the declared variable. Then, we assign a value to that variable:

pi = 3.14159;
//=> 3.14159

We can package both of the initialization steps — declaration and assignment — in a single line of code:

var pi = 3.14159;
//=> undefined

Multi-line Variable Assignment

Let's say I needed to declare and define multiple variables. It feels like a lot to have to repeat var over and over again. JavaScript allows us to do multi-line variable assignment to alleviate this pain. Every variable must be separated with a comma, and the entire line must end with a semicolon.

Let's condense the below code into one line:

var a = 5;
var b = 2;
var c = 3;
var d = {};
var e = [];

The above is equivalent to:

var a = 5,
    b = 2,
    c = 3,
    d = {},
    e = [];

which can be converted to:

var a = 5, b = 2, c = 3, d = {}, e = [];

Retrieving Variables

To retrieve a declared variable, refer to its name:

pi;
//=> 3.14159

Reassigning Variable Value

Changing the value of a variable in JavaScript works as follows:

var pi = 3.14159;
pi;
//=> 3.14159
pi = 3.14;
pi;
//=> 3.14;

Variable Values

Upon declaration, all variables are automatically assigned the value of undefined. It's only after we assign a new value that the variable will contain something other than undefined. We can use the typeof operator to check the data type of the value currently stored in a variable:

var language;
//=> undefined

typeof language;
//=> "undefined"

language = "JavaScript";
//=> "JavaScript"

typeof language;
//=> "string"

Top Tip: When writing JavaScript code, it's good practice to never set a variable equal to undefined. Variables will be undefined until we explicitly assign a value, so encountering an undefined variable is a strong signal that the variable was declared but not assigned prior to the reference. That's valuable information that we can use while debugging, and it comes at no additional cost to us.

Once a variable has been created with var, we can reassign it to our heart's content:

var pi = 3.14159;
//=> undefined

typeof pi;
//=> "number"

pi = "the ratio between a circle's circumference and diameter";
//=> "the ratio between a circle's circumference and diameter"

typeof pi;
//=> "string"

The data that's stored in our variable might change over time, but at any moment we can retrieve its current contents:

var language = "Mocha";
//=> undefined

language = "LiveScript";
//=> "LiveScript";

language = "JavaScript";
//=> "JavaScript";

language;
//=> "JavaScript";

Identify When to Use const, let, and var for Declaring Variables

Because of its ubiquity in legacy code and StackOverflow posts, it's important to get to know var. However, as we alluded to earlier, there is almost no reason to use var with the features JavaScript has post-2015. var comes with a ton of baggage in the form of scope issues (which is a whole other topic), and allows developers to play a little too fast and loose with variable declarations.

let

ES2015 introduced two new ways to create variables: let and const. Both solve all of var's scope issues, which, again, we'll cover in the lesson on scope in JavaScript. Both also throw an error if you try to declare the same variable a second time:

let pi = 3.14159;
//=> undefined

let pi = "the ratio between a circle's circumference and diameter";
//=> Uncaught SyntaxError: Identifier 'pi' has already been declared

note: in some browsers the console won't throw this error if you try the above code there. However, you will get the error when developing your app.

Just like with var, we can still reassign a variable declared with let:

let pi = 3.14159;
//=> undefined

pi = "the ratio between a circle's circumference and diameter";
//=> "the ratio between a circle's circumference and diameter"

typeof pi;
//=> "string"

const

Using let instead of var will help you avoid silly errors like declaring the same variable at two different places within your code, but there's an even better option to use as your default: const.

Declaring a variable with the const reserved word means that not only can it not be redeclared but it also cannot be reassigned. This is a good thing for three reasons:

  1. When we assign a primitive value (any type of data except an object) to a variable declared with const, we know that variable will always contain the same value.
  2. When we assign an object to a variable declared with const, we know that variable will always point to the same object (though the object's properties can still be modified — more on this in the lesson about objects in JavaScript).
  3. When another developer looks at our code and sees a const declaration, they immediately know that variable points to the same object or has the same value every other time it's referenced in the program. For variables declared with let or var, the developer cannot be so sure and will have to keep track of how those variables change throughout the program. The extra information provided by const is valuable, and it comes at no extra cost to you! Just use const as much as possible and reap the benefits.
const pi = 3.14159;
//=> undefined

pi = 2.71828;
//=> Uncaught TypeError: Assignment to constant variable.

NOTE: With let, it's possible to declare a variable without assigning a value, just like var:

let pi;
//=> undefined

pi = 3.14159;
//=> 3.14159

However, because const doesn't allow reassignment after the variable is initialized, we must assign a value right away:

const pi;
//=> Uncaught SyntaxError: Missing initializer in const declaration

const pi = 3.14159;
//=> undefined

As your JavaScript powers increase with experience, you'll develop a more nuanced understanding of what to use where. However, for now, this is a good rule of thumb:

  • Use var... never.
  • Use let... when you know the value of a variable will change. For example, a counter variable that starts at 0 and is subsequently incremented to 1, 2, 3, and so on. In the lessons on looping and iteration in JavaScript, let will have its moment in the spotlight.
  • Use const... for every other variable.

Best practice is to always declare variables with const and then, if you later realize that the value has to change over the course of your program, circle back to change it to let.

Conclusion

We covered what a variable is, how to initialize and retrieve it, and how to assign its values. We also looked at best practices for using var, let and const.

Resources

fewpjs-js-fundamentals-variables's People

Contributors

drakeltheryuujin avatar sylwiavargas avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.