JavaScript interview questions for freshers

JavaScript is client side programming language used for all type of web application development, and there are many different JavaScript frameworks, here are some of commonly asked JavaScript Interview Questions and answers for Beginners.

javascript Interview Questions Answers

Advanced Javascript Interview Questions

  1. What is JavaScript?
    JavaScript is a client-side Programming language, but also can be used as server side scripting language, JavaScript can be used with all web development technologies like java, asp.net, php, python etc. JavaScript can post data to serve side and external API. JavaScript is an open source and cross-platform scripting language.
  2. What are the different Data Types in JavaScript?
    • String
    • Number
    • Boolean
    • Undefined
    • Null
    • Object
  3. What is 'this' keyword in JavaScript?
    'this' keyword refers the current object from where it was being called.
  4. What is the use of isNaN function?
    isNan function returns boolean value true if the argument is not a number otherwise it is false.
  5. How to comment any code in Javascript?
    Single line comment example
    // for Single line comment
    Multi line comment example
    /* Multi 
    line 
    comments */
  6. What are the different types of loops in JavaScript?
    • For loop
    • While loop
    • do-while loop
    Learn more about loop in javascript with examples
  7. Can we access JavaScript function written in a different file? If yes then how?
    Yes, we can add access JavaScript function written in a different file by adding the file reference.
    <script src="~/Scripts/jquery.validate.js"></script>
    
  8. Is JavaScript a case-sensitive language?
    Yes, JavaScript is a case sensitive scripting language. So when we define any variable (like var k;), while accessing we have to use the same case, otherwise it will be considered as a different variable
        var k;
        var K; // different ;
    
  9. Which company developed JavaScript?
    Netscape, a software company who developed JavaScript.
  10. What is the difference between "not defined" and "undefined" in JavaScript?
    When we try to use any variable that has not been declared or doesn't exist then JavaScript will throw an error var name is not defined.
    var a; // declaring x
    console.log(a); //output: undefined 
    

    Now if we try to user some variable that has not been declared before

    var a; // Declaration
    console.log(b);  // Output: ReferenceError: b is not defined
    
  11. How to create an object in JavaScript?
    There are many different ways we can create object in JavaScript, here is a common example
    var Employee = function (name, org, salary) {
        this.name = name || "";  //attribute default value is null
        this.organization = org || ""; 
        this.salary = salary || 5000; 
    }
    var emp1 = new Employee("Bill","Microsoft",3000);
    var emp2 = new Employee("Whitney","IBM",5000);
    
  12. How to declare an array with some default values in JavaScript?
    Usually we always declare any array with some values assigned in it, here is how we can do
    var colors =  ['red','blue','orange','while','black','green'];
    
    Learn more about JavaScript Array with example
  13. How to define anonymous function in JavaScript
    This type of function has no name, anonymous can be easily declared in like an expression, starts with function keyword.
    <script> 
    var helloWorld = function () {
        alert("Anonymous function invoked");
    }
    helloWorld();
    </script> 
    
    Learn more about JavaScript Function with example
  14. How to set line break to a string in JavaScript code?
    We can add line break in a string statement using a backslash '\n' , at the end of each line.
    console.log("Hello World! \n I am ready for next day!");
    // OR 
    document.write("Hello Friend! \n How are you doing?");
    

    In above statement line will be broken to next line wherever \n found, Make sure code is within script tag.

  15. How to write async function in javascript?

    We can write async function in javascript using async keyword.

    let checkUser = async function(username, password){
    try {
    //let result = setTimeout(() => console.log("Tick"), 500);
            console.log("Welcome "+ username);
            throw new Error("some error message");
            //return result;
        }
        catch (ex)
        {
            console.log(ex)
        }
     };
    
  16. How to call a async function with await keyword in JavaScript?

    Look at the example below, where I am calling the above async function from below async function using await keyword.

    Notice, the line let result= await checkUser("u1","p1");
    async function myAsyncMethod() {
        try {
           let result= await checkUser("u1","p1");
           console.log(result);
        } catch (e) {
            console.error(e);
        } finally {
            console.log('we reached finally block');
        }
    }
    

    Learn more about JavaScript Async Function with example

  17. What is the difference among equal sign single = , double == and triple ===?

    Single = is used for assigning value, right to left
    Double == is for comparing the value
    Triple === is for comparing value with type

    Here are some examples.
    if (2=="2")
    {
        console.log("2=='2' is true");
    }
    if (2==="2")
    {
        console.log("2==='2' is true");
    }
    else 
    {
        console.log("2==='2' is false");
    }
    var bar = null;
    console.log(typeof bar === "object");
    
  18. How to write foreach to loop through array in JavaScript ?
    Here is an example of foreach in array
    var subjectArray = ["JavaScript", "JSON", "Asp.Net Core", "PHP"];
    subjectArray.forEach(fetch); 
    function fetch(item, index) {
        console.log(index + ":" + item );
      } 
    

    We also can write like example below.

    subjectArray.forEach(function (fetch) {
        console.log(fetch);
    });
    
  19. How to define an array variable in JavaScript with different type of data?

    In following student variable, we can store different type of data like name (string), age (integer) etc.

    var student= {name:"Arayan Bose",age:29, batch:"XII"};
    console.log(student.name);
    
  20. What is cookie in JavaScript? How to us cookie in JavaScript?

    Cookie is the small piece of data in plain text, each cookie contain data in name-value pair.

    In JavaScript we can access cookie object through document.cookie.

    To retrive all cookies, we can write code using document.cookie like below.

    var _cookies = document.cookie;
    document.write("All Cookies : " + _cookies);
    //To split all cookies pairs in an array.
    cookiearray = _cookies.split(';');
    

    document.cookie.length will get you the length of cookies.

    Write following code to create cookie in JavaScript.

    var _siteTitle = "Learn JavaScript Free";
    var _cookieValue = escape(_siteTitle) + ";";
    document.cookie = "title=" + _cookieValue;
    var _cookies = document.cookie;
    document.write("All Cookies : " + _cookies);
    
  21. How to change text of html button using JavaScript?

    To change any property of any html element we can access the html element either by id or by name, here in example we change the button property value accessing by id.

    Notice, the button text will become "Click Me" to "Have Fun".

    <input type="button" id="btnSave" value="Click Me!" onclick="ChangeText();" />
    <script type="text/javascript">
    	function ChangeText()
    	{
    		var btn = document.getElementById("btnSave")
    		btn.value = "Have Fun!";
    	}            
    </script>
    
  22. How we can submit any form using JavaScript?
    We can use submit method for any form submission dynamically using JavaScript, like document.form[0].submit();
    document.form[0].submit();
    

    Instead of index value, we also can use the form id to submit form-using JavaScript. like $("#frm1").submit();

  23. What are the different types of Pop up boxes available in JavaScript?
    There are three built-in methods
    • Alert
    • Confirm
    • Prompt
  24. What are escape characters in JavaScript?
    Escape characters (Backslash) like \, is used when working with special characters like single quotes, double quotes, apostrophes and ampersands, we place \ backslash before the character to make it display.
  25. What is regular expression in JavaScript, how to define regular expression?

    JavaScript Regular expressions is a powerful way of doing search and replace in any strings, a regular expression describes a pattern of characters.

    Learn more about Regular Expresssion in Javascript.
  26. How to calculate exponent using JavaScript?
    We can calculate exponentiation using JavaScript inbuilt pow function like Math.pow(x, y)

    There are many built-in math functions in javascript, pow is one of them.

  27. What is promise in JavaScript?
    JavaScript Promise is the new features of advanced JavaScript (ES6), specially used when you want to write async JavaScript function in Node application development, here is an example of how we can define Promise in javascript.
    const wait = time => new Promise((resolve) => setTimeout(resolve, time));
    wait(5000).then(() => console.log('Hello World!')); 
    
    Learn more about javascript promises example
  28. How to calculate date using javascript ?
    We can calculate date using JavaScript built-in date object. like var d = new Date(), example code will get the current date of the system.
    <script>
    var d = new Date();
    document.write("Date is" + d.getDate());<br />
    </script>
    // date result here

    We find date, time, seconds, month, year using the same date object in javascript, learn more about JavaScript Date function with examples.

  29. What is ES6 ?

    ES6 or ECMAScript is the advanced version of javascript, now we can do more object oriented javascript programming in ES6, which was not possible with earlier javascript version.

    We can do stuff like import, export, define class, inheritance, arrow function etc. Learn more about ES6 features

  30. How to define class in javascript with constructor?
    In ES6, we can define JavaScript class with class keyword, we also can define constructor Using same constructor keyword, take a look at following javscript class example.
    class Car {
    constructor(modelName) {
    this.modelName = modelName;
    }
    checkOil() {
    console.log(this.modelName + ' is Checking Oil');
        }
    }

    You can check more about Object oriented programming in JavaScript at JavaScript class oops example in ES6.

Advanced JavaScript Interview Questions for experienced

JavaScript has been evolved and more advanced than before, There are many JavaScript frameworks for developing modern efficient web application, so as an experienced JavaScript developer, one must know some of the latest JavaScript trends and framework, here are some interesting JavaScript questions that may help you to get ready for interview.

  1. Which are the latest JavaScript frameworks are most popular ?
    The most popular JavaScript frameworks are Node JS, JQuery, TypeScript, Angular, React, Vue, Ember, Backbone, Polymer etc.
  2. How to read and write file using JavaScript code?
    We can manage file and folder using JavaScript in node js, there is module for handling file system in JavaScript.
    var fs = require('fs');
    var localDir = './staticfiles1';
    if (!fs.existsSync(localDir)){
        fs.mkdirSync(localDir);
        console.log("new directory has been created");
    }
    

    Here is an example of how you can work with file system in javascript Node JS application.

  3. Can we connect sql database using JavaScript?
    Yes, now we can develop database driven application in JavaScript, Node JS framework provide us all libraries to connect any RDBMS from JavaScript application, and insert, update data from JavaScript code.
    var con = mysql.createConnection({
      host: "localhost",
      user: "username",
      password: "password",  
      database: "mydatabaseName",
      port:"0001",
      multipleStatements: true
    });
    

    Here is an example of how to work with MySql database in NodeJs application.

  4. How to make ajax call from JavaScript?
    JavaScript JQuery framework provide ready to use libraries for making ajax call in JavaScript, where we can post JSON object from client side to server side using JavaScript code.
    <script>
    $(document).ready(function(){
        $("#btnInfo").click(function(){
            $.ajax(
            {
                url: "page-or-view-name",
                data: JSON.stringify(model_data),
                type:"post",
                dataType: "json",
                success: function(result){
                    $("#div1").html(result);
                        }
            });
        });
    });
    </script>
    

    Here is an JQuery Ajax Post Example

You should also read the following post
 
Javascript Interview Questions
talentshunt job portal
Online Courses
Learn JavaScript
JavaScript Course Online, Check FREE JavaScript Tutorial
javascript course online
free javascript tutorial online
Interview Question Answers | Fresher Job Interview Tips