The JavaScript interview questions are divided into three sections:
Let’s begin with the first section.
Beginner Level JavaScript Interview Questions for Freshers
Q1. What is JavaScript?
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.
Q2. What is the difference between Java & JavaScript?
Java | JavaScript |
Java is an OOP programming language. | JavaScript is an OOP scripting language. |
It creates applications that run in a virtual machine or browser. | The code is run on a browser only. |
Java code needs to be compiled. | JavaScript code are all in the form of text. |
Q3. What are the data types supported by JavaScript?
The data types supported by JavaScript are:
String- This data type is used to represent a sequence of characters.
Example:
12 | var str = "Akash Sharma"; //using double quotes var str2 = 'David Matt'; //using single quotes |
Number- This datatype is used to represent numerical values.
Example:
12 | var x = 25; //without decimal var y = 10.6; //with decimal |
Boolean- This datatype is used to represent the boolean values as either true or false.
Example:
12345 | var a = 4; var b = 5; var c = 4; (a == b) // returns false (a == c) //returns true |
Symbol- This datatype is a new primitive data type introduced in JavaScript ES6. Symbols are immutable (they cannot be modified) and one-of-a-kind.
Example:
123456 | // two symbols with the same description const value1 = Symbol('hello'); const value2 = Symbol('hello'); console.log(value1 === value2); // false |
Null- It indicates a value that does not exist or is invalid.
Example:
1 | var a = null; |
Object- It is used to store collection of data.
Example:
12345 | // Object const student = { firstName: 'Arya', Roll number: 02 }; |
Q4. What are the features of JavaScript?
Following are the features of JavaScript:
- It is a lightweight, interpreted programming language.
- It is designed for creating network-centric applications.
- It is complementary to and integrated with Java.
- It is an open and cross-platform scripting language.
Q5. Is JavaScript a case-sensitive language?
Yes, JavaScript is a case sensitive language. The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
Q6. What are the advantages of JavaScript?
Following are the advantages of using JavaScript −
- Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
- Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
- Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
- Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
Q7. How can you create an object in JavaScript?
JavaScript supports Object concept very well. You can create an object using the object literal as follows −
1234 | var emp = { name: "Daniel", age: 23 }; |
Q8. Define anonymous function.
In JavaScript, an anonymous function is a function that does not have a name. It is typically used for short, one-off tasks where naming the function is not essential.
Java Course Online
- Instructor-led Sessions
- Real-life Case Studies
- Assignments
- Lifetime Access
Explore Curriculum
Example:
123 | function(parameters) { // body of the function } |
Q9. How can you create an Array in JavaScript?
You can define arrays using the array literal as follows-
12 | var x = []; var y = [1, 2, 3, 4, 5]; |
Q10. What is a name function in JavaScript & how to define it?
A named function declares a name as soon as it is defined. It can be defined using function keyword as :
123 | function named(){ // write code here } |
Web Development Full Course for Beginners
Q11. Can you assign an anonymous function to a variable and pass it as an argument to another function?
Yes! An anonymous function can be assigned to a variable. It can also be passed as an argument to another function.
Q12. What is argument objects in JavaScript & how to get the type of arguments passed to a function?
JavaScript variable arguments represents the arguments that are passed to a function. Using type of operator, we can get the type of arguments passed to a function. For example −
123456 | function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(7); //==> "number", 1 func("1", "2", "3"); //==> "string", 3 |
Q13. What are the scopes of a variable in JavaScript?
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
• Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Q14. What is the purpose of ‘This’ operator in JavaScript?
In JavaScript, this keyword refers to the object it belongs to. Depending on the context, this might have several meanings. This pertains to the global object in a function and the owner object in a method, respectively.
Q15. What is Callback?
A simple JavaScript function that is sent as an option or parameter to a method is called a callback. The function is called “call back” because it is meant to be invoked after another function has completed running. Functions are objects in JavaScript. This means that other functions can return functions and accept functions as arguments.
Q16. What is Closure? Give an example.
Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.
Q17. Name some of the built-in methods and the values returned by them.
Built-in Method | Values |
CharAt() | It returns the character at the specified index. |
Concat() | It joins two or more strings. |
forEach() | It calls a function for each element in the array. |
indexOf() | It returns the index within the calling String object of the first occurrence of the specified value. |
length() | It returns the length of the string. |
pop() | It removes the last element from an array and returns that element. |
push() | It adds one or more elements to the end of an array and returns the new length of the array. |
reverse() | It reverses the order of the elements of an array. |
Q18. What are the variable naming conventions in JavaScript?
The following rules are to be followed while naming variables in JavaScript:
- You should not use any of the JavaScript reserved keyword as variable name. For example, break or boolean variable names are not valid.
- JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123name is an invalid variable name but _123name or name123 is a valid one.
- JavaScript variable names are case sensitive. For example, Test and test are two different variables.
Q19. How does Type Of Operator work?
The type of operator is used to get the data type of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. It is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
Q20. How to create a cookie using JavaScript?
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
Syntax :
1 | document.cookie = "key1 = value1; key2 = value2; expires = date"; |
Q21. How to read a cookie using JavaScript?
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.
- The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
- You can use strings’ split() function to break the string into key and values.
Q22. How to delete a cookie using JavaScript?
If you want to delete a cookie so that subsequent attempts to read the cookie in JavaScript return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.
Q23. Explain call(), apply() and, bind() methods.
In JavaScript, the `call()`, `apply()`, and `bind()` methods are used to manipulate the execution context and binding of functions. They provide ways to explicitly set the value of `this` within a function and pass arguments to the function.
- `call()`: The `call()` method allows you to invoke a function with a specified `this` value and individual arguments passed in as separate parameters. It takes the context object as the first argument, followed by the function arguments.
“`javascript
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: ‘John’
};
greet.call(person, ‘Alice’);
// Output: Hello, Alice! My name is John.
“`
In this example, `call()` is used to invoke the `greet()` function with the `person` object as the execution context and the argument `’Alice’`.
- `apply()`: The `apply()` method is similar to `call()`, but it accepts arguments as an array or an array-like object. It also allows you to set the `this` value explicitly.
“`javascript
function greet(name, age) {
console.log(`Hello, ${name}! I am ${age} years old.`);
console.log(`My name is ${this.name}.`);
}
const person = {
name: ‘John’
};
greet.apply(person, [‘Alice’, 25]);
// Output: Hello, Alice! I am 25 years old.
// My name is John.
“`
In this example, `apply()` is used to invoke the `greet()` function with the `person` object as the execution context and an array `[‘Alice’, 25]` as the arguments.
- `bind()`: The `bind()` method creates a new function that has a specified `this` value and, optionally, pre-defined arguments. It allows you to create a function with a fixed execution context that can be called later.
“`javascript
function greet() {
console.log(`Hello, ${this.name}!`);
}
const person = {
name: ‘John’
};
const greetPerson = greet.bind(person);
greetPerson();
// Output: Hello, John!
“`
In this example, `bind()` is used to create a new function `greetPerson` with the `person` object as the fixed execution context. When `greetPerson()` is called, it prints `”Hello, John!”`.
The key difference between `call()`, `apply()`, and `bind()` lies in how they handle function invocation and argument passing. While `call()` and `apply()` immediately invoke the function, `bind()` creates a new function with the desired execution context but doesn’t invoke it right away.
These methods provide flexibility in manipulating function execution and context, enabling the creation of reusable functions and control over `this` binding in JavaScript.
Q24. Explain Hoisting in JavaScript.
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the actual code execution takes place. This means that you can use variables and functions before they are declared in your code.
However, it is important to note that only the declarations are hoisted, not the initializations or assignments. So, while the declarations are moved to the top, any assignments or initializations remain in their original place.
In the case of variable hoisting, when a variable is declared using the `var` keyword, its declaration is hoisted to the top of its scope. This means you can use the variable before it is explicitly declared in the code. However, if you try to access the value of the variable before it is assigned, it will return `undefined`.
For example:
“`javascript
console.log(myVariable); // Output: undefined
var myVariable = 10;
console.log(myVariable); // Output: 10
“`
In the above example, even though `myVariable` is accessed before its declaration, it doesn’t throw an error. However, the initial value is `undefined` until it is assigned the value of `10`.
Function declarations are also hoisted in JavaScript. This means you can call a function before it is defined in the code. For example:
“`javascript
myFunction(); // Output: “Hello, World!”
function myFunction() {
console.log(“Hello, World!”);
}
“`
In this case, the function declaration is hoisted to the top, so we can call `myFunction()` before its actual declaration.
It’s important to understand hoisting in JavaScript to avoid unexpected behavior and to write clean and maintainable code. It is recommended to declare variables and functions at the beginning of their respective scopes to make your code more readable and prevent potential issues related to hoisting.
Q25. What is the difference between exec () and test () methods in JavaScript?
The `exec()` and `test()` methods are both used in JavaScript for working with regular expressions, but they serve different purposes.
- `exec()` method: The `exec()` method is a regular expression method that searches a specified string for a match and returns an array containing information about the match or `null` if no match is found. It returns an array where the first element is the matched substring, and subsequent elements provide additional information such as captured groups, index, and input string.
“`javascript
const regex = /hello (w+)/;
const str = ‘hello world’;
const result = regex.exec(str);
console.log(result);
// Output: [“hello world”, “world”, index: 0, input: “hello world”, groups: undefined]
“`
In this example, the `exec()` method is used to match the regular expression `/hello (w+)/` against the string `’hello world’`. The resulting array contains the matched substring `”hello world”`, the captured group `”world”`, the index of the match, and the input string.
- `test()` method: The `test()` method is also a regular expression method that checks if a pattern matches a specified string and returns a boolean value (`true` or `false`) accordingly. It simply indicates whether a match exists or not.
“`javascript
const regex = /hello/;
const str = ‘hello world’;
const result = regex.test(str);
console.log(result);
// Output: true
“`
In this example, the `test()` method is used to check if the regular expression `/hello/` matches the string `’hello world’`. Since the pattern is found in the string, the method returns `true`.
In summary, the main difference between `exec()` and `test()` is that `exec()` returns an array with detailed match information or `null`, while `test()` returns a boolean value indicating whether a match exists or not. The `exec()` method is more suitable when you need to extract specific match details, while `test()` is useful for simple pattern verification.
Q26. What is the difference between the var and let keywords in JavaScript?
The var and let keywords are both used to declare variables in JavaScript, but they have some key differences.
Scope
The main difference between var and let is the scope of the variables they create. Variables declared with var have function scope, which means they are accessible throughout the function in which they are declared. Variables declared with let have block scope, which means they are only accessible within the block where they are declared.
For example, the following code will print the value of x twice, even though the second x is declared inside a block:
JavaScript
var x = 10;
{
var x = 20;
console.log(x); // 20
}
console.log(x); // 10
If we change the var keyword to let, the second x will not be accessible outside the block:
JavaScript
let x = 10;
{
let x = 20;
console.log(x); // 20
}
console.log(x); // ReferenceError: x is not defined
Hoisting
Another difference between var and let is that var declarations are hoisted, while let declarations are not. Hoisting means that the declaration of a variable is moved to the top of the scope in which it is declared, even though it is not actually executed until later.
For example, the following code will print the value of x even though the x declaration is not actually executed until the console.log() statement:
JavaScript
var x;
console.log(x); // undefined
x = 10;
If we change the var keyword to let, the console.log() statement will throw an error because x is not defined yet:
JavaScript
let x;
console.log(x); // ReferenceError: x is not defined
x = 10;
Redeclaration
Finally, var declarations can be redeclared, while let declarations cannot. This means that you can declare a variable with the same name twice in the same scope with var, but you will get an error if you try to do the same with let.
For example, the following code will not cause an error:
JavaScript
var x = 10;
x = 20;
console.log(x); // 20
However, the following code will cause an error:
JavaScript
let x = 10;
x = 20;
console.log(x); // ReferenceError: x is not defined
The var and let keywords are both used to declare variables in JavaScript, but they have some key differences in terms of scope, hoisting, and redeclaration. In general, it is recommended to use let instead of var, as it provides more predictable and reliable behavior.
Q27. Why do we use the word “debugger” in JavaScript?
“Debugger” in JavaScript is a tool or feature that helps writers find and fix mistakes in their code. It lets them stop the code from running, look at the variables, and analyse phrases to find bugs or strange behaviour and fix them. The word “debugger” comes from the idea of getting rid of “bugs” or mistakes, which is how early engineers fixed problems with hardware.
Q28. Explain Implicit Type Coercion in JavaScript.
In JavaScript, implicit type coercion is when values are automatically changed from one data type to another while the code is running. It happens when numbers of different types are used in actions or comparisons. JavaScript tries to change the numbers into a type that the action can use. Implicit pressure can be helpful, but it can also make people act in ways you didn’t expect, so it’s important to know how it works.
Q29. Is JavaScript a statically typed or a dynamically typed language?
Javascript is a dynamically typed language , because variable types are determined at runtime,rather than being explicitly declared and enforced at compile time as in statically typed languages.
You can assign different types of values to the same variable without causing a type error,as the language determines the type based on the value at the moment it is assigned.
Q30. What is an Immediately Invoked Function in JavaScript?
An immediately Invoked Function Expression(IIFE) is a function in javascript that is defined and executed after it is created.
Often used to create a local scope for variables,preventing them from polluting the global scope.
It typically involves wrapping a function expression in parentheses,followed by another set of parentheses to execute it.
1234567 | (function(){ Var localvariable = “hello world”; console.log(localvariable); })(); |
Q31. What are some advantages of using External JavaScript?
1. Scalability:
When your project grows, maintaining and scaling become necessary. In that case, we use external Javascript rather than inline script.
2. Performance:
When the project is live on a browser, browsers can cache external javascript files. When the file is downloaded,it can be stored locally, reducing load times for subsequent page loads and improving the performance.
3. Reusability:
External javascript files can be reused across multiple HTML pages,so you don’t have to duplicate your code.This not only saves time but helps maintain consistency across your website.
4. Organization :
Javascript in separate files helps keep your HTML document clean and organized.You can easily locate your file.
5. Security:
If your Javascript is in an external file, it sometimes helps prevent certain types of attack, such as cross-site scripting (XSS).
Q32. Explain Scope and Scope Chain in JavaScript.
Scope refers to the accessibility of variables, functions, and objects in a particular part of the code.
This also determines where the elements can be accessed and manipulated.
Two main types of scope are:
1. Global scope:
Variables and functions which are defined in global scope are accessible throughout the entire script.
For eg:
12345678910111213 | Var globaledureka =”Hello everyone welcome”; Function someFun(){ console.log(globaledureka); } someFun(); |
2. Local scope:
Variables which are declared within a function are only accessible within that function.
Fro eg:
12345678910111213 | Function somefun() { Var localed=”hello everyone ”; console.log(localed); } somefun(); console.log(localed); |
3. Scope Chain:
This is a mechanism in JavaScript that is used to resolve variable names when they are accessed.
The scope chain ensures that javascript has a structured way to resolve variables and handle variable lookups (especially in cases where variables have the same name but different scopes).
For eg:
123456789101112131415161718192021222324252627282930313233 | Var edureka =” I am good at coding”; Function outerfunc(){ Var outer =”I am a machine learning beginner”; Function innerfunc(){ Var inner =”I am a artificial intelligence beginner”; console.log(inner); console.log(outer); console.log(global); } innerfunc(); } outerfunc(); |
Q33. What are object prototypes?
Object prototypes in JavaScript are a fundamental concept that enables inheritance and the sharing of properties and method objects.
The prototype object can have its own prototype. Forming a chain known as the prototype chain.
Key points:
1.prototype property(‘_proto_’);
Every javascript object has an internal property called ‘_proto_’ or([[prototype]]);
2. Prototype object:
Prototype objects provide shared properties and methods to other objects.
3. Constructor function and prototype:
For eg:
123456789101112131415 | Function edureka(mess){ this .mess=mess; } edureka.prototype.edML=function{ console.log(“hello,welcome to the company ${ this .mess}”); }; Var AP= new edureka(“Ap”); AP.edML(); |
Q34. What are the types of errors in javascript?
Errors in javascript can be broadly classified into several types and each represents a different kind of problem.
1. Syntax Errors:
If your language does not follow the javascript languages syntax rules.
12345 | if ( true { console.log(“ this will cause a syntaxerror”); } |
2. Reference Errors
When variables that has not been declared or is out of scope is referred by script;
Foreg:
console.log(nonExistentVariable)
3. Type errors
When an operation is performed on a value of an inappropriate type,such as calling a non-function as a function or accessing a property on an undefined value.
For eg:
123 | Var edureka= 34 num.toUpperCase(); |
4. Range Errors:
When the numeric value is outside the allowable range then this error occurs.
For eg:
123 | Ver edureka= 1 ; edureka.toExponential( 500 ); |
5. URI errors:
When there is an incorrect use of global URI handling function like ‘decodeURIComponent()’ or ‘encodeURIComponent()’
decodeURIComponent(‘%’);
6. Eval Errors(not commonly encountered ):
If eval function is used improperly.
But ‘EvalError’ objects are not commonly used and are kept for compatibility with older version of javascript.
7. Aggregate Errors:
When multiple errors occurred simultaneously.
They were introduced in ECMAScript 2021 and can be used in conjunction with ‘promise.any()’ and similar cases.
Q35. What is memoization?
Memoization is used for optimization and to speed up your execution by storing the results of function calls and reusing those outputs when the same inputs occur again.This will also reduce the time complexity.
For eg:
Memoization Fibonacci function:
1234567891011121314151617181920212223242526272829303132333435363738394041 | Function memoi(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 fibonacci=memoize(function(n)) { if (n<= 1 ) return n; Return fibonacci(n- 1 )+fibonacci(n- 2 ); }); console.log(fibonacci( 10 )); |
Q36. What is recursion in a programming language?
When a function calls itself again and again in a program is called recursion.
Recursion is used to solve complex problems by breaking them into smaller problem and solving them individually.
Key concepts are:
Base case:
This means a condition where you have to stop in a recursion.
Recursive case:
This part reduces the problem into subproblems and then you can solve them efficiently.
For eg:
factorial problem using javascript:
12345678910111213 | Function facto(n){ if (n<= 1 ){ Return 1 ; } Return n*fact(n- 1 ); } console.log(facto( 5 )); |
Q37. What is the use of a constructor function in JavaScript?
A constructor function is a different type of function used to create and work with objects.
constructor function helps implement object-oriented programming concepts in JavaScript.
Key Features are creating instances, initialization, inheritance and prototype naming conventions.
For eg:
12345678910111213141516171819202122232425 | function edureka(name, age) { this .name = name; this .age = age; } edureka.prototype.greet = function() { console.log(`Hello, my name is ${ this .name} and I am ${ this .age} years old.`); }; var AP = new edureka( "AP" , 40 ); var john = new edureka( "john" , 5 ); AP.greet(); john.greet(); |
Q38. What is DOM?
The document object model (DOM) is a programming interface for web documents.
It represents the structure of a document as a tree of objects, such as elements, attributes, and text.
DOM allows programming languages,like Javascript,to interact with the content,structure,and style of a document, such as HTML or XML.
Features are tree structure, objects and properties, dynamic interaction, events, cross-platform and language-independent.
For eg:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id=”heading”>hi edureka!</h1>
<button onclick=”changeText()”>C text</button>
<script>
function changeText() {
// Access the h1 element by its id
var heading = document.getElementById(“heading”);
// Change the text content of the h1 element
heading.textContent = “Text has been changed!”;
}
</script>
</body>
</html>
DOM provides the methods ‘getElementById()’ and ‘textContent’ to manipulate the document dynamically.
Q39. Which method is used to retrieve a character from a certain index?
There are several methods to retrieve a character from a certain index in a string.
Most Commonly used are:
1. charAt()::
You must have used this in Java programming, which also works the same.
12345 | const str = "Hello, edureka!" ; const char = str.charAt( 4 ); console.log( char ); |
2. Bracket Notation::
For eg:
12345 | const str = "Hello, edureka!" ; const char = str[ 4 ]; console.log( char ); |
Q40. What do you mean by BOM?
The browser object model(BOD) allows developers to interact with the browser itself, outside of the content of the webpage.
Key Components of the BOM
- Window object
- Navigator object
- Location object
- History object
- Screen object
Uses of BOM
- Manipulating the browser window
- Interacting with the browser
- Accessing browser-specific features
The BOM is not standardized,which means its implementation can vary between different browsers.
Q41. What is the distinction between client-side and server-side JavaScript?
client -side | server-side |
Executed in the users web browser | Executed on the web server |
HTML,CSS,JAVASCRIPT | PHP,PYTHON,RUBY,JAVA |
Enhances user experience and dynamic elements | Manage data storage and retrieval |
User can modify the code ,can view it | Code is hidden from user and runs on server |
Limited by security constraints of the browser | Can securely manage sensitive data and perform protected operations. |
We hope these basic JavaScript Interview Questions for Freshers will help you get the basic understanding and prepare for the 1st phase of the interview.