JavaScript Basics : The language of the web
This article covers all the basics things about JavaScript variables and datatypes that you may need to know !
Table of contents
Introduction
Do you ever feel that your webpages are looking boring without interactivity ? If yes , then you may also thinks about that how can we make our webpages interactive. Well, JavaScript do this job of adding interactivity in the webpage. It also helps in making the webpage dynamic.
JavaScript is basically a high level language used to create interactive and dynamic webpages. It is one of the core tech of the web development along with HTML and CSS.
So, let’s deep dive into the basics of the JavaScript that may help you to get started and put strong command on the javascript . So, let’s began our journey of JavaScript basics.
Variables in JavaScript
What is Variable ?
A variable in JavaScript is like a container that is used to store data values. The data values can of different types such as Strings, numbers, boolean etc. Variables are essential for creating an interactive webpage.
Let’s consider a real life example as your home’s kitchen. In your kitchen different ingredients like sugar, chaipatti etc. are in different containers. So, here ingredients are the data types and the container holding them are the variables.
There are mainly two main ways by which we can declare variables in JavaScript which are following as :-
1. Explicit Declaration
By the word explicit we means, clearly explaining everything or not hiding anything. So, here explicit declaration means , declaring the variable manually in JavaScript. Explicit variables are declared using the var
, let
and const
keywords. Let’s understand these keywords one by one.
var
The
var
keyword is used to declare variable in JavaScript. The variable declared using thevar
keyword have function scope, meaning they are accessible within the function they are declared in, or globally if declared outside of any function. We can also use variables before declaring it usingvar
. This is because var supports - Hoisting.var Hoisting :- var hoisting means, wherever we declare the variables using the var keyword are they are processed at top before the script execute. This process is called - Hoisting.
The var keyword was only keyword used to declare variables before let and const. But var used rarely in these days.
function display(){
var a = "Sanket singh"; // decalered and intilized variable using the var keyword
console.log(a);
}
display();
// Output
// Sanket singh
let
The
let
keyword is the most used keyword to declare variables in modern JavaScript. The let keyword has block scope (means, the variable declared inside the block cannot be accessed outside the block ) and the variables cannot be redeclared once declared using the let keyword.
function add(){
let a = 10; // Declaring variables a nd b suing let keyword
let b = 10;
console.log("The sum of a and b is:", a + b);
}
add();
// Output :- The sum of a and b is: 20
const
The const keyword is used to declare the constant variables . It is also a block scope variable. By declaring the variable using the const keyword we cannot redeclare the variable. While declaring the variable we have to initialize the value to it and once initialize we cannot re-initialize it.
function display(){
const pi = 3.147; // declaring variable pi using const keyword
console.log("The value of pi is:", pi);
pi = 3.2; // TypeError: Assignment to constant variable.
}
display();
// If you wanted ouput comment the re-intilization of pi = 3.2;
Difference between
var
,let
andconst
Feature | var | let | const |
Scope | Function-scoped | Block-scoped | Block-scoped |
Re-declaration | Allowed within the same scope | Not allowed within the same scope | Not allowed within the same scope |
Re-assignment | Allowed | Allowed | Not allowed (constant value) |
Hoisting | Hoisted (initialized as undefined ) | Hoisted (but not initialized) | Hoisted (but not initialized) |
Mutable? | Yes | Yes | No (value cannot be changed) |
Usage Recommendation | Avoid using (due to global scope issues) | Use for variables that change values | Use for constants (unchanging values) |
2. Implicit / Automatic Declaration
In this type of declaration we assign values to the variables directly without any keyword. variable declaration is done by the JavaScript engine .
Implicit declaration does not support any block scoping which means the variable declared inside the block or function can also be accessible outside the block or function. JavaScript engine will make it as a global variable.
function display(){
Gods = "Hitesh sir and piyush sir"; // Declaring and intializing an implicit variable
console.log("Gods:",Gods);
}
display();
console.log("Gods-1:",Gods); // Can also be accessible outside the function
// Output
// Gods: Hitesh sir and piyush sir
// Gods-1: Hitesh sir and piyush sir
This technique of declaring variables is not recommended as it leads to unexpected behaviours and conflicts in large datasets.
Datatypes in JavaScript
What are datatypes ?
Let’s revisit the example of ingredients in your kitchen. Here we saw that different types of containers holding the different data values. How, we found that data values are different ? Well, this is were datatypes came into picture.
Datatypes defines the kind of data a variable is holding or can hold . It determines how data is stored, accessed and manipulated in the memory.
JavaScript has two main categories of datatypes which are :-
Primitive Datatypes .
Non-primitive Datatypes.
Let’ s understand these deeply :-
Primitive Datatypes
Primitive datatypes are the immutable ( once a primitive value is created it cannot be changed, although the variable that holds it may be reassigned another value ) and store by value in memory. There are different types of primitive datatypes following as :-
1. String
String represent the textual data ( characters enclosed in quotes ). Each element in a string occupies a position in string known as index staring from first element at index 0, second at index 1 and so on.
There is not datatype to define character in JavaScript. Characters also defines in double quotes.
let name = "Akash kadlag"; // Declaring a string variable
console.log(name);
2. Number
Number represents the both integer values and floating - point values but it store as floating - point numbers in memory.
let integer = 7; // dcelaring an integer
let float = 7.6; // Declaring a floating - point number
console.log(integer);
console.log(float);
3. Boolean
Boolean datatypes represents values as true
or false
.
let name = true; // Decalring an boolean varaible
console.log(name);
4. Null
Null datatype is used when we have to intentionally leave the value of variable empty. It is treated as false
for boolean operations. Null simply means — “ baad me dekhe ge “.
let info = null;
console.log(info);
5. undefined
The datatype of a variable is undefined when we only declare a value not initialize it with nay value. In simple terms, undefined means JavaScript does not know which type of value if going to come in variable.
let name;
cosnole.log(name); // Output :- undefined
6. BigInt
JavaScript store numbers in 64-bit floating - point format. If there is large number than that then, we use BigInt to store number in JavaScript.
let bigNum = BigInt(1234567890123456789n);
7. Symbol
A symbol is unique and immutable primitive datatypes and can be used to store the key of an object property. The purpose of symbols is to create unique property keys that are guaranteed not to clash with keys from other code.
const key = Symbol("Pasword123")
console.log(key);
// Output :- Symbol(Pasword123)
How to check the datatype ? (typeof
operator)
We can check the datatype of the variable using the typeof operator.
let num = 40;
let name = "Hello world";
let bool = true;
let pass = Symbol(1223);
let a = null;
let b;
console.log(typeof num); // number
console.log(typeof name); // string
console.log(typeof bool); // boolean
console.log(typeof pass); // symbol
console.log(typeof a); // object
console.log(typeof b); // undefined
Exception :- On doing the typeof of the null we get object as output. This is the bug in JavaScript which is never been corrected by the organization.
Non - Primitive Datatypes
Non - primitive datatypes are the datatypes that are used to store collection of data. These are mutable and store values by reference in memory.
Thera are mainly two types of non - primitive datatypes in the JavaScript which are :
1. Array
An array is a datatype that is used to store ordered collection of data. Arrays in JavaScript are bit different as other programming languages like ( C++, Java ).
In these languages arrays are type-specific but in JavaScript we can store different data types in single array. The JavaScript arrays are 0-indexed based which means first element at 0-index, second at 1-indxe and so on. Using length
property we can find the length of the array.
let nums = [10, 20, 30, 40]
console.log(nums); // Output :- [10, 20, 30, 40]
console.log(nums[2]); // Accessing the element of array by indexing (30)
console.log(nums.length) // Printing the length of the array (length = 4)
nums.push(45); // Adding item to the array (item insertde at last using push)
console.log(nums); // Output :- [10, 20, 30, 40, 45]
nums.pop(); // Used to remove the element from he array from last
console.log(nums); // Output :- [10, 20, 30, 40]
2. Object
An object in JavaScript is a datatype that is used to stare data in key-value pairs where key is unique identifier for each value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.
let person = {
name: "Developer singh",
age: 45,
employed: true,
company: "Chai code"
};
console.log(person); // Priting the whole object
console.log(person["employed"]); // priting the value using particular key
// Output
// { name: 'Developer singh', age: 45, employed: true, company: 'Chai code' }
// true
Type Coercion
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
const value1 = "5";
const value2 = 9;
let sum = value1 + value2;
console.log(sum);
In the above example, JavaScript will implicitly convert either value1 as number or value2 as string to perform operation. We can not control type coercion. If we want to have control over what datatype it is converting to we can use Type Conversion.
Conclusion
So, in this article we learnt about the JavaScript fundamentals about the variables and datatypes in the JavaScript . I hope this article added the value in your knowledge. If yes ! then, please like my article and if you have any suggestion let me know in the comments. That’s if for today ! bye all .