What are variables and datatypes in javascript - javascript basics
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, etc. 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 is a code word that I have developed to remember the datatypes in JavaScript. 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 (using let and const)
Now we know what are datatypes and variables in JavaScript now how can we create and use varaibles? So for that we use the let keyword. Keywords in javascript are simply reserved words that have some specific purpose, 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 in mind don't start your variable with special character or number, dont use space in between words( type more than one words like this firstSecond). for example see the code below.
let variable;
//you can also do this
let variableName; // pascal case is recommended
// let variable-Name ; not possible
One more thing variables cannot be redeclared,like you cannot do let <variable name>
two times in a common scope, it will result to an error. After declaration(creating a variable) we can store a value of any datatypes in that variable(JavaScript is dynamically typed language). 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 which stops us from modifying or changing the value. We will use another type of keyword in JavaScript named const keyword to declare a variable, whose value will be constant.
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 JavaScript 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.
Little bit 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 JavaScript 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 any data.
let emptyContainer = null;
Boolean: Boolean datatype is the most simplest one. They store true or false.
let isRaining = true;
let hasSunshine = false;
BigInts : 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.
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: 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.
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. 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 JavaScript 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 address one more thing I have done in the code. Take a look at the console.log command; you can see I have used some $ signs and {} within backticks (``). Yes, in JavaScript, you can print strings in three ways. Let's say you have a string hello world; you can use either double quotes (") or single quotes ('). But if you want to use a JavaScript expression (for example, any variable's value or any code computation like a + b) within the string, JavaScript 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 variable name or JavaScript expression (${3 % 2}
) within, and JavaScript will not treat that as plain text. Instead, it will calculate it and put the value in its place. 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 be using it in many places.
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!
Subscribe to my newsletter
Read articles from Priyojit Singha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Priyojit Singha
Priyojit Singha
Figuring out a lot of things ๐