DEV Community

MD. Kais
MD. Kais

Posted on

Top 10 Tricky InterView Question About JavaScript

Truthy vs Falsy:

As well as a type, each value also has an inherent boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre so understanding the concepts and effect on comparison helps when debugging JavaScript applications.

The following values are always falsy:

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefined
  • NaN

Everything else is truthy. That includes:

  • '0' (a string containing a single zero)
  • 'false' (a string containing the text “false”)
  • [] (an empty array)
  • {} (an empty object)
  • function(){} (an “empty” function)

Everything else is truthy.


Null vs Undefined


when it cause undefined?

  • declare but don't put a value.
let kais:
console.log(kais);
//undefined;
Enter fullscreen mode Exit fullscreen mode
  • Don't return a function.
function add(n,m){
   console.log(n+m);
}
const result=add(2,3);
console.log(result)//undefined; //cause no retrun from the function.
Enter fullscreen mode Exit fullscreen mode
  • don't return a value
function add(n,m){
   console.log(n+m);
return
}
const result=add(2,3);
console.log(result)//undefined; //cause no retrun a  value from the function.
Enter fullscreen mode Exit fullscreen mode
  • if the value is not there
const kais={name:'kais',phone:'01213'};
console.log(kais.gf)//undefined;
Enter fullscreen mode Exit fullscreen mode
  • if you set the value as undefined?
let kais=undefined;
console.log(kais);//undefined;
Enter fullscreen mode Exit fullscreen mode

when we get null?

  • when we set the value as null
let kais=null;
//null
Enter fullscreen mode Exit fullscreen mode

in code: https://github.com/Md-Kais/javaScript_interview/blob/main/nullVsundefined.js

Double equal vs Triple Equal

//tripleEqualVsDoubleEqual
//popular interview ques
//double equal never check data type of this variable{values};
//triple equal checks {data type+value}(strictly checks)

const first=0;
const second=false;
if(first==second){
    console.log('double match');//double match cause 0 means false
}
if(first===second){
    console.log('triple match');//0 is number and false is boolean type(never match);
}
const kais=1;
const kice='1';
if (kais==kice) {
    console.log('double match'); //value matches
}
if (kais===kice) {
    console.log('triple match');//triple never match cause kais is number and kice is boolean
}
//ALL  triple match is double match  but all double match isnot triple match
//as a jr. ,you use triple equal
const rais = 1;
const rice = 1;
if (kais == kice) {
    console.log('double match'); //value matches
}
if (rais === rice) {
    console.log('triple match');//triple matches cause of datatype+value
}

Enter fullscreen mode Exit fullscreen mode

Scope:


  • Local Scope
  • Global Scope
  • Function Scope: Each Object/ function create a function scope

Global Scop


  • When programmer declare a undeclared variable inside a function then it creates a global scope and become a global variable; Using Strict mode to solve this problem

In "Strict Mode", undeclared variables are not automatically global. 'use strict'; at the top of the code makes it strict mode. more at: https://www.w3schools.com/js/js_strict.asp

myFunction();
function myFunction() {
  carName = "Volvo";
  var friend="rohit";
  console.log(friend);//rohit;
}
console.log(friend);//error; variable not declared.
console.log(carName);//Volvo. cause creates a global variable.
Enter fullscreen mode Exit fullscreen mode
  • When programmer create a variable name using var. It becomes global variable.

Local Scope


  • Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have Function scope: They can only be accessed from within the function.

myFunction();
function myFunction() {
  carName = "Volvo";//global scope.
  var friend="rohit";//friend is a local variable
  console.log(friend);//rohit;
}
console.log(friend);//error; variable not declared.It's Local variable.
console.log(carName);//Volvo. cause undeclaration creates a global variable.
Enter fullscreen mode Exit fullscreen mode

the Lifetime of JavaScript Variables


The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab).


scope problem

function Counter() {
  let count = 0;

  this.up = function() {
    return ++count;
  };
  this.down = function() {
    return --count;
  };
}

let counter = new Counter();

alert( counter.up() ); // ?
alert( counter.up() ); // ?
alert( counter.down() ); // ?
//1,2,1
Enter fullscreen mode Exit fullscreen mode

Closure(main CONFUSING PART)


Closure means that things which creates a Unique Environment Inside an Environment. it means there is a part [[ environment ]]

definition if you a function within a function , execution of the inner function will create a scope inside of the outer function-a nested scope. Because the inside function is enclosed by outer function scope, the inner function
https://www.thatjsdude.com/images/scope/closureTwoFunc.png

https://www.thatjsdude.com/jsConcepts/concepts/scope.html

function a() {
    function b() {
        console.log('closure');
    }
    b(); //creates closure
    return false;//to skip undefined replying
}
//you call a function inside a function. so, you call the outer function is or not . the inner function execute.

//make a complex closure function;

function panda() {
    let penty = 0;
    return function() {
        penty++;
        return penty;
    }




}
const penty1 = panda();
console.log(penty1());
console.log(penty1());
console.log(penty1());
console.log(penty1());
console.log(penty1());

const penty2=panda();
console.log(penty2());
console.log(penty2());
console.log(penty2());

console.log(penty1());
Enter fullscreen mode Exit fullscreen mode

Alt Text

Difference Between Bind,Call,Apply


what is bind?

ans:
1. Bind an object to a function.
2.reference it using 'this'.


//bind reduce the code repitition and make code DRY
//bind is calling a function without owner of this function
//suppose rohit has an axe . and you land it to kais. and kais can chope the wood but kais is not the owner of the axe
// so bind is a function calling.

//lets call two object
let c_1 = {
    x: 2,
    y: -2
}
let c_2 = {
    x: 22222,
    y: -2333
}
function printObject() {
    return(this.x + ',' + this.y);
}
let ans_1 = printObject.bind(c_1);
let ans_2 = printObject.bind(c_2);
console.log(ans_1(),
ans_2());
console.log(printObject());//undifined, undifined . cause this or object can't mention before
Enter fullscreen mode Exit fullscreen mode

Call vs Apply

//call vs Apply
// call -> c, comma
//apply -> a, array
//call and apply is almost same. you have to call a object like this : 
//call:
//syntax: name_of_the-object_where_original_function_is_created.function_name.call(where_u_apply,data1,data2,data3,........................,dataN);
const normalPerson = {
    firstName: "Md.",
    lastName: "Kais",
    getFullName: function () {
        return (`${this.firstName} ${this.lastName}`);
    },//anonymus function;
    salary: 5500

}
const heroPerson = {
    firstName: "Masfdsdaf",
    lastName: "Ksfsadfd",
    getFullName: function () {
        return (`${this.firstName} ${this.lastName}`);

    },//anonymus function;
    salary: 10500,
    netSalary: function(TAX, tips, dutyless) {
        return (this.salary - TAX - tips - dutyless);
        console.log('hello');
    }
}
//call->comma
console.log(heroPerson.netSalary.call(normalPerson,55,550,100));//4795
console.log(heroPerson.netSalary.call(heroPerson, 55, 550, 100));//9795
//apply-> array
//data is passed by the help of array
//syntax: name_of_the-object_where_original_function_is_created.function_name.call(where_u_apply,[data1,data2,data3,........................,dataN]);

console.log(heroPerson.netSalary.apply(normalPerson, [55, 550, 100]));//4795
console.log(heroPerson.netSalary.apply(heroPerson, [55, 550, 100]));//9795
Enter fullscreen mode Exit fullscreen mode

this keyword(important)


which is left side of the dot , this keyword follow that .

if there is no context , then this refers the whole window.

if there is an element , then this refers the that element.

if there is an object, then this refers that object.

const myObject = {
            name: 'Kuddus Ali',
            getFullName: function () {
                console.log(this);
                // this myObject er jonno kaj korbe. 
                // kintu amra jodi ei method ta onno object er jonno declare kori, tahole this oi method er hoye kaj korbe. 
                return 'Mr. ' + this.name;
            }
        }
        // console.log(myObject.getFullName);
        myObject.getFullName();
        const anotherObject = {
            name: 'Bidyut Ali',
        }
        anotherObject.getFullName = myObject.getFullName;
        // console.log(anotherObject.getFullName);
        anotherObject.getFullName();

        function add(a, b) {
            console.log(this);
            return a + b;
        }
        add(5, 7);
        // ekhane add method or function er bam pashe kono object dot(.) diye jukto nai, tai this er value ta hobe window. 

        anotherObject.sum = add;
        // add function ta ke anotherObject er sum method hisebe declare korlam. 

        anotherObject.sum();
        // ekhane sum() function er bame dot(.) diye anotherObject ase. 
        // tai seta this hisebe jabe add function er vitor. 

        setTimeout(function () {
            console.log(this);
        }, 5000);
        alert('I will come after 5 seconds delay');
//The keyword  you use to refer to an object through which they were invoked is this
Enter fullscreen mode Exit fullscreen mode

Event Loop , Stack and Queue


Alt Text

Event loop means, how javascript works when execute that code. JavaScript event loops works in a stack way. It reads all the code. then start executing. Which comes first that execute last. Look at the video.

Alt Text

video link : https://www.youtube.com/watch?v=8aGhZQkoFbQ&vl=en

Alt Text

Callback Function


A callback is a function passed as an argument to another function

This technique allows a function to call another function

A callback function can run after another function has finished

Callback Function Sequence

JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.

function hello(name){
  console.log('hellp'+name);
}
hello(kais);
hello(rohit);
//hellpkais;
//hellprohit;
Enter fullscreen mode Exit fullscreen mode

DOM API


DOM→ Document Object Model.

There are three types of things we have to care about when we create any website. They are

  • Content
  • Presentation
  • Behavior

We know content is controlled by HTML, presentation by CSS where the behavior which is the most important factor for a dynamic website is controlled by JavaScript. Now to make them work altogether, we need something that could be accessed by all of the technology we use(HTML, CSS, JavaScript). What if we create and control all of the 3 concerns using just this 'something'. This will be much easier. From here the idea of the DOM first came. This 'something' we were talking about is nothing but DOM API.

When we create any content for the Internet using HTML, the browsers convert them to a document object which contains all the elements we mentioned in the content as nodes. If we assign different styles to an individual element, this gets also saved in its node in the DOM.

Now here is the good thing. We can access any of the contents and presentations using JavaScript to manipulate them for different conditions, in other words adding behaviour to make the content dynamic.

<!DOCTYPE html>
<html>
  <head>
    <title>DOM Page</title>
  </head>
  <body>
    <h1>The main heading</h1>
    <p class="highlight">An interesting summary of this content.</p>
    <p>
      Some supplementary details to accompany our discussion.
             It also has a <a href="#">link</a>.
    </p>
    <div class="widget">
      <div class="foo"></div>
    </div>
    <table>
      <thead>
        <tr>
          <th>School</th>
          <th>Color</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>UNC Chapel Hill</td>
          <td>Carolina Blue</td>
        </tr>
        <tr>
          <td>NC State</td>
          <td>Wolfpack Red</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The above HTML will look like this in the DOM object.

Alt Text

The image and the code are taken from here

Top comments (0)