Search This Blog

2026/08/08

Javascript : Guess output of the code



Guess output of the code.

Code:
//first question
var obj = {
    a: 1,
    b: 2,
    add: function () {
        return this.a + this.b;
    }
}
var r = obj.add();
console.log("r=" + r);

//second question
var obj1 = {
    a: 1,
    b: 2,
    add: function () {
        return this.a + this.b;
    }
}
var s = obj1.add;
console.log("s=" + s());

//third question
var s1 = obj1.add;
s2 = s1.bind(obj1);
console.log("s2=" + s2());

Output:
        r=3
        s=NaN
s2=3


Notes:
wrt obj1.add here s contains the function, but the connection
to obj1 is not retained.In non-strict mode, JavaScript sets: this = globalThis

2026/08/07

deep copy nested object

  Write a code to deep copy nested object.

Code:
var obj ={
    name:"sangram",
    address:{
        city:"mumbai",
        state:"maharashtra",
        pin:"4000**",
office:null,
        contactNo:{
            "landline":"***67-554569",
            "mobile":"**78456729",
        }
    }
}

function deepCopy(obj){
    var deepCopied={}
    for(let key in obj){
        if (obj[key] !== null || typeof obj[key] !== "object") {
            deepCopied[key] = obj[key]
        }else{
            deepCopied[key] = deepCopy(obj[key])
        }
    }
    return deepCopied
}

let x = deepCopy(obj);
console.log("Final Output:",x)

Output:

Final Output: {
  name: 'sangram',
  address: {
    city: 'mumbai',
    state: 'maharashtra',
    pin: '4000**',
office:null,
    contactNo: { landline: '***67-554569', mobile: '**78456729' }
  }
}

Note:deepcopy & deepclone term are used interchangeably in interviews & discussion.

Compare boolean with empty array


Guess output of following program

console.log(Boolean([]));   // true
console.log(![]);           // false

console.log(false == []);   // true
console.log(false == ![]);  // true


Output:
        true
        false
        true
        true

Explation in 3rd line
        console.log(false == []); // false == "" then 0 == 0 then true

In 4t line

        console.log(false == ![]);  //  false == ! true then false == false then true

Type Coercion in comparison




in == type coersion happens in === does not.In == for string comparison
toString method on object is called which can be overridden to get desired
result.

Code :
        const pre={}
       
        console.log(pre.toString()); // "[object Object]"

        const obj = {
        toString() {
        return "{}";
        }
        }

        console.log(obj.toString()); // "{}"
        console.log(obj == "{}");    // true
        console.log(obj === "{}");   // false


Output:
        [object Object]
        {}
        true
false 


Group By Object array based on provided key

Group by following object array based on key "city".

const users = [
  {
    name: "sangram",
    city: "kankavali"
  },
  {
    name: "sagar",
    city: "malvan"
  },
  {
    name: "sachin",
    city: "kankavali"
  }
];



Code :

const users = [
  {
    name: "sangram",
    city: "kankavali"
  },
  {
    name: "sagar",
    city: "malvan"
  },
  {
    name: "sachin",
    city: "kankavali"
  }
];

let obj = {};

let output = users.reduce((acc, item) => {
  if (!acc[item.city]) {
    acc[item.city] = [];
  }
  acc[item.city].push(item);
  return acc;
}, obj);

console.log("Final Output:", output);


Output:
Final Output: {
  kankavali: [
    { name: 'sangram', city: 'kankavali' },
    { name: 'sachin', city: 'kankavali' }
  ],
  malvan: [ { name: 'sagar', city: 'malvan' } ]
}

Second Largest Number in Array

 Given an array find second largest number


Code

let arr=[12,9,13,34,-45,12,67]
let unique = [...new Set(arr)]
console.log("Unique Array:",unique)

unique.sort((a,b)=>b-a)
console.log("Sorted Array:",unique)

console.log("Second Largest Number:",unique[1])

Output:
        [ 12, 9, 13, 34, -45, 67 ]
        [ 67, 34, 13, 12, 9, -45 ]
        Second Largest Number: 34

In form of function:


function findNthLargest(arr,n){
    let unique = [...new Set(arr)]
    unique.sort((a,b)=>b-a)
    if (unique.length < n){
        throw new Error("Array can't have nth largest number")
    }else{
        return unique[n-1]
    }
}

let arr=[12,9,13,34,-45,12,67]
let n=3
console.log(n + "th Largest Number:" + findNthLargest(arr,n))

Output:
    3th Largest Number:13






       

In an Array move zero element to bottom of array

Given an array modify array in such a way that all
zero element are at end non zero element at front

Code

var arr=[5,8,-45,0,6,0,10,-1,67];
console.log("Original Array",arr)

let nonZero = arr.filter((item)=>{
 return item !=0
})

let zero = arr.filter((item)=>{
 return item ==0
})

arr = [...nonZero,...zero]
console.log("Final Output:",arr)

Output:
    Original Array [
    5,  8, -45,  0, 6,
    0, 10,  -1, 67
    ]
    Final Output: [
    5,  8, -45, 6, 10,
    -1, 67,   0, 0
    ]

Another way


var arr = [5, 8, -45, 0, 6, 0, 10, -1, 67];
let j = 0;
for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 0) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
        j++;
    }
}

console.log("Final Output:", arr)