JavaScript Basics: Variables

Image for post
Image for post

JavaScript is loosely typed programming language. This means there are variables and types but these aren’t very strict and we can easily swap them around. For example, a variable can hold a number value and then we can assign a string to the same variable:

In strongly typed languages that would be impossible.

Variable simply holds a value or object. For example, numbers: 1, 2, 3 can be the values a variable holds. Variable name must start with _ (underscore), $ (dollar sign) or letter. Variable name can’t be a reserved keyword.

We can declare a variable by using var keyword followed by variable name:

Technically, variables a , b, c have a value of undefined.

We can also create a variable and assign a value:

Variable minAge holds number value of 18.

Moreover, we can declare a variable and assign undefined:

In JavaScript we have following types of variables,

primitive (a primitive value is not an object)

  • number — numeric value, for example: 1 or 3.14
  • string — string of characters, for example: ‘John’
  • boolean — logical value of true and false
  • undefineddefault value when a variable was declared, however the actual value wasn’t assigned yet
  • null — no value
  • symbolsymbol type

and

object — all other types are objects

Let’s try to declare them all:

As we can see array of colors is a treated as object.

Interesting case is the null. Technically, this should produce typeof null === null. Yet, for historical reasons this gives incorrect value of object. There was a change proposed to fix it, yet it was rejected. Therefore, we must remember that null is one of primitive values, its type is null yet typeof returns object.

Another, odd result is function — functions are objects. Yet, the specification of typeof returns function.

One more thing of the past, is the actual var keyword. We can use still use it. However, since ECMAScript2015 it’s better to use newer let and const keyword.

There is a subtle difference between the two. The first one, let allows to reassign a value multiple time:

While, const will allow to assign the value only once. However, lets note const shouldn’t be mistaken with constant. The value can change. It can’t be reassigned only. Let’s see this in action:

However:

We have changed the value but we didn’t use the assignment operator:

In modern days JavaScript the safest way to declare variables is to use const. If we need to change the value then we should use let keyword. Don’t use var anymore.

Written by

Programming, project management and politics

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