Search This Blog

2026/08/09

hasOwnProperty in Javascript


var key="constructor";
var obj = {};

if(obj[key]) {
    console.log("obj has property 'constructor'");
}


if(obj.hasOwnProperty(key)) {
    console.log("obj has own property 'constructor'");
}else{
    console.log("obj does not have own property 'constructor'");
}

Output:
obj has property 'constructor'
obj does not have own property 'constructor'

Explanation:
The code defines a variable `key` with the value "constructor" and an empty object `obj`.
It then checks if the object has a property with the name specified in `key` using
the `if(obj[key])` condition.
    Since all objects in JavaScript inherit from `Object.prototype`,
the object has the 'constructor' property through its prototype chain.so object has property 'constructor' is printed.
Next, it checks if the object has its own property with the name specified in `key`
using the `obj.hasOwnProperty(key)` method.
    Since the object does not have its own property named 'constructor',
the output "obj does not have own property 'constructor'" is printed.  



Javascript count occurance of characters in sentence



var naam = "hare krishna hare krishna krishna krishna hare hare hare rama hare rama rama rama hare hare";

function countCharacters(namm) {
    var charCount = {};
    for (var i = 0; i < naam.length; i++) {
        var char = naam[i];
        if (charCount[char]) {
            charCount[char]++;
        } else {
            charCount[char] = 1;
        }
    }
    return charCount;
}
console.log(countCharacters(naam));

Output:
{
  h: 8,
  a: 16,
  r: 12,
  e: 8,
  ' ': 15,
  k: 4,
  i: 4,
  s: 4,
  n: 4,
  m: 4
}
Explanation:
The code defines a string `naam` containing the phrase "hare krishna hare krishna
krishna krishna hare hare hare rama hare rama rama rama hare hare".
The function `countCharacters` takes this string as input and counts the occurrences
of each character in the string.

It initializes an empty object `charCount` to store the character counts.
It then iterates through each character in the string, checking if the character
already exists in the `charCount` object. If it does, it increments the count;
if not, it initializes the count to 1. Finally, it returns the `charCount` object,
which contains the frequency of each character in the string. The output shows the
counts of each character, including letters and spaces.

symbol in javascript


const id = Symbol("id");
const user = {
  name: "John",
  age: 30,
  [id]: 12345
};
console.log(user[id]); // 12345
console.log(user.id); // undefined
console.log(user); // { name: 'John', age: 30, [Symbol(id)]: 12345 }

Output:
12345
undefined
{ name: 'John', age: 30, [Symbol(id)]: 12345 }

Brief Explanation:
use of symbols as unique property keys in objects. In this code, a symbol is
created using `Symbol("id")`, which serves as a unique identifier for the `id`
property in the `user` object. The `user` object has three properties: `name`, `age`,
and a symbol-based property `[id]`.

When accessing the symbol-based property using `user[id]`,
it correctly retrieves the value `12345`. However, trying to access
it using `user.id` returns `undefined` because the property key is a symbol,
not a string.

Finally, logging the entire `user` object shows that it contains the symbol-based property

along with the other properties. 

function call with new keyword

 


function person(fistName, lastName) {
    this.fistName = fistName;
    this.lastName = lastName;
}

var person1 = new person("John", "Doe");
var person2 = person("Jane", "Smith");

console.log(person1); // John Doe
console.log(person2); // undefined

Output:
person { fistName: 'John', lastName: 'Doe' }
undefined

Notes:
    whenever you call a function with the `new` keyword, it creates a new object and sets the
    context 0f `this` to that new object. In the case of `person1`, it correctly creates a
    new instance of the `person` function, and you can see the properties `fistName` and
    `lastName` are set to "John" and "Doe" respectively.

    but when you call `person` without the `new` keyword, as in the case of `person2`,
    it does not create a new object. Instead, it calls the function in the
    global context (or undefined in strict mode), and since there is no return
    statement in the function, it returns `undefined`. Therefore, `person2` is `undefined`,
    and trying to access its properties will result in an error.


Custom map function in javascript



//implementing custom map function
function double(num){
    return num*2;
}


function customMap(arr,callback,index,length){
    var newArr = [];
    for(var i=0; i<length; i++){
        newArr[index] = callback(arr[i]);
        index++;
    }
    return newArr;
}

var arr=[1,2,45,10,5,6,7,8,9];
var doubled = customMap(arr,double,0,arr.length);
console.log(doubled);

//Native Map Function
var newArr = arr.map((item)=>{
    return item*2;
})

console.log(newArr);

Output:
[ 2, 4, 90, 20, 10, 12, 14, 16, 18 ] [ 2, 4, 90, 20, 10, 12, 14, 16, 18 ]


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)

   

2026/04/16

Express typescript,typeorm & multer

npm install express
npm install -D typescript ts-node nodemon @types/node @types/express
npx tsc --init
mkdir src
npm install dotenv
npm install typeorm reflect-metadata mysql2
npm install -D @types/node
npm install multer
npm install -D @types/multer
npm run dev


create directory public/upload
in src create config,routes,enity folder

inside config\data-ssource.ts

            import "reflect-metadata";
            import { DataSource } from "typeorm";
            import { User } from "../entity/User";

            export const AppDataSource = new DataSource({
            type: "mysql",
            host: "localhost",
            port: 3306,
            username: "root",
            password: "sangram#81",
            database: "myapp",
            synchronize: true, // auto create tables (dev only)
            logging: false,
            entities: [User],
            });

inside config\multer.ts

            import multer from "multer";
            import path from "path";

            // storage config
            const storage = multer.diskStorage({
            destination: function (_, __, cb) {
                cb(null, path.join(__dirname, "../../public/uploads"));
            },
            filename: function (_, file, cb) {
                const uniqueName = Date.now() + "-" + file.originalname;
                cb(null, uniqueName);
            },
            });

            export const upload = multer({
                storage,
                fileFilter: (_, file, cb) => {
                if (file.mimetype.startsWith("image/")) {
                    cb(null, true);
                } else {
                    cb(new Error("Only images allowed"));
                }
                },
            });

inside tsconfig.json

            {
            "compilerOptions": {
                "target": "ES2020",
                "module": "commonjs",
                "rootDir": "src",
                "outDir": "dist",
                "esModuleInterop": true,
                "strict": true,
                "skipLibCheck": true,
                "experimentalDecorators": true,
                "emitDecoratorMetadata": true
            }
            }

inside package.json

            {
            "dependencies": {
                "dotenv": "^17.4.2",
                "express": "^5.2.1",
                "multer": "^2.1.1",
                "mysql2": "^3.22.0",
                "reflect-metadata": "^0.2.2",
                "typeorm": "^0.3.28"
            },
            "devDependencies": {
                "@types/express": "^5.0.6",
                "@types/multer": "^2.1.0",
                "@types/node": "^25.6.0",
                "nodemon": "^3.1.14",
                "ts-node": "^10.9.2",
                "typescript": "^6.0.2"
            },
            "scripts": {
                "dev": "nodemon --watch src --ext ts --exec \"npx ts-node src/main.ts\"",
                "build": "tsc",
                "start": "node dist/main.js"
            }
            }

inside .env

        PORT=3000
        NODE_ENV=development

inside enity/User.ts

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

        @Entity()
        export class User {
        @PrimaryGeneratedColumn()
        id!: number;

        @Column()
        name!: string;

        @Column()
        email!: string;
        }

This should create user table not users.


inside routes\uploadRoutes.ts

        import { Router } from "express";
        import { upload } from "../config/multer";

        const router = Router();

        // single file upload
        router.post("/", upload.single("file"), (req, res) => {
        if (!req.file) {
            return res.status(400).json({ message: "No file uploaded" });
        }

        return res.json({
            message: "File uploaded",
            file: req.file.filename,
            url: `/uploads/${req.file.filename}`,
        });
        });

        export default router;

inside routes/userRotes.ts

        import { Router } from "express";
        import { AppDataSource } from "../config/data-source";
        import { User } from "../entity/User";
        const router = Router();

        router.get("/", (_, res) => {
        res.json([{ id: 1, name: "Sangram" }]);
        });


        router.get("/account", async (req, res) => {
        const userRepo = AppDataSource.getRepository(User);
        const users = await userRepo.find();
        res.json(users);
        });

        export default router;

src\main.ts

        import express from "express";
        import "dotenv/config";

        const PORT = process.env.PORT || 3000;
        import userRoutes from "./routes/userRoutes";
        import path from "path";
        import "reflect-metadata";
        import { AppDataSource } from "./config/data-source";
        import { User } from "./entity/User";

        const app = express();
        import uploadRoutes from "./routes/uploadRoutes";


        app.use(express.json());
        app.use(express.static(path.join(__dirname, "../public")));
        app.use("/uploads", express.static(path.join(__dirname, "../public/uploads")));

        app.use("/upload", uploadRoutes);
        app.use("/users", userRoutes);

        AppDataSource.initialize()
        .then(() => {
            console.log("DB connected");

            const userRepo = AppDataSource.getRepository(User);

            app.get("/", (_, res) => {
            res.send("API is running 🚀");
            });

            app.get("/account", async (_, res) => {
            const users = await userRepo.find();
            res.json(users);
            });

            app.post("/account", async (req, res) => {
            const user = userRepo.create(req.body);
            const result = await userRepo.save(user);
            res.json(result);
            });

     to compile project from typesscript to javascript run

        npx tsc
then run
        npm start

            app.listen(3000, () => {
            console.log("Server running on http://localhost:3000");
            });
        })
        .catch((err) => console.log("DB error:", err));


to run  project
        npm run dev

Here slight changes are made to use clustering.