2024 javascript Interview Question

  • Answer: Javascript is mainly used in browser for webpage interaction.so it is called as client side language.but now-a-days nodejs will be used for running javascript in server.
  • Answer: To get the data from server we need rest API and should be integrated in JavaScript using fetch method.below example
    fetch("url")
  • Answer: to get the data from server we need to use get method. For sending the data to server post method will be implemented. In get method params will be in the URL .In post method data will be separate from the URL which is called as the request body.
  • Answer: both the storage is used in browser . LocalStorage is like a permanent storage until user uninstall the browser or manually clearing the data.Session storage will delete the data when user closes the browser or tab
  • Answer:
    To show some message we have to use alert
     to get the confirm from the user we can use confirm
     to get the input from the popup be can use prompt
  • Answer: to store the multiple data we can use array.below Syntax is example for array
    var name=['one','two','three']
  • Answer: Es6 To filter the array with specific condition we can use this filter method. below example will filter the array by value starts with 'a'.
    arrayVariable.filter((obj)=>obj.startsWith('a'))
  • Answer:
    To handle the promise we have to use  async/await.
    Ex:
     async function getData(){
            let response = await samplePromise();
    }
    
  • Answer: JSON stands for Javascript Object Notation . simple to read, Easy to transfer. all the programming languages has the library to parse the Json
  • Answer: Index array just stores the data in the index position\n object array stores data in key value pair. key should be unique. if key is duplicate,then value will be override
    var name = []
    var detail = {"name":"test","mobile":"45454" }
    
  • Answer: Using push method we can store the data\notherwise directly mention the position and add the data
    arrayVariable.push("value")
  • Answer: var,let,const are used for declaring the variables but however all this things has difference. Using Var can declare the variable & update the variable ,redeclared the variable can be done. It's a global scope let is the keyword to declare the variable but redeclaration cannot be possible and it is the block scope .If it’s declared in the block cannot be accessible outside of the block. Const is also declare the variable.but it can’t be update or redeclare.
  • Answer: Using date object we can get the current date . example below syntax Var d = new Date();
  • Answer:
        var d = new Date();
            d.setDate(18);
            d.setFullYear(1947);
            d.setMonth(0);
            console.log(d);//18-Jan-1947
  • Answer:
    using regex can validate email like below.
    function ValidateEmail(mail) {
    
      var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    
    return mail.match(validRegex));
    }
    
  • Answer: yes. we can create OOPS classes in JavaScript. Inheritance, Object creation ,constructor are available in js.
    class Sample{  
    name;
    age;
    }
  • Answer: So when we want inherit the properties from another class we can use inheritance.In order to achieve inheritance use extends keyword. example below syntax:
    class Sample{  
    name;
    age;
    }
    class Detail extends Sample{  
    
    }
    var d  = new Detail();
    d.name = "value";
    //above variable access from parent class using child object.
    
    
  • Answer: literals are backtick (`) characters, allowing for several line strings, data binding
    const email ="test@gmail.com";
    console.log(`Hello ${email}!`); // Hello test@gmail.com!
  • Answer:
    const details = { 
        "name": "sample",
        "address": "Sample address",
        "age": 23
    }
    const { name } = details;
    console.log(name); // Output, sample
    
  • Answer: Using parseInt() can convert string to number. if the string is not number it will give Nan.
  • Answer:
    isNaN(str) method will return boolean. if str
    var str = 45;
    isNaN(str)//false
    
    var str ="tewt";
    isNaN(str)//true
    
  • Answer:
    name=()=>{  
    }
    name()//calling
    
  • Answer:
    Using 2 ways we can add or remove.
    type1:
    document.getElementById(“sel_id”).classList.add('clsName')
    document.getElementById(“sel_id”).classList.remove('clsName')
    
    type2:
    document.getElementById(“sel_id”).classList.toggle('clsName')
    
  • Answer:
    isNaN(str) method will return boolean. if str
    var str = 45;
    isNaN(str)//false
    
    var str ="tewt";
    isNaN(str)//true
    
  • Answer: let obj = new Sample();
  • Answer: document.getElementById(“btn_id”).addEventListener("click",()=>{ console.log(“sample”); })
  • Answer:
    document.getElementById(“sel_id”).addEventListener("change",(e)=>{ 
    console.log(e.target.value); 
    })
  • Answer: document.getElementById(“id”).value;
  • Answer: document.getElementById(“id”).style.color=”#fff”;
  • Answer: getelementbyID gets the element by id. Queryselector gets the element by classname,id,tagname or selector
  • Answer:
    A callback  function is passed as an argument to another function.
    and can execute after certain task.
    Example
    setTimeout(()=>{
    console.log("im callback")
    },100)
                        
  • Answer:
    whenever we are calling a promise,it can return success,failure which is resolve,reject
     Example:
    new Promise(function(resolve, reject) {
      resolve("I am surely going to get resolved!");//if success
      reject(new Error('Will this be ignored?'));//if error
    });
  • Answer: Using try & catch Catch method can be chained with then.
  • Answer: let p_tag = document.createElement("p"); document.getElementById("msg_list").appendChild(p_tag);
  • Answer: document.getElementById(“h1_id”).innerHTML =”sample text”;
  • Answer: JavaScript is the front and language. so it cannot directly connect with database but using rest API we can integrate or we have to use NODEJS and deploy the app in server.then it can able to connect to the database.
  • Answer: Request body is in post method. query parameter can be passed in post & get method
  • Answer: request header is also pass in http record in the header. example we can pass user ID token permissions.
  • Answer: Cookies client style data storage so the value of the cookie can be accessible by browser or the appropriate server.
  • Answer: Sar whenever we are hitting the server server will send the response with the status code. each status code will have its own description example below.
  • Answer: try{ }catch(e){ }
  • Answer: class SampleError extends Error { constructor(msg) { super(msg); } } if(test == undefined){ throw new SampleError("variable is undefined"); }
  • Answer:
    file1.js
    function test(){
        console.log("sample test log");
    }
    export  {test}
    
    file2.js
    import { test } from "./api2.js";
    
    class Api{
    
        async  getData(){
            let response = await fetch("https://reqres.in/api/users?page=2",{method:"GET"})
            let jsonData = await response.json();//extract the json data from server's response
            console.log(jsonData);
        }
    }
    In html file like below need to
    
  • Answer: When we create object for the classes constructor will be called.No need to call explicitly.we can pass parameters also.
  • Answer:
    setInterval() method will execute a callback function for each interval after the specified time.
    setInterval(()=>{
    console.log("executed")
    },1000)
    
  • Answer:
    setTimeout() method will execute a callback function after the specified time.
    it executes only once  .
    setTimeOut(()=>{
    console.log("executed")
    },1000)
    
    
  • Answer:
    To store collection of unique values we can go for set.
    Ex: 
    const letters = new Set();
    // Add Values to the Set
    letters.add("a");
    letters.add("b");
    letters.add("c");
    
     To store key value pair can implement map 
    Ex;
    const fruits = new Map([
      ["apples", 500],
      ["bananas", 300],
      ["oranges", 200]
    ]);
    
  • Answer: toUpperCase() toLowerCase() concat() trim() length
  • Answer: yes..by using nodejs compiler we can use javascript in server
  • Answer:
    javascript itself will not demand any ide.but below are popular ide in the market
    1.Visual Studio Code.
    2.sublime
    3.atom
    4.intellij
    5.notepad++
    

Questions prepared by SriPraveen

Connect with him

Instagram Youtube Linkedin