Start Javascript: learn about variables
Tags: javascript, beginners, tutorial, codenewbie
Published: 2019-09-04 22:08:35

---
title: Start Javascript: learn about variables
published: true
tags: javascript,beginner,tutorial,codenewbie
canonical_url: https://mindsers.blog/en/learn-javascript-variables/
---

 ![Start Javascript: learn about variables](https://images.unsplash.com/photo-1565945985123-4c67ab31eb8d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ)

Variables are the absolute base of programming. We wouldn't be able to do much without variables. We can find it in all the advanced concept of programming. It would be useless to program without it, dare I say.

We are going to cover the basis regarding variables to be understood by beginner. Though, we will talk about a few interesting points for advanced developers so keep reading.

In this post, you'll learn:

- what is a variable
- how to use it
- a few good practices regarding the use of variables 

## What is a variable?

Variables are a good **way to stock in memory datas that might change overtime.** It doesn't sound like much but it is what makes a program react to what a human does on its keyboard (or any other device really).

A variable has a name so we can call it where we need it in the code. It also has a value. For example, you can say that the variable `abc` has a value: `3`. Where you write `abc` in your code, the computer will replace it with the data stocked in memory. In our example, it is `3`.

As said earlier, the data of a variable can change overtime. Which means that `abc` could have the value `5` if you run the software again or even during the same run of it. This is where the name "variable" comes from. It is a bit of code that can vary depending on several factors.

## How to create a variable?

In JavaScript, the definition of a variable (which is when you create a variable) is made this way:


```js
// keyword name = value
var a = 2
let b = 4
const c = 6

```


The code above creates/defines 3 variables `a`, `b` and `c` which have for values `2`, `4` and `6` respectively.

This is the quick and simplified version of two other actions we've made on the variable. The definition of the variable equals 1) the declaration of the variable, saying we want to create one and keep some memory space for it specifically and 2) the initialization of the variable: giving the variable we just declared a value for the first time.


```js
let a // declaration of the variable a

a = 1 // initialization of the variable a
```


When these two actions are separated, **the variable exists as soon as it is declared but doesn't have a value unless the initialization has been done**. We then say that the variable is undefined because the process of definition is not completed. The variable equals `undefined`.

## The types of variable

We've seen that variables have a name, a value and that we can use keywords to define it. Variables also got a type.

The type is a way to regroup similar variables and take actions on those without really knowing what are their values when we write code.

For example, if I have two variables of the same type "integar", **I know I can add it even though I don't know the exact value** which will be stocked.

There are several types of variables in JavaScript. In the example of the 3 `a`, `b` and `c` variables we already talked about, each variable stocks a number. So the type is `Number`.

Variables can be one of the following types:

- `String`: A string of characters (± text)
- `Boolean`: A variable that can hold only 2 values: `true` or `false`.
- `Array`: A value table.
- `Object`: An object.
- `Number`: A number. It can be integar, positive, negative, decimal.
- `Symbol`: A unique data that can't be changed.

In JavaScript, we do not define the variable type explicitly. The type of a variable can be changed overtime. It doesn't mean variables have no types.

**The JavaScript engine is capable of guessing (or "infer") the type of a variable based on its value**. This feature gives a lot of flexibility to developers but if he wants to make sure a certain type is used, he must check it by himself.

To check the type of a variable, we can use two keywords `typeof` and `instanceof`, and several methods given by the native objects of JavaScript.

`typeof a` will give you the type of variable `a` among the following choices:

- `string`
- `number`
- `boolean`
- `function`
- `object`
- `symbol`
- `undefined`

As you might have noticed, there is no `array` in the list. In fact, `Array` is an object. JavaScript returns `object` as for any other objects.

With the keyword`instanceof`, you can verify that an object "inherits from an other object" or more literally if it can find the prototype of an object in the chain of prototype of another object.


```js
class ClassC {}
const objO = new ClassC()

objO instanceof ClassC // true

```


The example is quite simple and speaks for itself.

I spoke a bit about the methods offered by the language. Among it, you'll find `Array.isArray()`, `Number.isInteger()`, etc. Those methods take in account the value to test and return `true` or `false` depending of the assertion.

In general, the good practice is to prioritize these methods when it exists instead of using other keywords or homemade solutions.

## The declaration

In Javascript, declaration of variable is made with keywords `var`, `let` and `const` as we've seen before. It can be a little tricky in the beginning to choose between those 3 but they have different goals. Let's cover that together.

### The `var` keyword

This is the historic keyword. For a long time, there was just this keyword and no other.

This keyword declare a variable in its execution context, it means the variable will only be available in the function that it is declared in.

```js
// a doesn't exist

function context() {
  var a = 0
  
  // a exists
}

// a doesn't exist

```


If the variable is created in the global scope (or context), meaning outside of all function, the keyword `var` creates a variable in the global object which is `window` in a browser and `global` on a NodeJS server.


```js
typeof window.a === 'undefined' // return true
typeof window.b === 'undefined' // return true

var a = 0

typeof window.a === 'undefined' //return false
typeof window.b === 'undefined' // return true

```

### The `let` keyword

Brought by the ES2015 version of JavaScript, `let` is a keyword that aims at resolving the few problems of `var`.


```js
// a doesn't exist
// b doesn't exist

function context() {
  var a = 0
  // b exists but equals undefined
  
  if (true) {
      var b = 0
      
      // a exists
      // b exists and equals 0
  }
  
  // a exists
  // b exists and equals 0
}

// a doesn't exist
// b doesn't exist
```
<figcaption><code>var</code> doesn't make a difference between the scope of the function and the <code>if</code> scope</figcaption>

In fact, JavaScript will do someting called hoisting. It will read the code of the function, see that we want to define the `b` variable in the `if` and move its declaration at the top of the `context` function but leave its initialization in the `if`.

This behavior, which is very different from other programming languages, causes the variable `b` to exist before the `if`. Its value is `undefined` until its initialization in the  `if`. After that, its value is `0`.

It often causes problems with asynchrone code and makes the code even more difficult to understand and debug.

To avoid this problem, the ES2015 version of JavaScript brought the `let` keyword.



```js
// a doesn't exist
// b doesn't exist

function context() {
  let a = 0
  // b doesn't exist
  
  if (true) {
      let b = 0
      
      // a exists
      // b exists and equals 0
  }
  
  // a exists
  // b doesn't exist
}

// a doesn't exist
// b doesn't exist
```
<figcaption><code>let</code> limits the existence of variables on the containing scope</figcaption>

The `let` keyword allows to declare a variable and to limit it to the containing scope.

A scope is often represented with curly brackets in JavaScript. It means that every code structures having curly brackets define a scope and the variables creates inside those don't exist anymore on the outside.

**Since `let` exists, the good practice is to use it by default instead of `var`.** You will always be able to change it to `var` if needed.

### The `const` keyword

The ES2015 version of JavaScript also brought the `const` keyword. It almost works exactly like the `let` keyword but it allows to modify the variable solely when you declare it.

`const` means "constant". In other words, **it is a variable that never change.** The value you'll give to a constant is the only value it will stock until its deletion.


```js
const a = 0

a = 1 // Uncaught TypeError: Assignment to constant variable.
```


Note that I said it "allows to modify the variable solely when you declare it" not that "it allows to modify the variable solely when you initialize it."  

This is because you can not define the variable in two steps like you would generally with other variables. It is when you declare the variable, and solely at that time, that you can initialize the constants.


```js
const a // Uncaught SyntaxError: Missing initializer in const declaration
```


A good practice is to strictly limit the possibilities of modifying variables. This way, it is good to use rather `const` instead of `let`. You can always change it to `let` if needed.

If we had to make a list of keywords classified by priority, it will be: `const` > `let` > `var`.

Be careful though there is a little trap in JavaScript, pointers and references don't exist explicitly but their heritage are there. Objects are "passed by reference". **The `const` keyword creates an unchanging reference to a value.**



```js
const obj = { name: "Robert" }

obj = { name: "Jean" } // Uncaught TypeError: Assignment to constant variable.

obj.name = "Jean"

console.log(obj) // { name: "Jean" }
```
<figcaption>An object is not unchanging, its reference is.</figcaption>

The `const` keyword prevents us from modifying the reference to an object. It is thus not possible to reallocate a constant containing an object but it doesn't guarantee that the object's attributes are not modifiable.

If you want to prevent attributes of an object to be modified later on, use the `Object.freeze()` method.


```js
const obj = Object.freeze({ name: "Robert" })

obj = { name: "Jean" } // Uncaught TypeError: Assignment to constant variable.

obj.name = "Jean"

console.log(obj) // { name: "Robert" }
```

## Variables' names

In JavaScript, you can name a variable using caps or lower case letters, numbers and `_`. The name can not start with a number.

You'll admit this rule is quite permissive. The dev isn't restrained in its creativity. That being said, I think **all developers should give themselves a few rules** when it comes to naming variable.

### The case

The [case](https://fr.wikipedia.org/wiki/Sensibilit%C3%A9_%C3%A0_la_casse) is using a character in upper or lower case. In programmation there are several norms:  `lowerCamelCase`,  `UpperCamelCase`,  `kebab-case`,  `snake_case`,  `SCREAMING_SNAKE_CASE`, etc. You'll often see a community of developers gathered around the same language choosing the same norm to follow.

For exemple, the Python community likes the _Snake Case_ a lot whereas some other communities prefer the _Camel Case_. Other might even choose depending on the element they're willing to create: _Upper Camel Case_ for objects, _Lower Camel Case_ for scalar or primitive variables and _Screaming Snake Case_ for constants.

I will not be advocating here but here are 3 principles that might help you name your variables:

1. If there is a standard in your language, use it.
2. Once you've found your style, keep it for the entire project.
3. Be consistent throughout the project, be it 1 or 30 developers!

### The meaning

The meaning is important when you name variables. It expresses what is inside the variable depending on the context. A variable name that is meaningful makes the code easier to read, to understand and [limits the need to add comments](https://blog.nathanaelcherrier.com/fr/les-meilleurs-commentaires-ne-secrivent-pas/) (fr).

Avoid names like `a`, `cpt`, `zejqdhalkja`. Names that are too generic too or that can mean different things depending on who reads it (such as `Processor` or `Manager`) are not great either.

Use pronounceable variable names. Name you can actually pronounce are less effort for our humain brain. If I had to quote [Clean Code from Uncle Bob](http://amzn.to/2dD6zcB) which is – for me – a reference on the topic, I'd quote:

> Humans are good at words. A significant part of our brains is dedicated to the concept of words. And words are, by definition, pronounceable. [...] So make your names pronounceable.

Skip mental patterns. When you try to understand a bit of code, you don't want to have to ask yourself this kind of questions: "Wait, what is `r`? ". You're already trying to understand code, you don't want to add to that to try to understand each variable or function names... And you have to remember all of that!

There are a lot of simple advice that can be applied to naming variables and I'm not going to cover it all. I don't think I can talk about it all anyway.

But, I really encourage you to read  [Clean Code from Uncle Bob](http://amzn.to/2dD6zcB) or at the very least - for this topic — the 14 pages he wrote about naming variables. The chapter is called  "Meaningful names".

---

Here you have the basis (and a little more) to be able to use variables. There are a lot more to learn on the matter but it is a good start.

If you want to learn more about variables, you should go read the [article about C/C++ pointers](https://blog.nathanaelcherrier.com/en/pointers-c-cplusplus/). Even is you don't use C, this post will give you useful information about how variables work in C-like languages.

To dig deeper:

- [Ubiquitous Language](https://blog.nathanaelcherrier.com/fr/ubiquitous-language/) (fr): use a specific-to-the-job and common language to name the entities of your code
- [Destructuring in JavaScript](https://blog.nathanaelcherrier.com/en/destructuring-javascript/): discover a specific manipulation for `Array` or  `Object` variables.