1. Explain the difference between null and undefined ?
Null and undefined are very confusing in nature for a beginner. Let’s look at the ‘undefined’ first.
When you declare a variable without assigning a value to it in javascript, by default the variable will have value of undefined .
let ‘s see an example
let a;
console.log('Value of a is ',a);
And here is the result
Value of a is undefined
Now if we see the datatype of this variable ‘a’ in the above code by writing the following code
console.log('Data Type of a is ',typeof a);
And the output will be
Datatype of a is undefined
Isn’t it interesting the value and the type of variable ‘a; both are undefined which is very unique to JavaScript.
Now lets talk about ‘Null’ . Null means nothing. Lets write some code and see how null works in JavaScript
let b = null
console.log('Value of b is ',b)
And the out put will be
Value of b is null
Let’s check the type of variable ‘b’ by writing the following code
console.log('Data Type of b is ',typeof b);
And the output will be
Datatype of b is object
Null in JavaScript is treated as an object so the output is object
Now if we compare ‘a’ and ‘b’ by using comparison operator like the following we will see something interesting
if(a == b){
console.log(`a is equal to b`)
}else{
console.log(`a is not equal to b`)
}
And the output will be.
a is equal to b
How come this is possible ??
Because in JavaScript null and undefined both represent nothingness . So they are equal but there data types are different. So that is why it is recommended that when you do comparison between two variables and you are not sure of their types you should using Strict equality operator === rather than comparison operator ==. So if we change == to === then we should see the expected result
if(a === b){
console.log(`a is equal to b`)
}else{
console.log(`a is not equal to b`)
}
And the now the output will be as expected
a is not equal to b
2. When do you get ‘Nan’ as output in JavaScript?
Nan stands for ‘Not a Number’ . When you perform an arithmetic operation (except + as + also represents concatenation operator in JavaScript ) on a non numeric value (String value) you get ‘Nan’ as output. Let’s find out with a sample code
let a = 10
let b = 'Some Value but not a number'
console.log(a-b)
And the output will be
NaN
Also remember you can’t compare Nan with any arithmetic expression . It will always return false . Because every time NaN returns an unique value. If we write the following code
if((a-b) == NaN)
console.log('Valid')
else
console.log('Invalid')
We will always get the following output
Invalid
That means though output (a-b) in the above program is Nan but when we compare with NaN it always returns an unique value and that is why the above if condition will always be false
The Datatype of NaN will always be a number. You can think of NaN as a function always generating some unique number
3. What is Type Coercion in Javascript ?
The type coercion referes to the conversion of values from one type to another. Type coercion can be implicit or explicit
Implicit Type Coercion:
Implicit type Coercion refers to the automatic conversion of the unexpected data type to an expected data type . Let’s check with some code
let a=8;
a= a + ""
console.log('Value of a is ',a)
console.log('Type of a is ', typeof a)
And the output will be
Value of a is 8
Type of a is string
Here the during the operation a + “” The value of a has been converted to String from number as the operation was a string concatenation and Javascript implicitly coerced the type of a to String
Explicit Type Coercion –
Explicit Type Coercion refers to the conversion of type explicitly for your needs . for that purpose we use functions like Number(),String(),parseInt(), parseFloat() etc. Let’s check with a sample code
let b = "8"
let c = 9;
console.log(Number(b)+c)
The output will be 17 . The Number function converts the string b to a number and resultant value became 17
To prevent type coercion in Javascript you should always be aware of what kind of values you are using when you are performing some operation .
For example to prevent Type coercion to occur in a comparison operation you should always use strict equality operators (=== and !==) rather than normal comparison operators like (== and !=) Let’s check with an example
let x=10
let y="10"
if(x==y)
console.log('Invalid Operation')
if(x===y){
console.log('Invalid Operation')
}else{
console.log('Valid Comparison')
}
For the first if condition with (==) sign the output will be
Invalid Operation
As x is a number and y is string but when comparing with == the implicit type coercion happened which result in the above output
But in the next if condition with the x===y where comparison is being done by === it also check the type along with value so no type coercion will happen and you will get the following output
Valid Comparison
4. Difference between var, let and const in Javascript ?
Let’s first see what are var , let and const in javascript
The var and let keywords in Javascript let us created variables whose values can be reassigned. The variables created with above mentioned keywords can be assigned values at the time of declaration or after they have been declared.
On the other hand const keywords also creates a variable whose values can be reassigned so it is imperative to assign a value to a variable declared with const at the time of declaration
We can differentiate between var , let and constant based on the following three things
- Redeclaration and Reassignment
- Scope of the variable
- Hoisting
1. Redeclaration and Reassignment –
The variables declared with var can be redeclared
The variables declared with let can’t be redeclared
The variables declared with const can’t be redeclared
Let’s check with quick example
var x=10;
var x=20;
let y=10;
let y=20;
const z=20;
const z=30;
The output you will get if you run this above program
If we remove the declaration let y=20 Then the output will become
So variables declared with let and const cannot be redeclared
Now lets talk about reassignment of values to a variable
Variables declared with var can be reassigned values
Variables declared with let can be reassigned values
Variables declared with const can’t be reassigned values
Now let’s change the above program a bit and here is the modified program
var x=10;
x=20;
let y=30;
y=40
const z=50;
z=60;
And here you will see an error
The variables x and y didn’t throw any errors as they have been declared with var and let respectively but z has been declared with const so it throws an error when we are trying to reassign a value of 60 to z.
Scope of variable –
Let’s first understand what we mean by scope of a variable. The scope of variable refers to the fact where the variables can be accessed The scope a variable can be of three types global, local and block scope
A variable declared outside of any function has a global scope
A variable declared inside a function have local scope
A variable declared inside a block of code is of block scope. A block in Javascript is code fragment that is enclosed within a curly brace ( { } )
The variables declared with var keyword have only global and local scope .
The variables declared with let keyword have global, local and block scope
The variables declared with const keyword have global, local and block scope
Lets see this practically with an example code . Output has been commented beside
// Global Scope
var x = 10
let y = 20
let z = 30
// Function Scope/ Local Scope
function demo(){
var a = 40;
let b = 50;
let c = 60;
console.log('Value of a = ', a) // Value of a = 40
console.log('Value of b = ', b) // Value of b = 50
console.log('Value of c = ',c) // Value of c = 60
}
// Function called
demo();
// Block Scope
if(true){ // Block Starts
var p =70
let q = 80;
const r = 90
}// Block ends
// Global scoped variables
console.log('Value of x = ', x) // Value of x = 10
console.log('Value of y = ', y) // Value of y = 20
console.log('Value of z = ',z) // Value of z = 30
// Function scoped / Local Scoped variables
console.log('Value of a = ', a) // Error
console.log('Value of b = ', b) // Error
console.log('Value of c = ',c) // Error
// Block scoped variables
console.log('Value of p = ', p) // Value of p = 70
console.log('Value of q = ', q) // Error
console.log('Value of r = ',r) // Error
Hoisting –
Hoisting is a Javascript feature which moves all the declarations to the top of the program.
A variable declared with var always got hoisted to the top of the program
A variable declared with let won’t be hoisted at the top of the program
A variable declared with const won’t be hoisted at the top of the prorgram
Let’s check with three small programs and there output
numstr = "John"
var numstr;
console.log(numstr);
This program will run smooth as the variable numstr has been declared with var whihc got hoisted at the top of the program so when the program runs javascript sees the declaration of the variable at top and use the variable without any problem and we get the expected output
John
Now lets change the above variable declaration from var to let
numstr = "John"
let numstr;
console.log(numstr);
When you run this program it will throw a reference error as show below
Now lets change the variable declaration from let to const and see what happens
numstr = "John"
const numstr;
console.log(numstr);
This program will not even run as it will throw an syntax error because the const variable haven’t initialized.
So the fact is that using var in your program may create different unwanted problems which let and const will prevent but you will loose some flexibility in teh code.
But for better programming approach Javascript developers are recommended to use let and const instead of var
5. What is the difference between the following two function declarations ?
let xyz= (){
console.log(‘xyz’);
}
function abc(){
console.log(‘abc’)
}
The difference between these two is that function xyz is defined at run time while function abc() is defined as parse time.
Lets understand this with two small bit of code with output
Lets understand this with two small bit of code with output
xyz()
let xyz = function (){
console.log('xyz')
}
This will throw a reference error because xyz is being treated as variable which has been referenced before the initialization
Lets see the second function
abc()
function abc(){
console.log('abc')
}
This function got evaluated at parsing time and and gave output as expected.
abc
6. What are different ways to empty an array in Javascript ?
Let’s assume the following is an array of numbers
let arrayToBeEmptied = [ 23,1,32,45,54,65]
There are many ways we can empty the above array
First Method:
Assign the array an empty array like the following
arrayToBeEmptied = []
A note here if the array has been declared as const it won’t work
Second Method:
Make the array length as 0
arrayToBeEmptied.length = 0
Third Method :
Use splice method
arrayToBeEmptied.splice(0,arrayToBeEmptied.length)
Fourth Method:
Last one is little lengthy
while(arrayToBeEmptied.length!=0){
arrayToBeEmptied.pop()
}
7. What is Nullish Coalescing operator (??) in Javascript ?
Nullish Coalescing operator(??) in Javascript takes two values and returns the second value if the first value is null or undefined
Let’s take an example
let val1;
let val2 = 23
console.log(val1 ?? val2);
In the above code the value of val1 is undefined as there is no value assigned to it so the program will return the value of val2 which is 23 in this case.
You can think of the statement val1 ?? val2 as the replacement for the following code
if(val1 == null || val1 == undefined){
console.log(val2)
}
8. What is template literal ?
A template literal in JavaScript is a string literal that allows you to embed expressions inside the string. They are enclosed in backticks (“`) characters instead of double or single quotes.
It allows us to write multiline strings like the following
`My Name is John
I m 20 years old
I love to play cricket`
Another use of template literal is string interpolation. Without template literals if we need to print a variable with some static string we needed to use concatenation operator like the following
let age = 20
console.log('My Age is '+age);
With string interpolation you can do that with ease
let age = 20
console.log(`My Age is ${age}`)
Some specific use case of template literals are
* They make it easy to insert variables and expressions into strings.
* They can be used to create multi-line strings.
* They can be used to escape special characters.
* They are more concise and readable than string concatenation.
9.What is optional chaining operator (?.)
The optional chaining operator (?.) is a feature introduced in JavaScript as part of the ECMAScript 2020 (ES11) specification. It provides a concise and safe way to access nested properties and methods of an object, especially when dealing with complex data structures where some properties may be null or undefined.
In traditional JavaScript, attempting to access properties or call methods on a nested object that is null or undefined would result in a runtime error, often referred to as a “TypeError” or “Cannot read property ‘…’ of null/undefined.” This can lead to code crashes and the need for verbose and repetitive checks to ensure that each nested property exists before accessing it.
The optional chaining operator helps to address this issue by providing a short-circuiting mechanism. When used, if a property in the chain is null or undefined, the expression will immediately return undefined without throwing an error. If the property exists, the chain continues, and the result is returned.
Here’s the basic syntax of the optional chaining operator
object?.property
object?.method()
Usage Examples:
Accessing nested properties safely:
const user = {
name: 'John',
address: {
city: 'New York',
zipcode: 12345,
},
};
const cityName = user.address?.city; // 'New York'
const streetName = user.address?.street; // undefined (no error)
Calling nested methods safely
const calculator = {
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
const result1 = calculator.add?.(3, 5); // 8
const result2 = calculator.subtract?.(3, 5); // undefined (no error)
It’s important to note that the optional chaining operator is designed to be used in modern JavaScript environments. If you need to support older browsers or environments that do not yet support ECMAScript 2020, you may need to use alternative approaches, such as using explicit null checks or polyfill libraries that provide similar functionality.
10. Difference between map and forEach in Javascript ?
In JavaScript, both map() and forEach() are array methods used to iterate over arrays and perform operations on their elements. However, they have some key differences in their behavior and return values:
- Purpose:
- map(): The map() method creates a new array by applying a provided function to each element of the original array. It returns a new array with the same length as the original array, where each element is the result of the function applied to the corresponding element in the original array.
- forEach(): The forEach() method simply iterates over the elements of the array and executes a provided function on each element. It does not create a new array; instead, it is typically used for side effects, such as logging data or modifying the original array directly.
- Return Value:
- map(): Returns a new array with the same length as the original array, containing the results of the provided function applied to each element.
- forEach(): Does not return anything. It simply iterates over the array.
- Usage:
- map(): Use map() when you want to transform the elements of an array into a new array with modified values, without modifying the original array.
- forEach(): Use forEach() when you want to perform some operation on each element of the array without creating a new array.
Example of map():
const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map((num) => num * 2);
// doubledNumbers is [2, 4, 6, 8]
Example of forEach
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit) => console.log(fruit));
// Output: apple, banana, orange
- Immutability:
- map(): As it returns a new array with modified elements, it does not modify the original array.
- forEach(): Since it does not return anything and is often used for side effects, it can modify the original array elements if the provided function performs such modifications.
- Chaining:
- map(): As it returns a new array, you can chain multiple array methods together after using map().
- forEach(): Since it does not return anything, chaining other array methods directly after forEach() is not possible.
In summary, if you want to create a new array with modified elements based on an existing array, use map(). If you simply need to perform operations on the elements of an array without creating a new array, use forEach().