DEV Community

Vector Ojay
Vector Ojay

Posted on

let j = "JavaScript"(A newbie's guide on Declaring Variables in JavaScript)

let j = 'JavaScript'

You've just embarked on your programming journey, and chances are, you've recently delved into learning JavaScript (an excellent choice, by the way!👍).
Perhaps even before you decided to become a developer, you've come across syntax like the ones in the code below:

let j = "JavaScript";
const me = "Developer".
Enter fullscreen mode Exit fullscreen mode

And you might have wondered what all this jargon really means. Don't worry, I've been in your shoes too! (If that's any consolation).

The lines of code above are primary examples of how variables are declared in JavaScript.

One of the initial and fundamental lessons you'll encounter as you dive into JavaScript is how to declare variables. Comprehending the hows and whys of variable declaration is pivotal to your progress, as a newbie developer.

In this article, we're going to cover everything you need to know about declaring variables in JavaScript: from the basics of what a variable is, to why they hold significance in JavaScript, how values are stored in them, the various data types, different ways in which variables are named, and much more.

By the end of this article, you should have a solid grasp of:

  • Understanding what variables are and how they affect your code.
  • Best practices for naming variables to enhance code readability.
  • How to effectively choose between different variable declaration keywords (var, let, const) based on specific use cases.
  • The diverse data types that JavaScript offers.

And more...

Table of Contents

Introduction

Values and Data Types

  • Introduction to Values as Data or Information
  • Various Data Types in JavaScript
    • Primitive Types
    • Reference Types

Variables

  • Definition and Purpose of Variables
  • Variable Declaration in JavaScript

Variable Keywords

  • let: The Preferred Keyword for Variable Declaration
  • const: Declaring Constants for Unchanging Values

Variable Assignment and Reassignment

Variable Naming Conventions

  • Importance of Meaningful Names
  • Common Naming Conventions
    • Camel Case
    • Pascal Case
    • Snake Case
  • Guidelines for Naming Variables

Conclusion
Summary and Key Takeaways

Values and Data Types:

Introduction to Values as Data or Information:

In JavaScript, a value is simply a piece of data or information that can be used by a program.
 
These values can be of various data types. For instance, they can manifest as a string (which is essentially text, enclosed in single or double quotes, as demonstrated below), a Number (such as 3, 459, or 3000), Booleans (representing true or false), and more.

"Programmer" //this value represents a string.
38 //this value represents a number.
true // this value represents a Boolean.
null // this value represents null.
undefined // this value represents undefined.
Enter fullscreen mode Exit fullscreen mode

Various Data Types in JavaScript
There are two categories of Data types in JavaScript:

  • Primitive Types
  • Reference Types

Primitive Types

  • Numbers: Representing both integers and floating-point numbers.
  • Strings: Representing pieces of text.
  • Booleans: Representing true or false.
  • Undefined: Signifying a variable that has been declared but hasn't been assigned a value.
  • Null: Denoting the absence of a value.
  • Symbol: Representing a unique and unchangeable value.
  • BigInt: Catering to large integers.

Both Symbol and BigInt were the latest data type introductions to ES6.

Reference Types

  • Object, which is a collection of key-value pairs.
  • Array, which is a collection of values.
  • Function, which is a block of reusable code.

Values hold immense importance in JavaScript, as we use them to perform nearly every operation in a program, be it calculations, outputting messages, data validation, updating dates and times, decision-making, and much more.

In essence, it's safe to say that without values, a JavaScript program is practically useless.

Variables:

Definition and Purpose of Variables

A variable is essentially a container used to store data or values, like those mentioned above (strings, numbers, etc.).

Variables make it easier to work with or manipulate values in our code.
To create a variable (or declare a variable, as is normally said in the world of programming) in JavaScript, we use the let keyword or the const keyword.

Variable Declaration in JavaScript

In the code below, we are using the let keyword to create a variable called firstName

let firstName;
Enter fullscreen mode Exit fullscreen mode

Now when you type the let or const keyword, you are basically telling JavaScript to create an identifier or memory space, with a certain label name that you give it.

In the case of the code above, the label name given to that memory space is called firstName.

We can now go ahead and store some information in that memory space we created.
To store a value inside of a variable, we use the = sign, also known as the assignment operator in JavaScript, just as in the code below:

let firstName = "Vector";
Enter fullscreen mode Exit fullscreen mode

Here, the value "Vector", has been successfully stored to the variable firstName.

We can then use the variable name to do operations in our code, instead of the value itself.

For example, instead of logging the hardcoded value to the console:

console.log("Vector"); //shows Vector in the console
Enter fullscreen mode Exit fullscreen mode

We can now use the variable firstName in place of "Vector".

console.log(firstName); // also shows Vector in the console
Enter fullscreen mode Exit fullscreen mode

Let's try to log the value 38, which is a number, to the console:

console.log(38);
Enter fullscreen mode Exit fullscreen mode

Here, we're simply logging the hardcoded value 38 without storing it in a variable.

However, we can log the same value to the console in a smarter way by first storing it in a variable, and then using that variable name to log the value:
See the code below:

let num = 38;
console.log(num);
Enter fullscreen mode Exit fullscreen mode

In the code, we can see that the value 38 was first stored into a variable called num, and then the name of that variable was used in logging it to the console, instead of the hardcoded value itself.

With this simple lines of code, we can begin to imagine how crucial variables could be when writing our code.

Let's imagine a scenario where we have been instructed to log to the console the multiplication table for 2, in our code:

console.log(2 * 1); //2
console.log(2 * 2); //4
console.log(2 * 3); //6
console.log(2 * 4); //8
console.log(2 * 5); //10
console.log(2 * 6); //12
console.log(2 * 7); //14
console.log(2 * 8); //16
console.log(2 * 9); //18
console.log(2 * 10); //20
Enter fullscreen mode Exit fullscreen mode

Now, let's also assume that there's now a small issue and we have been given a new instruction to switch from the multiplication table of 2 to that of 3.

This would imply that we would have to go through our code and replace every instance of the number 2 with the number 3, as seen in the code below:

console.log(3 * 1); //3
console.log(3 * 2); //6
console.log(3 * 3); //9
console.log(3 * 4); //12
console.log(3 * 5); //15
console.log(3 * 6); //18
console.log(3 * 7); //21
console.log(3 * 8); //24
console.log(3 * 9); //27
console.log(3 * 10); //30
Enter fullscreen mode Exit fullscreen mode

This would obviously require a lot of work for such a small issue, don't you think?

And this is precisely why variables are crucial.

Let's repeat the same process, but this time, we'll first store the number 2 inside a variable called num, like this:

let num = 2;

Then, we'll use the variable name, which is num, to log our multiplication table to the console, just like we did earlier:

console.log(num * 1); //2
console.log(num * 2); //4
console.log(num * 3); //6
console.log(num * 4); //8
console.log(num * 5); //10
console.log(num * 6); //12
console.log(num * 7); //14
console.log(num * 8); //16
console.log(num * 9); //18
console.log(num * 10); //20
Enter fullscreen mode Exit fullscreen mode

The result will still be the same as before, since num still holds the value of 2.

So now, if we are asked to change our multiplication table from that of 2, to that of 3, we can now simply do that by changing the value stored in the variable num, like this:

let num = 3;

console.log(num * 1); //3
console.log(num * 2); //6
console.log(num * 3); //9
console.log(num * 4); //12
console.log(num * 5); //15
console.log(num * 6); //18
console.log(num * 7); //21
console.log(num * 8); //24
console.log(num * 9); //27
console.log(num * 10); //30
Enter fullscreen mode Exit fullscreen mode

And there you have it!

Thanks to this approach, we avoid the painstaking task of manually replacing every instance of the value 2 in our code, and still achieved the same result.

Just imagine, if we had calculations like 2 * 1, spanning all the way to 1000.
 
Having to substitute 2 a thousand times? That sounds like an absolute nightmare, doesn't it? 😳

Variable Keywords

So now that we've seen a basic example of how things work when we use variables, let's talk about the different keywords we can use to declare variables.

There are three of them:

The var, let and const keywords.

let: The Preferred Keyword for Variable Declaration

In the codes we wrote above, we mostly used the let keyword to declare our variables.

The let keyword is generally used in declaring variables in JavaScript, and is a modern alternative to the older var keyword.

It's important to note that the var keyword is an older, outdated way of declaring a variable, and should preferably not be used when writing your code.

We use the let keyword when we want to declare variables that might change or be reassigned later.

Let's say your nick name is Rossy, and we want to store this information using a variable, as in the code below.

let nickName = "Rossy";
Enter fullscreen mode Exit fullscreen mode

Now we have your nick name, which is "Rossy" stored in a variable named nickName. Right?

Let's say that you later want to change your nick name from Rossy to Larry, and we have to change that information in the code above.

We can simply do that by reassigning the variable nickName to its new value, which is "Larry".

Here's how we can do that:

nickName = "Larry";
Enter fullscreen mode Exit fullscreen mode

Now remember that we learnt earlier that variables are like containers which we use to store data.

So in the code above, we are simply telling JavaScript to take out the previous value stored inside that container which we named nickname and replace it with the new value "Larry".

Note that while reassigning the value, we did not use the let keyword again. We simply set the already declared variable nickName to it's new value, which is "Larry".

const: Declaring Constants for Unchanging Values

On the other hand, we use the const keyword to declare variables that are constant and would never be reassigned. In other words, when you declare a variable with the const keyword and store a value inside it, that value can never be changed.

const e = 2.71828;
Enter fullscreen mode Exit fullscreen mode

Trying to reassign this variable e to another value like we did with the let keyword will return an error in our console.

e = 3.14; // returns error: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

While declaring variables, we need to bear the following in mind:

  • It's preferable not to use the var keyword, especially as a newbie. It can lead to unexpected behavior in your code, especially in modern JavaScript development.

  • Use the let keyword for variables that may need to be reassigned.

  • Use the const keyword for values that would never be reassigned.

It enhances code readability and prevents accidental reassignment.

Variable Assignment and Reassignment

We can easily reassign variables that have already been assigned a value.
Let's look at the example code below:

let job = "Programmer";
let occupation;
occupation = job;
Enter fullscreen mode Exit fullscreen mode

Here, we created a variable named job and assigned it the value "Programmer".

Then in the second line, we created another variable named occupation, but we didn't assign any value to it.

Declaring a variable like that without storing anything in it is like reserving a storage for something later in the future.

In the third line, we took the content from the job variable (which is the word "Programmer") and put it into the occupation variable.

So now, both job and occupation boxes contain the same value, which is the word "Programmer".

Think of it like copying a word from one box to another. Now, both boxes (job and occupation) have the same value inside them.

Variable Naming Conventions

There are a number of variable naming conventions in JavaScript. But the most common naming conventions are Camel Case, Pascal Case, and Snake Case

  • Camel Case: This is the most widely used convention in JavaScript. In this case, the first word is written in lower case, and every other word after it is capitalized (i.e., starts with a Capital letter, and the rest, small letters), just like in the code examples below:
let myVariable;
let totalAmount;
const displayTotalBalance;
Enter fullscreen mode Exit fullscreen mode
  • Pascal Case (Upper Camel Case): This is similar to camel case, but in this case, each word starts with a capital letter, just like in the code example below:
let MyFirstName;
const SecondClass;
let GetUserDetails;
Enter fullscreen mode Exit fullscreen mode
  • Snake Case: In this case, words are normally separated by underscores (_). This convention is not as common in JavaScript as camel case, but you would come across it from time to time. Let's see some examples in the code below:
let my_first_name;
const second_class;
Enter fullscreen mode Exit fullscreen mode

Guidelines for Naming Variables

Being able to name variables efficiently is one of the skills that makes a developer stand out, in programming.

When naming variables in JavaScript, below are some of the guidelines to consider:

  • Meaningful Names: Choose names that accurately describe the purpose or content of the variable or function. Avoid generic names like temp or x.

  • Avoid Reserved Words: Don't attempt to use JavaScript's reserved words or keywords as variable names. For example, don't name a variable var, function, or true.

For example:

let function;
Enter fullscreen mode Exit fullscreen mode

This is bad practice!

  • Consistency: It's important to always maintain consistent naming conventions throughout your codebase. This makes it easier for developers (including your future self) to read and understand the code.

  • Use Descriptive Names: Choose names that clearly convey the purpose of the variable or function. This helps improve the self-documenting nature of your code.

  • Variable names should only contain letters, digits, or the dollar symbol $ and underscore _.

  • The first character in your variable name should never be a digit.

Conclusion

Summary and key Takeaways

Variables in JavaScript are like containers that store different types of information, like numbers or text.

Using variables allows for more efficient code writing and makes it easier to make changes or updates.

For example, when using variables, switching from one value to another is as simple as reassigning the variable, rather than manually replacing each instance of the value in the code.

In conclusion, understanding how to declare and use variables in JavaScript is a fundamental skill for any programmer.

It enables efficient data management and enhances code flexibility and readability.

By following naming conventions and choosing meaningful names, developers can create more maintainable and understandable code.

I hope you found this article helpful, as a newbie, or an experienced programmer. If you did, feel free to leave a comment in the comment section, or add a suggestion if you think I omitted something.

Happy Coding!

Top comments (0)