✍ JavaScript concepts that every developer should know 🦾
Table of Contents
1). Primitive Types
2). Value types and reference types
3). setTimeout
4). Optional Chaining (?.)
5). Global, local, block and lexical scope
6). Promise/callback/async/await
Primitive Types
All Programming languages have built-in data structures.
Data type: Data type is classification which type of value will assign to variable and tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support various types of data, including integer, character or string, and Boolean.
Primitive Data Type:
In JavaScript, data that is not an object or does not have a method or property is a primitive data type. There are 7 types of primitive data type:
Value Types and Reference Types
1. Value Types
JavaScript has 5 data types that are passed by value: string
, number
, number
, undefined
and null
and we also called them primitive types.
const x = 10;
const y = 'abc';const a = x;
const b = y;console.log(x, y, a, b); // -> 10, 'abc', 10, 'abc'
In the above example we have two variables x
and y
and we assign x
and y
to a
and b
, so we you update a
and b
value it will never impact on a
and b
.
2. Reference Types
JavaScript has 3 data types that are passed by reference: Array
, Function
, and Object
. These are all technically Objects, so we’ll refer to them collectively as Objects.
const reference = [1];
const refCopy = reference;reference.push(2);
console.log(reference, refCopy); // -> [1, 2], [1, 2]
In the above example we have two variables reference
and refCopy
and we pushing one element in reference
and it automatically update on refCopy
as well.
For more expiation you can read:
setTimeout
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. n other words, you cannot use setTimeout()
to create a "pause" before the next function in the function stack fires.
setTimeout()
method sets a timer which executes a function or specified piece of code once the timer expires.
this function basically take three arguments functionRef
, delay
and param
and param
is optional
setTimeout(() => {
console.log("Delayed for 1 second.");
}, "1000")
Optional Chaining (?.)
Optional chaining is introduced in ES2020. It is very helpful feature in JavaScript, with help of optional chaining
you can reduce your conditional statements for example you are getting one object and you use this object so how will optional chaining
help
const userData ={
firstName: "john",
lastName: "Don",
age: 23,
}// before optional chaining
// if you need to use firstName and lastNameuserData && userData.firstName
userData && userData.lastName// after optional chaininguserData?.firstName
userData?.lastName
Global, local, block and lexical scope
Before understanding global
, local
, block
and lexical
scope, you should understand what is scope? scope: in JavaScript scope refers the current context of code which determines the accessibility of variables.
When you start writing a code you are in global
scope if you define any variable at the top or outside of function then the variable will be in global
scope or you can say variable take a global
scope.
If you assign variable inside of any function then variable is in local
scope for the particular function, that means variable scope is a local
scope.
If you assign variable inside of any conditional statement then it will be in block
scope or you can say it take a block
scope.
Lexical scope: lexical
scope is the ability of an inner function to access the scope of an outer function.
This is the example of global, local and block scope
// global scope
var name = “John”; // var is by default global scope;const scopeFunction = () => {
let name = “John_1”; // local scope
if(true) {
const name = “C_John”; // block scope
console.log(name) // “C_John”
} const scopeFunction_1 = () => {
let name = “John_2”; // local scope
console.log(name) // “John_2”
}
console.log(name) // “John_1”
}console.log(name) // “John”
This is the example of lexical scope
var dog = “Lewis”;const outerFunc = () => {
// SCOPE 1
let cat = “Jerry”;
const scopeFunction = () => {
// SCOPE 2
console.log(cat) // “Jerry”
console.log(dog) // “Lewis”
}
}
In scopeFunction
you see we are calling cat
and dog
but doesn’t defined inside of scopeFunction
so this is the lexical
scope flexibility in JavaScript so we can use parent function or scope variables in child function.
Promise/callback/async/await
In JavaScript, a promise is a good way to handle asynchronous operations. It used to find out if the asynchronous operation is successfully completed or not.
A promise may have one of three states.
- Pending
- Fulfilled
- Rejected
When promise called it in pending state that means process is not completed. If operation is completed it will be in fulfilled state and if failed it will be in rejected state.
For example we you request to server using promise it will be in pending state, when the data arrives successfully it will be in fulfilled state and if an error occurs it will be in rejected state.
let testPromise = new Promise(function(resolve, reject) {
let x = 0;
return x===0? resolve(“Success”): reject(“Error”)
});testPromise.then(
result => alert(result);
error => alert(error); // handle particular then error
);//we can use multiple then here as per requirement
testPromise
.then(result => alert(result))
.catch(error => alert(error));
Callback
In JavaScript, you can also pass a function as an argument to a function. This function that is passed as an argument inside of another function is called a callback function. For example: you have user firstname and lastname and you need to get full data of user using full name
let getUserFullName = (firstName, lastName, callback) => {
let fullName = `${firstName} ${lastName}`);
callback(fullName);
}getUserFullName(“Jhon”, “Don”, getUserDetailByName);getUserDetailByName = (userName) =>{
// Write your code here
}
Async
We use the async
keyword with a function to represent that the function is an asynchronous function. The async function always returns a promise.
Example:
async function test(){
return Promise.resolve(1);
}const test = async () => {
return 1;
}test().then(alert);
Await
The await
keyword is used inside the async
function to wait for the asynchronous operation.
The use of await
pauses the async function until the promise returns a result (resolve or reject) value. For example:
const test = async () => {
let promise= new Promise((resolve, reject) => {
setTimeout(() => resolve(“done!”), 1000)
}
let result= await promise; // wait until promise resolves
alert(result); // “done!”
}
🛠 Error handing
When you use promise
or async
function and your request got rejected in this case you have many ways to handle request error in promise
const test = async () => {
await Promise.reject(new Error(“Opps!”, options, fileName, lineNumber));
}const test = async () => {
throw new Error(“Opps!”);
}const test = async () => {
try{
let res = await fetch(‘url’);
let user = await res.json();
} catch(err){
alert(err);
}
}
For understanding new Error() checkout
Thank you for reading 🙏