JavaScript - sakib03/Interview GitHub Wiki

Important Links

LeetCode

HackerRank

Preparing for a Frontend Interview

JavaScript Interview Questions & Answers

ECMAScript Features - ES2015/ES6 to ES2023/ES14

ES2015+ cheatsheet

JavaScript Design Patterns

JavaScript Theory: Promise vs Observable

Javascript: call(), apply() and bind()

JavaScript EventLoop

JavaScript Shallow copy & Deep copy

Introduction to Object Oriented Programming in JavaScript

Debouncing in JavaScript

Callbacks vs Promises in JavaScript

What are Pure Functions and Side Effects in JavaScript?

What Is Data Encryption: Types, Algorithms, Techniques and Methods

What Is SHA-256 Algorithm: How it Works and Applications

OAuth vs JWT (JSON Web Tokens): An In-Depth Comparison

Understanding package.json versioning


YouTube Links

JavaScript Fundamentals Crash Course

Advanced JavaScript Crash Course

Asynchronous JavaScript Crash Course

10 JavaScript Features to Know for React/Vue/Angular

JavaScript Algorithms and Data Structures


next-gen-js-summary

In this module, I provided a brief introduction into some core next-gen JavaScript features, of course focusing on the ones you'll see the most in this course. Here's a quick summary!

let & const

let and const basically replace var . You use let instead of var and const instead of var if you plan on never re-assigning this "variable" (effectively turning it into a constant therefore).

Read more about let

[Read more about const](https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/const)

ES6 Arrow Functions

Arrow functions are a different way of creating functions in JavaScript. Besides a shorter syntax, they offer advantages when it comes to keeping the scope of the this keyword (see here).

Arrow function syntax may look strange but it's actually simple.

function callMe(name) { 
   console.log(name);
}

which you could also write as:

const callMe = function(name) {
   console.log(name);
}

becomes:

const callMe = (name) = {
   console.log(name);
}

Important:

When having no arguments, you have to use empty parentheses in the function declaration:

const callMe = () = { 
   console.log('Max!');
}

When having exactly one argument, you may omit the parentheses:

const callMe = name = { 
   console.log(name);
}

When just returning a value, you can use the following shortcut:

const returnMe = name = name

That's equal to:

const returnMe = name = { 
   return name;
}

Read more

Exports & Imports

In React projects (and actually in all modern JavaScript projects), you split your code across multiple JavaScript files - so-called modules. You do this, to keep each file/module focused and manageable.

To still access functionality in another file, you need export (to make it available) and import (to get access) statements.

You got two different types of exports: default (unnamed) and named exports:

default => export default ...;

named => export const someData = ...;

You can import default exports like this:

import someNameOfYourChoice from './path/to/file.js';

Surprisingly, someNameOfYourChoice is totally up to you.

Named exports have to be imported by their name:

import { someData } from './path/to/file.js';

A file can only contain one default and an unlimited amount of named exports. You can also mix the one default with any amount of named exports in one and the same file.

When importing named exports, you can also import all named exports at once with the following syntax:

import * as upToYou from './path/to/file.js';

upToYou is - well - up to you and simply bundles all exported variables/functions in one JavaScript object. For example, if you export const someData = ... (/path/to/file.js) you can access it on upToYou like this: upToYou.someData.

Classes

Classes are a feature which basically replace constructor functions and prototypes. You can define blueprints for JavaScript objects with them.

Like this:

class Person {
   constructor () {
      this.name = 'Max';
   }
}

const person = new Person();
console.log(person.name); _// prints 'Max'_

In the above example, not only the class but also a property of that class (=> name) is defined. They syntax you see there, is the "old" syntax for defining properties. In modern JavaScript projects (as the one used in this course), you can use the following, more convenient way of defining class properties:

class Person {
   name = 'Max';
}

const person = new Person();
console.log(person.name); _// prints 'Max'_

You can also define methods. Either like this:

class Person {
   name = 'Max';
   printMyName () {
      console.log(this.name); _// this is required to refer to the class!_
   }
}

const person = new Person();
person.printMyName();

Or like this:

class Person {
   name = 'Max';
   printMyName = () = {
      console.log(this.name);
   }
}

const person = new Person();
person.printMyName();

The second approach has the same advantage as all arrow functions have: The this keyword doesn't change its reference.

You can also use inheritance when using classes:

class Human {
   species = 'human';
}

class Person extends Human {
   name = 'Max';
   printMyName = () = {
      console.log(this.name);
   }
}

const person = new Person();
person.printMyName();
console.log(person.species); _// prints 'human'_

Spread & Rest Operator

The spread and rest operators actually use the same syntax: ...

Yes, that is the operator - just three dots. It's usage determines whether you're using it as the spread or rest operator.

Using the Spread Operator:

The spread operator allows you to pull elements out of an array (=> split the array into a list of its elements) or pull the properties out of an object. Here are two examples:

const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5]; _// This now is [1, 2, 3, 4, 5];_

Here's the spread operator used on an object:

const oldObject = {
   name: 'Max'
};
const newObject = {
   ...oldObject,
   age: 28
};

newObject would then be

{
   name: 'Max',
   age: 28
}

The spread operator is extremely useful for cloning arrays and objects. Since both are reference types (and not primitives), copying them safely (i.e. preventing future mutation of the copied original) can be tricky. With the spread operator you have an easy way of creating a (shallow!) clone of the object or array.

Destructuring

Destructuring allows you to easily access the values of arrays or objects and assign them to variables.

Here's an example for an array:

const array = [1, 2, 3];
const [a, b] = array;
console.log(a); _// prints 1_
console.log(b); _// prints 2_
console.log(array); _// prints [1, 2, 3]_

And here for an object:

const myObj = {
   name: 'Max',
   age: 28
}
const {name} = myObj;
console.log(name); _// prints 'Max'_
console.log(age); _// prints undefined_
console.log(myObj); _// prints {name: 'Max', age: 28}_

Destructuring is very useful when working with function arguments. Consider this example:

const printName = (personObj) => {
   console.log(personObj.name);
}
printName({name: 'Max', age: 28}); _// prints 'Max'_

Here, we only want to print the name in the function but we pass a complete person object to the function. Of course this is no issue but it forces us to call personObj.name inside of our function. We can condense this code with destructuring:

const printName = ({name}) => {
   console.log(name);
}
printName({name: 'Max', age: 28}); _// prints 'Max'_)

We get the same result as above but we save some code. By destructuring, we simply pull out the name property and store it in a variable/ argument named name which we then can use in the function body.


Notes

What is ECMAScript?

ECMAScript is a Standard for scripting languages such as JavaScript, JScript, etc. It is a trademark scripting language specification. JavaScript is a language based on ECMAScript. A standard for scripting languages like JavaScript, JScript is ECMAScript.

What are the difference between var, let & const?

var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared. They are all hoisted to the top of their scope.

What are the new features introduced in ES6?

  • Let & Const
  • Template Strings
  • Spread & Rest Operator
  • Default Function Parameter
  • Arrow Functions
  • Object Literals
  • Destructuring of Arrays & Objects
  • Class Syntax
  • Class Inheritance
  • Generators (Used when function needs a pause – function* and yield & .next())

What are the DataTypes in JavaScript?

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by JavaScript engine.

Data types that are known as primitive values in JavaScript are numbers, strings, booleans, null, undefined. Objects such as functions and arrays are referred to as non-primitive values. The fundamental difference between primitives and non-primitives is that primitives are immutable and non-primitives are mutable.

What are the Operators in JavaScript?

  • Arithmetic Operators: + - * /
  • Assignment Operators: = += -+ *= /=
  • Comparison Operators: == === != !== > >= < <=
  • Logical Operators: && ||
  • Modulus: %
  • Increment/Decrement: ++Prefix Postfix++
  • Ternary Operator: Condition ? True : False

What are the Loops in JavaScript?

  • While, Do While & For Loop
  • break; keyword to break the loop
  • continue; keyword to continue the loop

What are the Scopes in JavaScript?

  • Local Scope (Variable created inside a function)
  • Global Scope (Variable created outside a function)
  • Block Scope (Variable created in a block {})

What are the ways to create an Array in JavaScript?

  • var variable = [];
  • var variable = new Array();

What are the ways to create an Object in JavaScript?

  • var variable = {};
  • var variable = new Object();
  • var variable = Object.create();

What are the Number Methods in JavaScript?

  • toExponential()
  • toFixed()
  • toPrecision()

Global JavaScript Methods For Converting Variables to Numbers:

  • ParseInt()
  • ParseFloat()
  • Number()

Number Properties:

  • MAX_VALUE : Returns the largest number possible in JavaScript
  • MIN_VALUE : Returns the smallest number possible in JavaScript
  • POSITIVE_INFINITY : Represents infinity (returned on overflow)
  • NEGATIVE_INFINITY : Represents negative infinity (returned on overflow)
  • NaN : Represents a "Not-a-Number" value

What are the String Methods in JavaScript?

  • IndexOf(string, position)
  • lastIndexOf(string, position)
  • search(string)
  • slice(start, end)
  • substring(start, end)
  • substr(start, length)
  • replace(old, new)
  • toUpperCase()
  • toLowerCase()
  • concat()
  • trim()
  • padStart()
  • padEnd()
  • charAt(index)
  • charCodeAt(index)
  • split(separator)

What are the Array Methods in JavaScript?

  • join(separator)
  • pop()
  • push(“”)
  • shift()
  • unshift(“”)
  • splice(0,0,””)
  • concat()
  • slice()
  • sort()
  • reverse()

Array Iteration Methods:

  • forEach()
  • map()
  • filter()
  • reduce()
  • every()
  • some()
  • indexOf()
  • lastIndexOf()
  • find()
  • findIndex()

Read more


Logical Question

Print number pattern

Print star patterns

Print pyramid

Write own map function

const array = [1,2,3,4,5];

// Original Map Function
array.map((number, index, array) => console.log(number, index, array));

// Own Map Function
Array.prototype.myMap = function(callback){
    let newArray = [];
    for(let index = 0; index < this.length; index++){
        newArray.push(callback(this[index], index, this));
    }
    return newArray;
}
array.myMap((number, index, array) => console.log(number, index, array));

Write own filter function

const array = [1,2,3,4,5];

// Original Filter Function
const filterArray = array.filter((number, index, array) => number > 3);
console.log(filterArray);

// Own Filter Function
Array.prototype.myFilter = function(callback){
    let newArray = [];
    for(let index = 0; index < this.length; index++){
        if(!!callback(this[index], index, this)){
            newArray.push(this[index]);
        }
    }
    return newArray;
}
const newFilterArray = array.myFilter((number, index, array) => number > 3);
console.log(newFilterArray);

Remove nested array from an array and Print all values in one array

const array = [1,2],[3,4],[5](/sakib03/Interview/wiki/1,2],[3,4],[5);
console.log(array.flat());

Given two strings, return true if they are anagrams of one another

function anagrams(str1, str2){
    const array = [];
    Array.from(str1).map(char => {
        if(str2.includes(char)){
            array.push(true);
        } else {
            array.push(false);
        }
    });
    return array.every(char => char);
}
console.log(anagrams("ote", "two"));

Given a string, reverse each word in the sentence

var string = "Welcome to this Javascript Guide!";

// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");

// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {
	return string.split(separator).reverse().join(separator);
}

Remove duplicate elements

// ES6 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];

Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8]

How would you use a closure to create a private counter?

function counter() {
	var _counter = 0;
		// return an object with several functions that allow you
		// to modify the private _counter variable
		return {
			add: function(increment) { _counter += increment; },
			retrieve: function() { return 'The counter is currently at: ' + _counter; }
		}
}

// error if we try to access the private variable like below
// _counter;

// usage of our counter function
var c = counter();
c.add(5); 
c.add(9); 

// now we can access the private variable in the following

Write a function to create a new array of objects with consolidated values of FullName & Address from an existing array of objects having values like Name, FirstName, LastName, Street, City & PIN.

const details = [{
    firstname: "Roshanara",
    lastname: "Shaikh",
    city: "Mumbai",
    pin: "400020",
},
{
    firstname: "Sakib",
    lastname: "Shaikh",
    city: "Navi Mumbai",
    pin: "410210",
}];
const newDetails = details.map(detail => {
    const object = {
        fullname: `${detail.firstname} ${detail.lastname}`,
        address: `${detail.city} ${detail.pin}`,
    };
    return object;
});
console.log(newDetails);

Write a function for the following

Question

const finalResult = plus(9).minus(2).plus(4).plus(3).minus(5).getResult(); // result 9

Answer

function plus(x) {
    let res = x;
    function add(val){
        res += val;
        return this;
    }
    function sub(val){
        res -= val;
        return this;
    }
    function getResult() {
        return res;
    }
    return {
        plus: add,
        minus: sub,
        getResult: getResult,
    };
}

// ----------------- OR -----------------

function plus(res) {
    return {
        plus(val){
            res += val;
            return this;
        },
        minus(val){
            res -= val;
            return this;
        },
        getResult() {
            return res;
        },
    };
}

Write a function for the following

Question

arr1=['ab','cd','ef']
arr2=['af','ee','ef']

/* compare those array and check the element are same or not
result like // [yes,no,yes]
because arr1[0] and arr2[0] have common 'a'
arr1[2] and arr2[2] is common
try to create solution the above problem */

Answer

function check(s1, s2){
    var map = new Map();
    for (var i = 0; i < s1.length; i++){
        if(map.has(s1[i].charCodeAt(0))){
            map[s1[i].charCodeAt(0)]++;
        } else {
            map[s1[i].charCodeAt(0)]=1;
        }
    }
    for (var i = 0; i < s2.length; i++)
        if (map[s2[i].charCodeAt(0)] > 0)
            return true;

    return false;
}

let array = [];
function equalityCheck(arr1, arr2){
    for(let index = 0; index < arr1.length; index++){
        check(arr1[index], arr2[index]) ? array.push("yes") : array.push("no");
    }
}
equalityCheck(arr1, arr2);

console.log(array);

Write a function for the following

Question

let data = 'bbccceeeexdd';
Output - b2c3e4x1d2

Answer

function encrypt(data){
    let map = new Map();
    for(let i = 0; i < data.length; i++){
        if(map.has(data[i].charAt(0))){
            map.set(data[i], map.get(data[i])+1);
        } else {
            map.set(data[i], 1);
        }
    }
    return Array.from(map).toString().replace(/,/g, "");
}
console.log(encrypt(data));

Write a function for the following

Question

var temp = 34567
Output - 3,4,5,6,7

Answer

function convertToCommaSeperated(){
    const value = Array.from(temp.toString()).toString();
    console.log(value);
}
convertToCommaSeperated(temp);

Write a function for the following

Question

Find duplicate value and return unique value:-
let data = [
{id:1, name: "john", city: "mumbai"},
{id:1, name: "john", city: "mumbai"},
{id:2, name: "Doe", city: "Kolkata"},
{id:5, name: "Kelly", city: "Delhi"},
{id:3, name: "Jemmy", city: "Noida"},
{id:4, name: "Nisham", city: "Banglore"}]

Answer

function createUnique(data){
    const arr = [];
    data.map(item => {
        const strObj = JSON.stringify(item);
        if(!JSON.stringify(arr).includes(strObj)){
            arr.push(item);
        }
    });
    console.log(arr);
}

// ------------------ OR -----------------

function createUnique(data){
    const arr = [];
    data.map(item => {
        if(arr?.every(obj => obj.id !== item.id)){
            arr.push(item);
        }
    });
    console.log(arr);
}

createUnique(data)

Write a function for the following

Question

Maximum repeated value return with count like {Adam:4}:-
var names = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben", "Adam", "Ferry", "Adam","Robert","Adam"];

Answer

let name = {};
names.map(value => {
    if (Object.keys(name).includes(value)){
        name[value] = name[value]+1;
    } else {
        name[value] = 1;
    }
});
console.log(name);

Write a function for the following

Question

This is a demo task.
Write a function:
function solution(A);
that, given an array A of N integers, returns the smallest positive integer (greater than 0) 
that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [-1, -3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].

Answer

function solution(A){
    let sortedUnique = A.sort((a,b) => a-b);
    let smallestNumber = sortedUnique[0];
    let largestNumber = sortedUnique[sortedUnique.length - 1];
    if(largestNumber <= 0) return 1;
    for(let n = smallestNumber; n <= largestNumber; n++){
        if(!sortedUnique.includes(n)) return n;
        if(largestNumber === n) return n+1;
    }
}
console.log(solution([1, 3, 6, 4, 1, 2]));
console.log(solution([1, 2, 3]));
console.log(solution([-1, -3]));

Write a function for the following

Question

Scenario:
Print 'Fizz' for multiple of '3'. 
Print 'Buzz' for multiple of '5'.
Print 'FizzBuzz' for multiple of both '3' & '5'.

Output as follows for the input number '15':
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Answer

function fizzBuzz(n) {
    let fizz = 'Fizz';
    let buzz = 'Buzz';
    for (let i = 1; i <= n; i++) {
        if(i % 3 === 0 || i % 5 === 0){
            console.log(`${i % 3 === 0 ? fizz : ''}${i % 5 === 0 ? buzz : ''}`);
        } else {
            console.log(i);
        }
    }
}
fizzBuzz(15);

Write a function for the following

Question

Write a input box once type any word, word should be display in <p> paragraph:-
<input type="text">
<p id="result">

Write a function for the following

Question

Question

Write a function for the following

Question

Question

Write a function for the following

Question

Question

Answer

class Calculator{
    constructor(){
        this.value = 0;
    }

    add(number){
        this.value += number;
        return this;
    }

    subtract(number){
        this.value -= number;
        return this;
    }

    print(){
        console.log(this.value);
    }
}
class ScientificCalculator extends Calculator{
    square(){
        this.value *= this.value;
        return this;
    }
}

const s = new ScientificCalculator;
s.add(10).subtract(5).square().print();

Code Question

Question 1:

function a(){
	let a=10;
	let a=20;
	console.log(a);
}
a();

Answer: Uncaught SyntaxError: Identifier 'a' has already been declared"

----------------------------------------------------------------------------------------------------

Question 2:

function a() {
	var x=1;
	{
		var x=2;
		console.log(x);
	}
	console.log(x);
}
a();

Answer: // 2 2

----------------------------------------------------------------------------------------------------

Question 3:

function a(){
	let x=1;
	{
		let x=2;
		console.log(x);
	}
	console.log(x);
}
a();

Answer: // 2 1

----------------------------------------------------------------------------------------------------

Question 4:

a={'1':1, '2':2};
b={'1':1, '2':2};
c=b;
if(c==b) alert("i love ckn"); 
if(c===b) alert("i hate ckn");

Answer: // i love ckn // i hate ckn

----------------------------------------------------------------------------------------------------

Question 5:

a={'1':1, '2':2};
b={'1':1, '2':2};

if(a==b) alert("i love ckn"); 
if(a===b) alert("i hate ckn");

Answer: nothing

----------------------------------------------------------------------------------------------------

Question 6:

function abc() {
	var a = '10';
}
abc();
console.log(a);

Answer: Uncaught ReferenceError: a is not defined

----------------------------------------------------------------------------------------------------

Question 7:

Print ten times 10

Answer: Print ten times :- 10