DEV Community

Nathanaël CHERRIER
Nathanaël CHERRIER

Posted on • Originally published at mindsers.blog on

Start Javascript: learn about variables

Start Javascript: learn about variables

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:

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

Enter fullscreen mode Exit fullscreen mode

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.

let a // declaration of the variable a

a = 1 // initialization of the variable a
Enter fullscreen mode Exit fullscreen mode

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 keywordinstanceof, 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.

class ClassC {}
const objO = new ClassC()

objO instanceof ClassC // true

Enter fullscreen mode Exit fullscreen mode

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.

// a doesn't exist

function context() {
  var a = 0

  // a exists
}

// a doesn't exist

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

The let keyword

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

// 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
Enter fullscreen mode Exit fullscreen mode
var doesn't make a difference between the scope of the function and the if scope

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.

// 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
Enter fullscreen mode Exit fullscreen mode
let limits the existence of variables on the containing scope

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.

const a = 0

a = 1 // Uncaught TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

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.

const a // Uncaught SyntaxError: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

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.

const obj = { name: "Robert" }

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

obj.name = "Jean"

console.log(obj) // { name: "Jean" }
Enter fullscreen mode Exit fullscreen mode
An object is not unchanging, its reference is.

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.

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

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

obj.name = "Jean"

console.log(obj) // { name: "Robert" }
Enter fullscreen mode Exit fullscreen mode

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 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 (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 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 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. 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:

Top comments (12)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

const defines a constant. Constants are not variables. The clue is in the names:

  • 'constant' - a place to store a value that once set, remains CONSTANT
  • 'variable' - a place to store a value that remains VARIABLE, i.e. can later be used to store another value
Collapse
 
robbevwinckel profile image
robbevwinckel

In Javascript const is a bit misleading. It does not define a constant, but it's a one-time assignment. It's a constant reference to a value.

Because of this you can not change constant primitive values, but you can change properties of a constant object.

Collapse
 
mindsers profile image
Nathanaël CHERRIER

Most people don't understand that when it comes to learning, the most important is not be absolutely true but to make connection between notions.

Can you tell me why almost every article/tuto/course I found by googling "What's a variable" explains constant as "a type of variables"? By doing that we tell the readers that what he just learned with variables is still valid for constants but one thing changes: he can't change the value of a constant. He doesn't have to know more when he just started to learn to code.

Also, what I find interesting in the JS documentation is the sentence:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

It seems like, here, a constant is a variable.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Not at all - it is a constant holding (or having a reference to) one 'thing'. The fact that the thing can be changed internally doesn't mean it isn't still the same 'thing' (like if I change my shoes from blue to red, I'm still me). The 'thing' that the constant is 'storing' cannot be changed to a different 'thing'.

This is the fundamental difference between 'variables' and 'constants' and should be taught right from the start so as to avoid any confusion later. It isn't difficult, the names describe the behaviour. A variable is variable, a constant stays constant

Thread Thread
 
mindsers profile image
Nathanaël CHERRIER

The 'thing' that the constant is 'storing' cannot be changed to a different 'thing'.

This is the fundamental difference between 'variables' and 'constants' and should be taught right from the start so as to avoid any confusion later.

When the article say:

The value you'll give to a constant is the only value it will stock until its deletion.

It's not clear enough?

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The issue is with referring to a constant as a variable. This is simply wrong and generates unnecessary confusion. Your description of the behaviour of a constant however, is completely acceptable

Thread Thread
 
mindsers profile image
Nathanaël CHERRIER

Then, you can start a proposal to change that in the TC39 and Ecma 262 specifications because they are currently referring to a constant as a variable:

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.

source: tc39.es/ecma262/#sec-let-and-const...

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

A javascript specification (that defines at a technical level the way a const is implemented in the language) and how best to teach programming concepts to beginners are 2 entirely different things :)

Collapse
 
volomike profile image
Mike Ross 🇺🇸

Here's something fun to show people. Watch how long the JSON string becomes between an array and an object in these two scenarios:

var a = [];
a[1111] = 1234;
a[2222] = 1234;
console.log(JSON.stringify(a));

as opposed to:

var a = {};
a[1111] = 1234;
a[2222] = 1234;
console.log(JSON.stringify(a));

Key point -- you'll often want to use objects instead of arrays.

Collapse
 
curtisfenner profile image
Curtis Fenner

I'm going to be nitpicky.

Variables in JavaScript do not have types. They have values, and those values have types. This is important to understand JavaScript, as it is to understand other dynamically typed languages; there is no restriction on which types of values any given variable can take on.

The JavaScript engine is capable of guessing (or "infer") the type of a variable based on its value

JavaScript does not do any inference, as it has no static type system. This is called reflection, and it is not a guess -- the language is mandated to keep the bookkeeping records which make it possible to determine, dynamically, what the type of any value is (again, not variable, but value).

Collapse
 
mindsers profile image
Nathanaël CHERRIER • Edited

Thanks for reading and sharing your thoughts. I really appreciate.

Talking about if it's the variable or its value that has a type is like asking if it's the egg or the chicken that appears first. Given that in JavaScript a variable always has a value and a value always has a type, I think we can say a variable has a type even if this type can change (when the value change though).

Collapse
 
kritikgarg profile image
kritikgarg • Edited

👌 This is a fantastic introduction to variables in Javascript, Nathanaël! 🙌You've done an excellent job of breaking down the concept in a way that's easy to understand, making it a valuable resource for those new to the language. I'm looking forward to reading more of your insightful posts in the future!

👀 Recently, I came across an 📰 informative article at Guide to Salesforce Flow Variables.💡 Found it to be a 💯 great resource for those interested in learning about flow variables in Salesforce! 🌟It provides a complete guide on flow variables, which is really helpful for beginners. Highly recommended!