Olibr Blogs

Blog > All Engineering Topics > what is backend development

JavaScript Interview Questions for Beginners

JavaScript Interview Questions for Freshers

by Snehal Naik
JavaScript Interview Questions for Beginners

Table of Contents

Pointer image icon

Introduction

Gearing up for your first JavaScript interview? We’ve got you covered! From knowing the difference between Java and JavaScript to answering questions on data types and JavaScript functions, this blog contains the top JavaScript interview questions for freshers.

Pointer image icon

JavaScript Interview Questions for Beginners

1. What are the differences between Java and JavaScript?

Aspect Java JavaScript
Type Statically typed (compiled) Dynamically typed (interpreted)
Platform Runs on a virtual machine or browser Runs only in browsers
Syntax Class-based Prototype-based
Compilation Requires compilation All code is in text (interpreted)
Purpose General-purpose language Primarily used for web interactivity
OOP Strongly object-oriented Object-oriented scripting
Features Abstraction, encapsulation, inheritance, polymorphism DOM manipulation, event handling, AJAX
Memory Management Explicit memory allocation Automatic garbage collection
Security Strongly typed, secure Less secure due to dynamic nature

2. What are JavaScript Data Types?

Data types can be divided into primitive and non-primitive types. Primitive data types are further divided into: 

String: Represents text and is enclosed in quotes (single or double). 

var str = "Vivek Singh Bisht"; //using double quotes  
var str2 = 'John Doe'; //using single quotes 

Number: Stores decimal numbers (floating point) and can include or exclude decimals. 

var x = 3; //without decimal  
var y = 3.6; //with decimal 

Bigint: Used for large integers. 

var bigInteger = 234567890123456789012345678901234567890; 

Boolean: Represents true or false values.

var a = 2; 
var b = 3;  
var c = 2; 
 (a == b) // returns false  
(a == c) //returns true 

Undefined: Indicates a variable that has been declared but not assigned a value. 

var x; // value of x is undefined  
var y = undefined; // we can also set the value of a variable as undefined 

Null: Represents the absence of any value. 

var z = null; 

Symbol: Used for unique identifiers (introduced in ECMAScript 6). 

var symbol1 = Symbol('symbol');

Non-primitive data types are used to store multiple and complex values. Object data type is used to store the collection of non-primitive data.

3. Which symbol is used for comments in JavaScript?

In JavaScript, the double forward slash (//) is used for single-line comments. Anything after // on the same line is considered a comment and is ignored by the interpreter. For multi-line comments, you can use /* to start the comment block and */ to end it. 

best software companies

Don't miss out on your chance to work with the best

Apply for top global job opportunities today!

4. What would be the result of 3+2+”7″?

3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2 will be 5. Then the output will be 5+”7″ = 57. 

5. What is the use of the isNaN function?

The isNaN() function in JavaScript is used to determine whether a value is Not-a-Number (NaN). Here’s how it works: 

  • When you pass a value to isNaN(), it checks if the value can be converted to a valid number. 
  • If the value cannot be converted to a number (e.g., a string containing non-numeric characters), isNaN()returns true. 
  • If the value can be converted to a number (e.g., a valid numeric string or an actual number), isNaN()returns false.

Example

console.log(isNaN("hello")); // true (because "hello" cannot be converted to a number) 
console.log(isNaN("123"));   // false (because "123" can be converted to a number) 
console.log(isNaN(42));      // false (because 42 is a valid number) 

6. Which is faster in JavaScript and ASP script?

Typically, JavaScript is faster for client-side tasks since it avoids the round-trip to the server. However, ASP can be faster for server-side processing because it leverages the server’s resources and can work directly with server-side databases and file systems. 

7. What is negative infinity?

Negative Infinity in JavaScript is a special numeric value that is less than any other number. It is obtained by dividing a negative number by zero or subtracting infinity from a positive number. It is represented as –Infinity. 

console.log(-Infinity < -1000); // true 
console.log(-1 / 0); // -Infinity 

8. Is it possible to break JavaScript Code into several lines?

You can use the backslash ‘\’ to break the JavaScript code into several lines in a string statement.

For example: 

document.write("A Online Knowledge Base\ for Developers") 

The code-breaking line is avoided by JavaScript which is not preferable. 

let gfg= 10, GFG = 5, 
Developers= 
gfg + GFG; 

9. What are undeclared and undefined variables?

Undeclared: A variable that has not been declared using varlet, or const. Accessing an undeclared variable results in an error. 

Undefined: A variable that has been declared but not assigned a value. It holds the special value undefined. 

10. Write a JavaScript code for adding new elements dynamically.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Document</title> 
</head> 
<body> 
    <button onclick="create()"> 
        Click Here! 
    </button> 
  
    <script> 
        function create() { 
            let geeks = document.createElement('Developers');
           Developers.textContent = "Jobsfordevelopers"; 
           developers.setAttribute('class', 'note'); 
            document.body.appendChild(developers); 
        } 
    </script> 
</body> 
</html> 

11. What are global variables? How are these variables declared, and what are the problems associated with them?

Global variables are the variables that have global scope. They define outside of functions and can be used by any function without passing them to the function as parameters. 

Example: 

let petName = "Rocky"; //Global Variable 
myFunction(); 
function myFunction() { 
    document.getElementById("geeks").innerHTML 
        = typeof petName + "- " + 
        "My pet name is " + petName; 
} 

document.getElementById("Geeks") 
    .innerHTML = typeof petName + "- " + 
    "My pet name is " + petName; 

Problems 

Pollution: Global variables can lead to naming conflicts and unintended side effects. 

Security: Sensitive data stored globally can be accessed by any part of the code. 

Maintainability: Debugging and understanding code with many globals can be challenging. 

12. What do you mean by NULL in JavaScript?

The NULL value represents that no value or no object. It is known as empty value/object. In JavaScript, null is a special value that represents the intentional absence of any object value. It is one of JavaScript’s primitive data types, alongside undefined, boolean, number, string, and symbol. 

13. How to delete property-specific values?

The delete keyword deletes the whole property and all the values at once: 

let gfg={Course: "DSA", Duration:30}; 
delete gfg.Course; 

14. What is a prompt box?

A prompt box in JavaScript is a type of pop-up dialog box that allows the user to input a value before proceeding. When a prompt box pops up, the user can enter a value, and then click “OK” to submit the value or “Cancel” to dismiss the box. The prompt() function is used to display a prompt box. 

15. What is the ‘this’ keyword in JavaScript?

The this keyword in JavaScript refers to the object it belongs to. Its value depends on where it is used: 

  • In a method: this refers to the owner object. 
  • Alone: this refers to the global object (window in a browser). 
  • In a function: this refers to the global object (in non-strict mode) or undefined (in strict mode). 
  • In an event: this refers to the element that received the event. 
  • With call(), apply(), and bind(): this can be explicitly set to a specific value. 

Example 

var person = { 
    firstName: "John", 
    lastName: "Doe", 
    fullName: function() { 
        return this.firstName + " " + this.lastName; 
    } 
}; 
console.log(person.fullName()); // John Doe 

16. How do timers work in JavaScript? Are there any drawbacks to using the timer?

Timers in JavaScript are used to execute a function or code snippet after a certain period of time. The two primary functions for timers are setTimeout() and setInterval(). 

Drawbacks 

  • Accuracy: Timers are not always precise. The execution time might be delayed due to other tasks being processed in the event loop. 
  • Resource Intensive: Excessive use of timers can lead to performance issues, as they keep the JavaScript engine active. 
  • Unpredictable Execution: If multiple timers are set, their execution order is not guaranteed, which can lead to unpredictable behavior in your application. 

17. What is the difference between ViewState and SessionState?

ViewState and SessionState are mechanisms used in ASP.NET to maintain state information between HTTP requests. 

ViewState 

  • Scope: Maintains state information for a single page across postbacks. 
  • Storage: Stored in a hidden field on the page. 
  • Lifetime: Exists for the duration of the page’s life on the client. 
  • Security: Encoded but not encrypted by default, can be tampered with if not properly secured. 
  • Usage: Used to persist form data and control properties. 

SessionState 

  • Scope: Maintains state information across multiple pages for a single user session. 
  • Storage: Stored on the server (in-memory, database, etc.). 
  • Lifetime: Exists for the duration of the user session. 
  • Security: More secure as data is stored on the server. 
  • Usage: Used to store user-specific information like login credentials, user preferences, etc. 

18. How to submit a form using JavaScript?

You can use document.form[0].submit() method to submit the form in JavaScript. 

19. Does JavaScript support automatic type conversion?

Yes, JavaScript supports automatic type conversion, also known as type coercion. JavaScript automatically converts types when performing operations that involve different types. 

Examples: 

String and Number 

var result = "5" + 5; // "55" (string concatenation) 
var result = "5" - 1; // 4 (numeric subtraction) 

Boolean and Number 

var result = true + 1; // 2 (true is converted to 1) 
var result = false + 1; // 1 (false is converted to 0) 

20. Explain Hoisting in JavaScript.

It is the default behavior of JavaScript where all the variable and function declarations are moved on top. Irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global. 

Variable Hoisting 

Only the declarations are hoisted, not the initializations. 

console.log(x); // undefined 
var x = 5; 
console.log(x); // 5 

Function Hoisting 

Function declarations are hoisted entirely. 

Only the declarations are hoisted, not the initializations. 

greet(); // "Hello!" 
function greet() { 
    console.log("Hello!"); 
} 

Function Expressions are not hoisted. 

greet(); // TypeError: greet is not a function 
var greet = function() { 
    console.log("Hello!"); 
} 

21. Why do we use the word “debugger” in JavaScript?

The debugger statement in JavaScript is used to invoke any available debugging functionality, such as setting a breakpoint in the code. When the JavaScript engine encounters the debugger statement, it stops the execution of the code and allows developers to inspect the state of the application at that point, helping them identify and fix bugs. 

Example 

function testDebug() { 
    var x = 10; 
    debugger; // Execution will pause here if debugging tools are open 
    var y = x + 5; 
    console.log(y); 
} 
testDebug(); 

22. What is the difference between “ == “ and “ === “ operators?

Both are comparison operators. “==” is used to compare values. “ === “ is used to compare both values and types. 

Example 

var x = 2; 
var y = "2"; 
(x == y)  // Returns true since the value of both x and y is the same 
(x === y) // Returns false since the typeof x is "number" and typeof y is "string" 

23. Difference between var and let keyword in JavaScript.

var: 

  • Function-scoped: Variables declared with var are scoped to the function in which they are declared. 
  • Hoisting: var declarations are hoisted to the top of their scope but not the assignments. 
  • Can be redeclared: Variables declared with var can be redeclared within the same scope. 

Example 

function varExample() { 
    console.log(x); // undefined (hoisted declaration) 
    var x = 10; 
    var x = 20; // No error 
    console.log(x); // 20 
} 
varExample(); 

let: 

  • Block-scoped: Variables declared with let are scoped to the nearest enclosing block (e.g., within {}). 
  • Hoisting: let declarations are hoisted but not initialized until the definition line is executed. 
  • Cannot be redeclared: Variables declared with let cannot be redeclared within the same scope. 

Example 

function letExample() { 
    console.log(y); // ReferenceError: y is not defined 
    let y = 10; 
    // let y = 20; // SyntaxError: Identifier 'y' has already been declared 
    console.log(y); // 10 
} 
letExample(); 

24. Explain Implicit Type Coercion in JavaScript.

Implicit type coercion in JavaScript is the automatic conversion of values from one data type to another when performing operations involving different types. 

Example: 

String and Number

console.log("5" + 2); // "52" (number 2 is coerced to string "2") 
console.log("5" - 2); // 3 (string "5" is coerced to number 5)  

Boolean and Number 

console.log(true + 1); // 2 (true is coerced to number 1) 
console.log(false + 1); // 1 (false is coerced to number 0) 

25. Explain passed by value and passed by reference.

Primitive data types are passed by value and non-primitive data types are passed by reference in JavaScript.  

Passed by Value: The actual value is passed. In JavaScript, primitive data types (numbers, strings, booleans, null, undefined, symbol, and bigint) are passed by value. Changing the value of the argument inside the function does not affect the original value. 

function modifyValue(x) { 
    x = x + 1; 
} 
let a = 5; 
modifyValue(a); 
console.log(a); // 5 

Passed by Reference: The reference (address) to the actual data is passed. In JavaScript, objects (including arrays and functions) are passed by reference. Changing the value of the property inside the function affects the original object. 

Example

function modifyObject(obj) { 
    obj.name = "New Name"; 
} 
let person = { name: "John" };
modifyObject(person); 
console.log(person.name); // "New Name" 

26. What is an Immediately Invoked Function in JavaScript?

An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed immediately after its creation. IIFEs are often used to create a local scope to avoid polluting the global namespace. 

Syntax 

(function() { 
    // Code here runs immediately and has its own scope 
    console.log("IIFE executed"); 
})(); 

Example 

(function() { 
    var x = 10; 
    console.log(x); // 10 
})(); 
console.log(typeof x); // "undefined" (x is not in the global scope) 

27. What do you mean by strict mode in JavaScript and characteristics of JavaScript strict-mode?

Strict mode in JavaScript is a way to opt in to a restricted variant of JavaScript, which can help catch common coding mistakes and “unsafe” actions such as defining global variables unintentionally. It can be enabled by adding “use strict”; at the beginning of a script or function. 

Characteristics 

  • Prevents the use of undeclared variables. 
  • Disallows duplicate parameter names in functions. 
  • Eliminates this coercion to the global object. 
  • Throws errors for assignments to non-writable properties. 
  • Disallows with statements. 

28. Explain Higher Order Functions in JavaScript.

Higher-order functions are functions that can take other functions as arguments and/or return functions as their result. They are a fundamental concept in functional programming. 

Example 

function higherOrder(fn) { 
  fn(); 
} 
higherOrder(function() { console.log("Hello world") });    
function higherOrder2() { 
  return function() { 
    return "Do something"; 
  } 
}       
var x = higherOrder2(); 
x()   // Returns "Do something"  

29. What do you mean by Self Invoking Functions?

A self-invoking expression is automatically invoked (initiated) without being requested. If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself. 

(function() { 
    console.log("This is a self-invoking function"); 
})(); 

30. Explain call(), apply() and, bind() methods.

call(): Invokes a function with a specified this value and arguments provided individually. 

function greet(greeting) { 
    console.log(greeting + ", " + this.name); 
} 
const person = { name: "John" }; 
greet.call(person, "Hello"); // "Hello, John" 

apply(): Invokes a function with a specified this value and arguments provided as an array. 

greet.apply(person, ["Hi"]); // "Hi, John" 

bind(): Creates a new function that, when called, has its this value set to the provided value. 

const greetJohn = greet.bind(person); 
greetJohn("Hey"); // "Hey, John" 

31. What is the difference between exec () and test () methods in JavaScript?

The test () and exec () are RegExp expression methods used in JavaScript.  

exec(): Executes a search for a match in a specified string and returns a result array or null. 

const regex = /hello/; 
const result = regex.exec("hello world"); 
console.log(result); // ["hello"]

test(): Tests for a match in a specified string and returns true or false. 

const testResult = regex.test("hello world"); 
console.log(testResult); // true 

32. What is currying in JavaScript?

Currying is a technique in functional programming where a function is transformed into a sequence of functions, each with a single argument. It allows partial application of a function’s arguments. 

function add(a) { 
    return function(b) { 
        return a + b; 
    }; 
} 
const addFive = add(5); 
console.log(addFive(10)); // 15 

33. What are some advantages of using External JavaScript?

  • Separation of Concerns: Keeps HTML and JavaScript code separate, making the code easier to maintain. 
  • Caching: Browsers can cache external JavaScript files, leading to faster load times for returning visitors. 
  • Reusability: External scripts can be reused across multiple pages or projects. 
  • Collaboration: Easier for multiple developers to work on different parts of a project simultaneously. 

34. Explain Scope and Scope Chain in JavaScript.

Scope: The context in which variables and functions are accessible. JavaScript has function scope and block scope. There are three types of scopes in JavaScript: 

  • Global Scope 
  • Local or Function Scope 
  • Block Scope 

Scope Chain: Refers to the hierarchy of scopes. When a variable is accessed, JavaScript first looks in the current scope, then in the outer scope, and so on, until it reaches the global scope. 

function outer() { 
    let a = 10; 
    function inner() { 
        let b = 20; 
        console.log(a); // 10 (from outer scope)
    } 
    inner(); 
    console.log(b); // ReferenceError: b is not defined 
} 
outer();

35. Explain Closures in JavaScript.

A closure is a function that has access to its own scope, the scope of the outer function, and the global scope. Closures allow functions to retain access to variables from an outer function even after that function has finished executing. 

function makeCounter() { 
    let count = 0; 
    return function() { 
        count++; 
        return count; 
    }; 
} 
const counter = makeCounter(); 
console.log(counter()); // 1 
console.log(counter()); // 2 

36. Mention some advantages of JavaScript.

  • Client-Side Execution: Reduces server load and provides faster interaction by executing in the user’s browser. 
  • Rich Interfaces: Enables the creation of interactive and dynamic web pages with features like drag-and-drop and animations. 
  • Versatility: Can be used for front-end and back-end development (e.g., with Node.js). 
  • Wide Adoption: Supported by all modern browsers and has a vast ecosystem of libraries and frameworks. 

37. What are object prototypes?

Prototypes are a mechanism by which JavaScript objects inherit properties and methods from other objects. Each object has a __proto__ property, which points to its prototype. 

  • Date objects inherit properties from the Date prototype 
  • Math objects inherit properties from the Math prototype 
  • Array objects inherit properties from the Array prototype. 
  • On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype. 

38. What are callbacks?

A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some action. 

function divideByHalf(sum){ 
  console.log(Math.floor(sum / 2)); 
} 

function multiplyBy2(sum){ 
  console.log(sum * 2); 
} 

function operationOnSum(num1,num2,operation){ 
  var sum = num1 + num2; 
  operation(sum); 
} 

operationOnSum(3, 3, divideByHalf); // Outputs 3 

operationOnSum(5, 5, multiplyBy2); // Outputs 20 

39. What are the types of errors in JavaScript?

  • Syntax Errors: Mistakes in the code syntax. 
  • Reference Errors: Referring to a variable that is not declared. 
  • Type Errors: Using a value in an inappropriate way. 
  • Range Errors: A value not in the set or range of allowable values. 

40. What is memoization?

Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. 

function memoize(fn) { 
    const cache = {}; 
    return function(...args) {
        const key = JSON.stringify(args); 
        if (cache[key]) { 
            return cache[key];
        } 
        const result = fn(...args); 
        cache[key] = result; 
        return result; 
    }; 
} 
const factorial = memoize(function(n) { 
    if (n <= 1) return 1; 
    return n * factorial(n - 1); 
}); 
console.log(factorial(5)); // 120 
console.log(factorial(5)); // 120 (cached) 

41. What is recursion in a programming language?

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. A recursive function must have a base case to terminate the recursive calls. 

The following function calculates the sum of all the elements in an array by using recursion: 

function computeSum(arr){ 
  if(arr.length === 1){ 
    return arr[0]; 
  } 
  else{ 
    return arr.pop() + computeSum(arr); 
  } 
} 
computeSum([7, 8, 9, 99]); // Returns 123 

42. What is the use of a constructor function in JavaScript?

Constructor functions are used to create objects and set their properties and methods. They are a blueprint for creating multiple instances of an object type. 

function Person(name, age) { 
    this.name = name; 
    this.age = age; 
} 
const person1 = new Person("John", 30); 
console.log(person1.name); // "John" 

43. What is DOM?

DOM stands for Document Object Model.  DOM is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects. JavaScript can interact with and manipulate the DOM to dynamically change the content, structure, and style of a web page. 

Example of how HTML code gets converted to DOM: 

document.getElementById("myElement").innerHTML = "Hello World"; 

44. Which method is used to retrieve a character from a certain index?

The charAt() method retrieves the character at a specified index in a string. 

const str = "Hello"; 
console.log(str.charAt(1)); // "e" 

45. What do you mean by BOM?

The Browser Object Model (BOM) provides interaction with the browser itself. It includes objects like window, navigator, screen, location, and history. 

console.log(window.innerWidth); // Width of the browser window 
console.log(navigator.userAgent); // Information about the browser 

46. What is the distinction between client-side and server-side JavaScript?

Client-Side JavaScript 

  • Runs in the user’s browser. 
  • Manipulates the DOM, handles user interactions, and performs client-side validations. 
  • Example: Adding event listeners to buttons. 

Example

document.getElementById("myButton").addEventListener("click", function() { 
    alert("Button clicked!"); 
}); 

Server-Side JavaScript 

  • Runs on a server. 
  • Handles server-side logic, such as database interactions and serving web pages. 
  • Example: Using Node.js to build a backend server. 

Example 

const http = require('http'); 

const server = http.createServer((req, res) => { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    res.end('Hello World\n'); 
}); 
server.listen(3000, () => { 
    console.log('Server running at http://localhost:3000/'); 
}); 
Pointer image icon

Conclusion

As a beginner, it might get overwhelming for you to go through all the material that is available to prepare for your JavaScript interview. This blog makes interview preparation easy with a curated list of JavaScript interview questions for beginners. However, remember to practice coding questions regularly and stay connected with the JavaScript community to stay updated with the latest updates and trends. To find JavaScript developer job opportunities that match your skills set, sign up with Olibr now!  

Take control of your career and land your dream job

Sign up with us now and start applying for the best opportunities!

FAQs

By default, JavaScript is synchronous. This means that code is executed line by line, and each operation must complete before the next one starts. This can lead to blocking behavior if a particular operation takes a long time to complete. JavaScript can also operate asynchronously, allowing certain operations to be executed without blocking the main thread. This is achieved through mechanisms such as callbacks, promises, and async/await. 

JavaScript is a high-level, dynamic, and interpreted programming language that is widely used in web development. It allows developers to create interactive and dynamic content on web pages. JavaScript is an essential technology of the World Wide Web, alongside HTML and CSS. 

A new array must be defined using empty brackets to declare an array with literal notation. It looks like this: let myArray = []; You will place all elements within the square brackets and separate each item or element with a comma. 

The event loop is a fundamental concept in JavaScript that allows for non-blocking asynchronous operations despite JavaScript being single-threaded. It enables JavaScript to perform tasks such as handling user inputs, making network requests, and other asynchronous operations without blocking the main execution thread. 

You may also like

Leave a Comment