Skip to main content

Building Blocks in JS

Variables

An application requires data to work, data is the fundamental ingredient required to create an application. When we scroll through Instagram, we see "content", right? But what is it really? It is just data! A ton of data that is consumable. A user interface requires data to work! All the beautiful components we build require data to work. Say we make a basic element to render text content, to help you imagine what I mean, say there is a box with a title and text on it.

So in the above card, we see that it is of a particular width and height, with a border! But that would mean nothing without actual data to be rendered.

So, to store this data, we need a container, right? What is the container in the context of a programming language? Yeah, you guessed it, Variables.

Variables are containers for storing information.

function printMessage() {
  var message = "Hello";
  console.log(message);
}

Consider the above code, a function to print a message. Here var message is called a variable declaration. And "hello" which is the actual content is saved in it.

Remember how we put Laddus in a box in our house? Laddus here is the content and the box is the variable. It is called a variable because once you finish eating those laddus, you might put some chips inside of it! The content can vary but the container remains the same, right?

Image generated using Microsoft copilot

Variable Declaration

To create a variable in Javascript, we need to use the keyword var or let and then the variable name.

let message;

In the above code, the variable message is created. The process of performing the above is called variable declaration. In other words, getting a box, an empty box with nothing inside of it.

Now, we can add some data to this variable.

message = "hello";

Another way of doing this would be assigning the data at the time of declaring.

let message = "hello";

What is the difference between the two? It is equivalent to bringing a box of Laddus vs getting an empty box and then putting in some laddus to it. It is as simple as that.

When we assign "hello" to the variable, the memory that was associated with the variable now holds the data.

We can declare multiple variables together, similar to getting multiple empty boxes together.

let name, age, gender;

These are our 3 empty boxes.

We could get 3 boxes with things in them as well.

let name = "Shrikanth"; age = 28; gender = "male";

Another way of doing it would be:

let name = "Shrikanth";
let age = 28;
let gender = "male";

Did you know? ( optional read )

We could also declare a variable using the var keyword, which declares the variable globally, vs let declares within a scope. More about this is discussed in the future articles.

Variable naming rules

In JavaScript, variable names must adhere to specific syntactical rules.

Let's discuss some of them:

Firstly, they cannot start with a number. For example, names like 1stPlace or 2ndValue are invalid, and attempting to use them will result in a syntax error. Variable names must begin with either a letter (A-Z, a-z), an underscore (_), or a dollar sign ($). Following the initial character, variable names can include letters, digits (0-9), underscores, or dollar signs. This means names like pokemon1, _pokemon, and $pokemon are all acceptable.

Additionally, variable names in JavaScript are case-sensitive, so myVariable, MyVariable, and MYVARIABLE are all 3 different variables. It’s important to be consistent with naming conventions to avoid confusion. For example, while you could use userAge or user_age, mixing styles within the same project should be avoided to maintain readability and coherence. Although, it is recommended to name variables in camelCase, and, I would highly recommend doing so.

Lastly, while variable names can be long and descriptive, they should avoid including spaces or special characters (except underscores and dollar signs) to ensure compatibility with JavaScript's naming conventions.

Some examples of valid variable names:

let $ = "Dollar";
let _ = "This is an underscore";

Note: Although the code is mostly written in English, to the best of my knowledge, we can use any other language to declare variables, for example

var 我 = "Blah";

is a valid declaration!

Some invalid names would be

let 123Blah = "Hello";
my variable = "invalid"; // Invalid because variable names can't contain spaces.
my-variable = "invalid"; // Invalid because `-` is not allowed in variable names.
my@variable = "invalid"; // Invalid because `@` is not allowed in variable names.
function = "invalid"; // Invalid because `function` is a reserved keyword.
class = "invalid"; // Invalid because `class` is a reserved keyword.


Reserved names

In JavaScript, certain words are reserved by the language because they are integral to the language's syntax and functionality. These reserved keywords, such as var, let, const, if, for, while, and return, are used to define the structure and control flow of the code. Attempting to use these reserved keywords as variable names will result in a syntax error, as the JavaScript engine interprets them with a special meaning that cannot be overridden. For instance, using var or return as a variable name would lead to an error because these words are reserved for declaring variables and controlling the function's execution flow.

Re-Assigning

Variables declared with var and let can be re-assigned, i.e. in the lifecycle of a program, these values could change.

var number1 = 1;
var number2 = 2;
var result = 0;
result = number1 + number2;

In the above example, we see that the initial value of result was zero, as the code continued executing, we added the two numbers and re-assigned the value to the variable result.

Constants

Constants are variables that have a fixed value throughout the lifecycle of the execution. These are unchanging values. A constant is declared with a const keyword.

const pi = 3.1415;

The value of pi cannot and should not change since it is a constant.

Another example could be

const birthday = "01-01-1996";

Since the birthday of a person cannot change ( can it? ), it should be declared as a constant.

Trying to re-assign a value to a constant will throw an error

const pi = 3.1415;
pi = 100; // Throws an error

The above code throws an error TypeError: Assignment to constant variable.

Constants are very useful in the code, for example, say we need to perform some operations on some numbers

const salary = 199895;
let yearlySalary  =  salary * 12;
let increamentPercentage = 12%;
let nextSalary =  yearlySalary * 1.12;

Here, since the salary value is a number that is hard to remember, compared to the word salary, using a constant can be extremely helpful. This is just one such use case, we could use this for color codes ( Hex codes ), or anything that we know to be a constant and should not - does not change in the code flow.

Uppercase constants are declared for things that are permanent, such as strings in the project. Here "STRINGS" is a constant in upper case, but it could very well have been like Strings too, but It is a common practice to put strings inside a file, such as

const STRINGS = {
  title : "Project title",
  actionButton : "Click here"
};

Here the variable STRINGS is a constant that is used across the project. This is not a syntax but a common practice used in projects. There are many other examples of declaring upper-case constants too.

Variable naming conventions

When naming variables in JavaScript, it's important to follow certain conventions to ensure code readability and maintainability. One fundamental rule is to use meaningful names that clearly describe the purpose of the variable. For instance, instead of naming a variable x, use a descriptive name like totalPrice or userAge.

This practice helps other developers (and future you) understand what the variable represents without having to decipher its meaning from the code's context. Additionally, variable names should be written in camelCase, where the first word is lowercase and each subsequent word starts with an uppercase letter, such as userAge or maxValue. etc. This convention is widely adopted in JavaScript and improves consistency across codebases.

More about the naming conventions is discussed in the article "Javascript Coding Structure".

Using use strict vs not using use strict

In JavaScript, the "use strict" directive is a way to opt into a stricter set of rules for writing code, which can help catch common errors and enforce better coding practices. When you include "use strict"; at the beginning of a JavaScript file or function, it activates strict mode. Strict mode changes the behavior of the JavaScript engine in several ways, such as preventing the use of undeclared variables, which can help avoid potential issues caused by typos or variable scope problems.

// Strict mode example

"use strict";

// Implicitly declaring a variable
function strictExample() {
    undeclaredVar = "This will cause an error";
    console.log(undeclaredVar);
}

When not in the strict mode, variables can be declared even without using the let keyword such as

num =10

would be a valid declaration. Although, most of the projects use the strict mode and I would recommend against using non-strict mode.

Great, I hope you now have a clear understanding about variables in Javascript, ready for the next topic?