DEV Community

loading...
Cover image for Everything You Should Know About Javascript Variables

Everything You Should Know About Javascript Variables

codenutt profile image Jared Updated on ・9 min read

Front Matter

I'm a firm believer in deliberate practice and also the idea that the best way to learn something is to teach it. This article will focus solely on javascript variables. We'll go over things like types, coercion, scope, hoisting and some style choices.

Really, this is just an excuse to make more title cards. I do it all for the graphics.

Laughing Lion

Video

If you prefer to watch, instead of read, check out the companion video!

What is a variable?

First things first, let's get a good definition.

A variable is a named location for storing a value. That way an unpredictable value can be accessed through a predetermined name. - MDN

Think of it as a placeholder.

When you say to yourself, "I need to remember all this information later, but I only want to remember one word"...that's a variable!

See, I suffer from short-term memory loss.

Types

JS is a dynamically typed language, so we generally don't have to worry about assigning the type of data that is being stored in that variable. However, knowing the types makes debugging a lot easier.

Variables don't have types, but the values in them do. These types define intrinsic behavior of the values. - Kyle Simpson

JavaScript defines seven built-in types:

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol -- added in ES6!

Note: All of these types except object are called "primitives".

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. - MDN

null

Represents the intentional absence of any object value - MDN

null is something you (the human) use to purposefully say, this variable has no value.

I'm not worthless!

General Usage

Consistent way of returning from a function that doesn't yield results:

    function return3 (value) {
        if(value === 3) { return value }
        else { return null }
    }

    return3(2) // null

If we didn't tell it to return null, it would return undefined.

undefined

Defines a variable that does not have a value. In other words, the JS Engine is aware that a variable exists, but it has no value. This may seem similar to null but they are different. The main difference is that null is a defined value, whereas undefined is not. For a great article about this specific topic, check this out.

    let b;
    console.log(b) // undefined

boolean

Simple true or false

    let falseVariable = false

number

The number in JS differs from other programming languages that define what type of number, e.g. float, integer, etc. Instead, JS uses the double-precision 64-bit floating point format (IEEE 754). That means you don't have to worry about the type of number when declaring it. Just declare away!

    let four = 4;
    let fiveish = 5.1;
    console.log(four + fiveish) // 9.1

General Usage

A value you expect to do something computational with, e.g. math.

string

A sequence of characters. For example, this sentence.

    let someString = "I'm a string!"

General Usage

Storing information to display to the user.

object

An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). - MDN

    let car = {
        color: "red",
        miles: 400,
    }

    console.log(car.color) //red

General Usage

Everything. Which, is only partially a joke. I use JS objects to pass data around in an application.

A note about the Array

Technically speaking, an Array is an object. If you don't believe me run this in the console:

    typeof [1,2,3] === "object";

However, as Kyle Simpson notes:

It's most appropriate to think of them (arrays) also as a "subtype" of object (see Chapter 3), in this case with the additional characteristics of being numerically indexed (as opposed to just being string-keyed like plain objects) and maintaining an automatically updated .length property.

symbol -- added in ES6!

Unique Identifiers. No two symbols will ever be the same. Useful as object keys, in large data structures.

Avoid Naming collisions

Gotta be honest, I haven't used this in the real world, so maybe someone has a good example to share! However, I found a really good overview of symbols here.

Bonus!

undeclared

Undeclared means that the variable you are trying to access is not available in the scope, which we'll talk about in length in a minute. The error you will see is ReferenceError: x is not defined .

Declaring variables

There are three different ways to declare a variable in Javascript. We're going to talk about all three: var , let and const .

var vs const vs let

It's been a minute since const and let were standardized into the JS Spec (2295360 as of the minute I'm writing this).

var

Old school way of defining a variable in JS. It was king of the block for a long time, until it's much more specific brothers came long.

  • can be changed
  • scoped globally or locally to an entire function regardless of block scope.

let

  • can be changed.
  • scoped to the block.
  • let variables are not initialized until their definition is evaluated. - MDN

const

  • cannot be changed after instantiation.
  • scoped to the block.

when to use let vs const

There are two camps about how to approach when to use what.

  1. I don't trust anyone
    1. This method says, use const first for every variable. If the need comes along that you need to change a variable after it's been declared, change it to let.
  2. I trust myself
    1. This method says, use let for everything. If the need comes along that you need to make sure a variable can't be changed, change it to const.

Moral of the story here:

  • Don't use var anymore. If you're worried about compatibility in browsers, it has 94% global compatibility. If that still isn't good enough (there are some edge cases), you probably should use Babel to poly-fill other things anyways.

Coercion

What if I told you that you could change the past.

You gotta put your past behind you.

Check it out.

    let threeString = "3";
    let threeNum = 3;

They look different right? One is obviously a number and one obviously a string .

If we do this, you'd expect it to throw an error:

    let sum = threeString + threeNum

But it doesn't! JS "coerces" threeString into a number so it can do math. Thanks JS...I think? In this scenario, it's probably fine. However, you can run into issues if you are trying to evalute an expressions "truthy-ness". Check out this article for an even DEEPER dive.

Scope

Scope in Javascript refers to:

The current context of execution. - MDN

This means different things depending on whether we are talking about the old school var or the new school const / let . Scope comes in two flavors: local and global.

Global

Global scope is anything at the top level of the file.

    var globalVar = "I'm global!"
    let globalLet = "I'm also global!"
    const globalConst = "I'm global too!"

    function someFunction() {
        console.log(globalVar); // I'm global!
        console.log(globalLet); // I'm also global!
        console.log(globalConst); // I'm global too!
    }

Local

The definition of local scope changes slightly, depending on whether you are talking about var or let/const.

var (functional scope)

A var statement when called within a function, is available anywhere in that function. For example:

    function someFunction() {
        if(true) {
            var localScope = "Yo! Call me!"
            console.log(localScope) // "Yo! Call me!"      
        }
        console.log(localScope) // "Yo! Call me!"
    }

As long as it's within that function, it's available to be called.

let and const (block scope)

The new kids on the block let and const are BLOCK scoped, which means they are only available within the block they are in.

Examples of blocks are: if/switch statements, for/while loops. Or, as described expertly in this article:

Generally speaking, whenever you see {curly brackets}, it is a block.

Using the same example:

    function someFunction() {
        if(true) {
            let localScope = "Yo! Call me!"
            console.log(localScope) // "Yo! Call me!"      
        }
        console.log(localScope) // Uncaught ReferenceError: localScope is not defined
    }

Hoisting

Per the MDN docs:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

More simply put:

all declarations, both variables and functions, are processed first, before any part of your code is executed. - Kyle Simpson

When a var statement is hoisted to the top of the context, it is assigned a value of undefined .

    hoistedVar = "I've been hoisted!";
    var hoistedVar;

    console.log(hoistedVar) // I've been hoisted!

What better way to understand it than using Tyler McGinnis' amazing Javascript Visualizer! As you can see, both variables are given a value of undefined as soon the Creation phase starts. This allows the compiler to assign the value of "I've been Hoisted" to the value when it parses through the code during execution.

Hoisting in action)

Let and Const Caveat

let and const are not hoisted in the same way that var is. var is initialized as undefined when they are hoisted. let and const remain uninitialized until the statement is evaluated by the compiler. Thanks, Bergi, for the insight.

Therefore, using the same example:

    hoistedVar = "I've been hoisted!";
    let hoistedVar;

    console.log(hoistedVar) // Uncaught ReferenceError: 
                                                    //Cannot access 'hoistedVar' before initialization

Style Choices

Stylish Timon

Casing

When you declare variables, there's a bunch of different options. The style is up to you, but just keep it consistent.

Camel Casing (Dromedary)

    let camelCasedVar = "Im camel cased"

This is used for common variables throughout my applications.

Camel Casing (Pascal)

    let PascalCasedVar = "Im Pascal cased"

I use Pascal casing for Classes or Components.

Snake Case

    let snake_case_var = "Sssssnake case"

This method is pretty common in PhP, for whatever reason, but I haven't seen it much in JS land. I don't really like it anyways, so I don't use it anymore.

Kebab-case

    <input id="kebab-case-input">

According to StackOverflow, this convention is known colloquially as kebab-case. While this method can't be used by JS, it is a common convention in HTML. I try to avoid it for reasons mentioned below.

What I use

I typically use camel casing, for everything (CSS, JS, HTML). For one, it seems to be pretty standard about the JS world, but also because it makes writing out selectors a little cleaner/consistent.

Consider the example below:

    <form action="/" id="form">
      <input type="text" id="kebab-case">
      <input type="text" id="camelCase">
      <button type="submit">Submit</button>
    </form>
    // When we submit form data, we can access it via the event parameter.  
    let form = document.getElementById("form")
    form.addEventListener("submit", function(event) {
        event.preventDefault();

            // if we use hyphens, we have to use brackets/quotes to get the value
        const kebabInput = event.target["kebab-case"].value

            // if we use anything without special characters, we can use dot notation
        const camelInput = e.target.camelCase.value
    }, false)

I think this makes for cleaner code, but I'll leave that up to you to debate.

What do I call this variable?

Now that you know where you're going to be able to access it, and whether you can change it or not, it's time to name it! If you're like me, it takes a good five minutes to settle on a variable name. Over the years, I've come across some helpful tips to avoid that wasted time. The most important one:

Name it what it is.

Wow, what great advice.

Rafiki

I know it sounds simple, but just think about what exact information is going to be held in this variable and what you're going to do with it. Try to avoid using single character variables like i, e or p. Use whole words. If your text editor is any good, it'll autocomplete those for you anyways.

Reserved Words

Just a note, there are a bunch of reserved words in JS. For instance: abstract, var and boolean. You can check them all out here.

Final Thoughts

Wow, we made it to the end. Congratulations! Honestly, there is a lot of information here. We talked all about types, hoisting, coercion, and threw in some ES6 for flavor. There's no way we covered it all.

Did I miss anything? What other topics should we explore together?

Leave a comment below!

As always, happy coding!

Lion King Walking Montage

Resources

Paid Courses

ES6 for Everyone

Free

Carbon

Eloquent JavaScript

Var, let and const- what's the difference?

https://tylermcginnis.com/var-let-const/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

https://www.tutorialspoint.com/javascript/javascript_variables.htm

https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec

Discussion (4)

pic
Editor guide
Collapse
devdufutur profile image
Rudy Nappée


In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods.

Actually numbers and strings do have methods 😉

Collapse
codenutt profile image
Jared Author

So, I looked into this because I was curious. The types themselves are in fact primitives and immutable, however, as noted in MDN:

That's why Primitives are immutable - instead of working on them directly, we're working on a copy, without affecting the original.

When we say let string = "some string", the "some string" portion is a primitive, however, that variable is wrapped in a String class, which does have methods.

Reference: developer.mozilla.org/en-US/docs/G...

Thank you for pointing that out and making me dig deeper!

Collapse
codenutt profile image
Jared Author

That is a good point!