What are variables and datatypes in javascript - javascript basics

ยท

9 min read

In coding we dont just print sentences. We work with values and the values are stored in variables. Think of it as a container in the main memory of your computer, it has some space and it can stores values for you in that space, so that you can work with them, like add two values to get an answer. These values can be of various types like Numbers, Strings(a sentence or a letter), symbols(emoji, math symbols, etc) and many more, these types of values or data are called datatypes. There are about 7 dataypes(type of data stored in a variable) that you need to know.

They are as follows: Numbers, Null, Boolean, BigInt, Symbols, String, undefined and Objects. Some of them are easy to intersept by their name but some might be strangers to you. Don't worry I'm here. In order to keep them in mind I have a trick for you. Say out loud "NN-BB-SS-U-O", "NN-BB-SS-U-O", "NN-BB-SS-U-O".

Now you might be wondering what was that. This a code word that I have developed to remember the datatypes in js. Let me break it down for you. "NN-BB-SS-U-O" lets start from the first letter and move rightwards, the first N is Number then, second N is Null, first B is boolean and second B is BigInt, followed by Symbols and Strings, and then U is Undefined, O is Object. That's it, Isn't it easy now?

How to use variables

Now we know what datatypes are but how to use variables in js to store the value? So for that we use the let keyword. Keywords in javascript are simply reserved words, they are defined by the developers who manage code( the guys at ECMA). So to use a variable first we define it, using the let keyword, followed by the name of the variable, you can name your variable anything you want, just keep two things in mind it needs to be a single word and you can use two words in the name just don't include space in between or any special characters like -, use _ instead. for example see the code below.

let variable;
//you can also do this
let variableName; // pascal case is recommended
let variable_Name;
// let variable-Name ; not possible

One more thing variables cannot be redeclared,like you cannot do let <variable name> two times, it will result to a error. After declaration(creating a variable) we can store a value of any datatypes in that variable. Just know that once we assign (storing a value to a variable) a value to that variable, the variable type becomes the same as the datatype it holds. To assign a value we do the following.

variable = 300; //I stored a number

To check the type of the variable we can use the typeof command, what this does is it finds out the datatype of the variable and gives you the output. So the below code will give you the output as number in the terminal.

console.log(typeof variable); // this will output number
// console.log(typeof(variable)); you can also do it like this

At any time in future, you can change the value of the variable by again using the equals sign(=), but sometimes some value do not change, like the name of a person. So how can we write a code when we assign the name of a person or a value in general to a variable and stop anything from changing it again. We will then use another type of keyword in js named const keyword to do the same.

const name = "Alex";

Now if you try to assign another value to it after that, it will throw and error, it will say "TypeError: Assignment to constant variable." . So this far we have learnt what are variables and datatypes in js and how we can use let and const keyword to declare or create variables, how can we assign or store value to a variable using "=" . what is the difference between a let and a const variable. Now I would like to introduce you to our third friend the var keyword, this perfroms very similarly like let . But you will rarely be using it.

More about var keyword

Remember I told you that javascript is a weakly typed langauge, and its very forgiving for errors. Lot of things which might throw errors or are simply not possible in other programming languages are possible in javascript. So you know we cannot redeclare a variable using let keyword two times, but it was developed to counter this mistake developers used to make while using var. With var you can redeclare a variable twice in the codebase and this used to drive people crazy when some junior dev used to make this mistake. So var can also be used to declare a variable in js but just know that let is used instead of var and in some other blog we'll dive deep into var, let and const.

More about each datatypes

So I hope I was able to familiarize you with the three ways to decalre a variable. Lets see more about each datatypes one by one.

Numbers: When it comes to everything numerical in the wide world of JavaScript, numbers are your go-to entities. Numbers are your friend when it comes to counting apples, finding the distance to the moon, or slicing a pizza into equal portions. They can easily fit into the mathematical symphony of your code as decimals (floating-point numbers) or integers (whole numbers).

let quantity = 42;      // Integer
let temperature = 98.6; // Floating-point number

Null: Let's now discuss the fascinating idea of null. A variable effectively becomes an empty vessel when it is assigned the value null. It denotes the deliberate removal of all object value. Consider it as a blank canvas ready for a data artist's touch.

let emptyContainer = null;

Boolean: Ah, the world of true or false, a binary system! In JavaScript, booleans are the defenders of logic. They capture the idea of choices, enabling your code to take many routes in response to various circumstances. A boolean variable is similar to a traffic signal that guides the movement of your programme.

let isRaining = true;
let hasSunshine = false;

BigInts : BigInts are the heavy lifters of numeric representation, prepared to take on enormous computations with ease. When regular numbers just will not cut it, BigInts step in. This data type supports integers of arbitrary length, handling computations that might surpass the limits of standard numbers.

let bigNumber = 9007199254740991n;

Symbols: Consider symbols as your code's undercover secret agents, working behind the scenes to preserve order and uniqueness. Symbols are frequently used to create unambiguous property keys in objects, preventing unintentional clashes with other identifiers. Symbols add a touch of uniqueness to the JavaScript stage.

const secretKey = Symbol('hidden');

String: They are the building blocks of communication between your program and the user, strings are the wordsmiths of JavaScript. Embrace them to manipulate, concatenate, or dissect textual information within your code. Whether it is a single character or an epic poem, strings wrap it all.

let greeting = 'Hello, World!';
let singleCharacter = 'A';

Undefined: Visualize a variable as an empty space that has to be filled. A variable bears the label "undefined" when it is declared but not given a value. It is similar to uncharted area that has the potential to contain data but has not been initialized yet.

let notDefinedYet;
console.log(notDefinedYet); // Outputs: undefined

Objects: Objects are the Swiss Army knives of JavaScript data types; they can store a wide range of key-value pairs and represent complex entities in your code. Objects can be used to define a person with a name and age or to create complex data structures. Essentially, objects are the builders of organized information.

let person = {
  name: 'John Doe',
  age: 30,
  occupation: 'Developer'
};

Now that you have a better grasp of each data type, you can use variables in JavaScript with more strength. Did you know that you can also find the type of a given variable using the typeof opeartor.

//suppose you have a variable
let a=10;
console.log(typeof a);

the output will be somthing like this.

number

Lets see some more example and try to find out the datatypes of some more different types of variables.

// Define variables with different data types
let str = "Hello, World!";
let num = 42;
let bool = true;
let obj = { key: "value" };
let arr = [1, 2, 3];
let func = function () { console.log("Function executed"); };
let nul = null;
let und = undefined;

// Use typeof to determine the data type
console.log(`Type of str: ${typeof str}`);
console.log(`Type of num: ${typeof num}`);
console.log(`Type of bool: ${typeof bool}`);
console.log(`Type of obj: ${typeof obj}`);
console.log(`Type of arr: ${typeof arr}`);
console.log(`Type of func: ${typeof func}`);
console.log(`Type of nul: ${typeof nul}`);
console.log(`Type of und: ${typeof und}`);

the output of the above code will be something like this, do try on your system.

Type of str: string
Type of num: number
Type of bool: boolean
Type of obj: object
Type of arr: object
Type of func: function
Type of nul: object
Type of und: undefined

Well look at the code carefully, I have declared variables of almost all the datatypes in js and then I have used the typeof operator to get the dataype and print them using console.log. I haven't told you about functions yet, but yes functions are also a datatype in javascript, just know that for now. We will look into functions in some future blog.

String interpolation:

I would also like to adress one more thing that I have done in the code base. Take a look at the console.log command can you see I have used some $ sign and {} with in backticks(``). Yes in js you can print string in three ways lets say you have a string hello world now you can use either double quotes(") or single quotes('), but let say you want to use a javascript expression(for example any variable's value) in between the string, but js considers anything between "" or '' as plain text so for that you can use backticks. Then you can use ${} also known as template literals with the the variable name or js expression(${3%2}) within and js will not treat that as plain text. for example you have the following code:

let name="Alex";
console.log(`Hello world ${name}`);

In the above code can you see how I used it. If type the same text in "" or '' it will give the output as Hello world ${name} because it treats it as plain text but the output will be Hello world Alex where Alex is the value of the variale "name". This is a really useful feature and you will yourself using it in many cases.

Well all of these might be little more than enough for you, but trust me it was necesary. Do take your time and you can ask for any help from me. I hope you had a great time learning and I will meet you soon in some other blog or on youtube. Till then happy coding and happy learning!

ย