Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
As of 2024, there are approximately 370.8 million JavaScript libraries and functions detected on the web. Additionally, JavaScript is detected on around 6.5 million of the top million websites. All leading web browsers support JavaScript, demonstrating its ubiquity in the web development domainToday, Google and Facebook use JavaScript to build complex, desktop-like web applications. With the launch of Node.js, It has also become one of the most popular languages for building server-side software. Today, even the web isn’t big enough to contain JavaScript’s versatility. I believe that you are already aware of these facts, and this has made you land on this JavaScript Interview Questions article.
So, this is the perfect time to get started if you want to pursue a career in JavaScript and learn the required skills. Our JavaScript Interview Questions, JavaScript training, and Java Training program can help you gain in-depth information and prepare for your interviews.
This Edureka video on “JavaScript Interview Questions” will help you to prepare yourself for JavaScript Interviews.Learn about the most important JavaScript interview questions and answers and know what will set you apart in the interview process.
The JavaScript interview questions are divided into three sections:
Let’s begin with the first section.
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.
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. |
The data types supported by JavaScript are:
String- This data type is used to represent a sequence of characters.
Example:
var str = "Akash Sharma"; //using double quotes var str2 = 'David Matt'; //using single quotes
Number- This datatype is used to represent numerical values.
Example:
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:
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:
// 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:
var a = null;
Object- It is used to store collection of data.
Example:
// Object const student = { firstName: 'Arya', Roll number: 02 };
Following are the features of JavaScript:
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.
Following are the advantages of using JavaScript −
Check out Java Interview Questions to learn more about Java!
JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = { name: "Daniel", age: 23 };
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.
Example:
function(parameters) { // body of the function }
You can define arrays using the array literal as follows-
var x = []; var y = [1, 2, 3, 4, 5];
A named function declares a name as soon as it is defined. It can be defined using function keyword as :
function named(){ // write code here }
Yes! An anonymous function can be assigned to a variable. It can also be passed as an argument to another function.
If you wish to learn JavaScript and build your own applications, then check out our Full Stack developer course online, which comes with instructor-led live training and real-life project experience.
It includes training on Web Development, jQuery, Angular, NodeJS, ExpressJS and MongoDB.
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 −
function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(7); //==> "number", 1 func("1", "2", "3"); //==> "string", 3
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.
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.
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.
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.
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. |
The following rules are to be followed while naming variables in JavaScript:
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.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
Syntax :
document.cookie = "key1 = value1; key2 = value2; expires = date";
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.
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.
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.
“`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’`.
“`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.
“`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.
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.
The `exec()` and `test()` methods are both used in JavaScript for working with regular expressions, but they serve different purposes.
“`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.
“`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.
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.
“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.
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.
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.
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.
(function(){ Var localvariable = “hello world”; console.log(localvariable); })();
When your project grows, maintaining and scaling become necessary. In that case, we use external Javascript rather than inline script.
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.
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.
Javascript in separate files helps keep your HTML document clean and organized.You can easily locate your file.
If your Javascript is in an external file, it sometimes helps prevent certain types of attack, such as cross-site scripting (XSS).
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:
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:
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:
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();
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:
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();
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.
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:
Var edureka=34 num.toUpperCase();
4. Range Errors:
When the numeric value is outside the allowable range then this error occurs.
For eg:
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.
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:
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));
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:
Function facto(n){ if(n<=1){ Return 1; } Return n*fact(n-1); } console.log(facto(5));
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:
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();
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.
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.
const str = "Hello, edureka!"; const char = str.charAt(4); console.log(char);
2. Bracket Notation::
For eg:
const str = "Hello, edureka!"; const char = str[4]; console.log(char);
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
Uses of BOM
The BOM is not standardized,which means its implementation can vary between different browsers.
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.
Attributes- provide more details on an element like id, type, value etc.
Property- is the value assigned to the property like type=”text”, value=’Name’ etc.
Here are the list of ways an HTML element can be accessed in a Javascript code:
(i) getElementById(‘idname’): Gets an element by its ID name
(ii) getElementsByClass(‘classname’): Gets all the elements that have the given classname.
(iii) getElementsByTagName(‘tagname’): Gets all the elements that have the given tag name.
(iv) querySelector(): This function takes css style selector and returns the first selected element.
There are 3 different ways in which a JavaScript code can be involved in an HTML file:
An inline function is a JavaScript function, which is assigned to a variable created at runtime. You can differentiate between Inline Functions and Anonymous since an inline function is assigned to a variable and can be easily reused. When you need a JavaScript for a function, you can either have the script integrated in the page you are working on, or you can have it placed in a separate file that you call, when needed. This is the difference between an internal script and an external script.
Q45. Explain Higher Order Functions in javascript.
Higher-order functions in JavaScript are functions that can take other functions as inputs or return functions as their outputs. They make it possible to use strong functional programming methods that make code more flexible, reused, and expressive. By treating functions as first-class citizens, they make it possible to abstract behaviour and make flexible code structures.
The three possible ways of defining a variable in JavaScript are:
Typed Language is in which the values are associated with values and not with variables. It is of two types:
Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or program.
Session Storage – It is similar to local storage; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.
The main difference between “==” and “===” operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn’t allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type “===” return false, while “==” return true.
Q50. What is currying in JavaScript?
Currying is a JavaScript functional programming approach that converts a function with many parameters into a succession of functions that each take one argument. It allows you to use only a portion of the inputs, allowing you to create functions that may be used several times and are specialized.
Here is a declared ambiguous variable with no value assigned to it. Null, on the other hand, is an assigned value. As an alternative to that variable, one can use an empty variable. Also, there are actually two different types: undefined is an object, while null is a type in and of itself.
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
A JavaScript framework is an application framework written in JavaScript. It differs from a JavaScript library in its control flow. There are many JavaScript Frameworks available but some of the most commonly used frameworks are:
Window | Document |
JavaScript window is a global object which holds variables, functions, history, location. | The document also comes under the window and can be considered as the property of the window. |
innerHTML – It will process an HTML tag if found in a string
innerText – It will not process an HTML tag if found in a string
Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element. Then the execution passes to its parent element and so on till the body element.
NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.
One of the differences between the two is that Primitive Data Types are passed By Value and Objects are passed By Reference.
The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-
parseInt("4F", 16)
Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its concatenation will be done. So the result would be 73. The ” ” makes all the difference here and represents 3 as a string and not a number.
Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code into multiple files. For example-
//------ lib.js ------</span> export const sqrt = Math.sqrt;</span> export function square(x) {</span> return x * x;</span> } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js ------</span> { square, diag } from 'lib'; console.log(square(5)); // 25 console.log(diag(4, 3)); // 5
Now with this, we have reached the final section of JS Interview Questions.
Arrow function or we can say “fat arrow function ” is a special type of way to write a function in javascript.
They were first introduced in ECMAScript 6(ES6).It also provide a shorter syntax compared to that of traditional ones.
Syntax
Const edureka = (parameter1,parameter2,….) => {
//function body
};
For eg::
Const mul =(a,b) => a*b;
console.log(mul(23,34));
The prototype design pattern is a creational pattern used in software development.
With the help of prototype design patterns, objects can create clones of themselves. This is very easy and simple to use.
Key features are prototype interface, concrete prototype, client.
It works first when a prototype is created then concrete prototype is made doing some changes then final cloning is done.
For eg:
class Proedureka { constructor(course) { this.course = course; } clone() { return new Prototype(this.course); } getName() { return this.course; } } const prototype1 = new Prototype("Prototype 1"); const prototype2 = prototype1.clone(); console.log(prototype1.getName()); console.log(prototype2.getName());
You can take its use cases as
1. Resource-intensive Object
2. Object state
3. Avoiding Constructor Overhead
The rest parameter and spread operator are features in ECMAScript 6 (ES6) that provide a more concise and flexible way to handle function arguments, arrays, and objects.
Syntax-
Function functionName(…args){
//your statements
}
For eg::
For rest parameter
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(0,9,8)); console.log(sum(6,4));
Promises are a powerful tool for managing asynchronous operations. They guide us to handle tasks that have more time complexity, such as fetching data from a server, reading a file, and executing a complex computation, without hindering the execution of the program.
Key concepts of promises in javascript are::
1. Asynchronous operations
2. Promise States
3. Chaining and composition
Basic Syntax
const myPr = new Promise((resolve, reject) => { // Asynchronous operation const success = true; if (success) { resolve("successful!"); } else { reject("failed!"); } });
You can take use cases as
1. Fetching data
2. Sequential Asynchronous operations
3. Error handling
Advantages of promises in javascript are::
1. Avoiding callback hell
2. Error propagation
3. Composability
Classes provide a clear and structured way of creating an object.
For eg::
class edureka { constructor(course, code) { this.course = course; this.code = code; } myed() { console.log(`Hello, my edureka course is ${this.course} and I my course code is ${this.code} .`); } } const person1 = new edureka("Machine Learning", 003); person1.myed();
Special type of function allows you to define an iterative algorithm by writing a single function whose execution can be paused and resumed.
This feature provides a powerful way to work with asynchronous operations,sequences and also lazy evaluations.
It is denoted by ‘function*’
1. Key features are pausing and resuming execution
2. Iteration
3. Lazy evaluation
Syntax::
function* generatorFunction() { yield value1; yield value2; ... }
For eg::
const myedgene = generatorFunction(); console.log( myedgene.next()); console.log( myedgene.next()); console.log( myedgene.next());
For eg::
generating sequence of numbers–
function* numGenerator() { let ednum = 1; while (true) { yield ednum++; } } const numbers = numGenerator(); console.log(numbers.next().value); console.log(numbers.next().value); console.log(numbers.next().value);
Use Cases can be
1. Iterating over data
2. Asynchronous programming
3. Cooperative concurrency
4. Lazy evaluation
Weakset is a collection type that allows you to store weakly held objects.
“Set”:-it lets you store unique values
“Weak”:-weak nature
Key feature are
For eg::
let ws = new WeakSet(); let obj1 = { a: 1 }; let obj2 = { b: 2 }; ws.add(obj1); ws.add(obj2); console.log(ws.has(obj1)); console.log(ws.has(obj2)); ws.delete(obj1); console.log(ws.has(obj1));
callbacks are functions that are passed as arguments to other functions and are initiated after a certain event or task has been done.
They are fundamental concepts in JavaScript.
Reasons to use callbacks:
1. handling asynchronous operations
Like APIcalls,Timers,Event Handling.
2. modularity and reusability
For eg::
function executeWithLogging(action, callback) { console.log("Starting action..."); callback(action); console.log("Action completed."); } executeWithLogging("Task 1", task => console.log(`Executing ${task}`)); executeWithLogging("Task 2", task => console.log(`Running ${task}`));
3. custom control flow
For eg::
function performTask(task, onSuccess, onError) { try { if (task === "fail") throw new Error("Task failed"); onSuccess("Task completed successfully"); } catch (error) { onError(error); } } performTask( "task1", successMessage => console.log(successMessage), errorMessage => console.error(errorMessage) );
4. event driven
Foreg::
document.getElementById("myButton").addEventListener("click", function() { console.log("Button was clicked!"); });
5. Avoiding blocking code::
In environments like node.js used for server-side javascript.
Weakmap is a collection type that stores key-value pairs, where the keys are objects and the values can be any arbitrary values
The keys in weakmap are held weakly meaning they do not prevent garbage collection if there are no other references to the object.
Key features are
1. only objects as keys
2. weak references
3. no enumeration or iteration
4. non-enumerable
5. methods like
set(key,value)
get(key)
has(key)
delete (key)
For eg::
let edurekaweakMap = new edurekaWeakMap(); let obj1 = {}; let obj2 = {}; edurekaweakMap.set(obj1, "Object 1 value"); edurekaweakMap.set(obj2, "Object 2 value"); console.log(edurekaweakMap.get(obj1)); console.log(edurekaweakMap.has(obj2)); edurekaweakMap.delete(obj1); console.log(edurekaweakMap.has(obj1));
It is a syntax feature in javascript that allows the user to extract properties from object and assign them to variables in a more legible way.
Syntax
const edureka = { course: "ML", code: 090, job: "Engineer" }; const { course, code, job } = edureka; console.log(course); console.log(code); console.log(job);
Use Cases and benefits are::
1. concise code
2. avoid repeated access
3. function parameters
It is a powerful feature in javascript that simplifies the extraction and assignment of object properties,making the code more readable and maintainable.
prototype | Classical inheritance |
Property chain,Dynamic inheritance,object.create | Classes and instances,inheritance,constructor function |
flexible,simplicity | Familiar syntax,clear structure |
Readability,inheritance depth | Less flexibility,boilerplate code |
Uses object.create | Uses class,extends,super |
Refers to the period between creation of a variable’s scope and the point where the variable is actually declared and initialized.
function example() { console.log(ed); let ed = 10;} example();
Key features of temporal dead zone are::
1. Scope and initialization
2. error handling
3. var VS let /const:var
The Temporal Dead Zone is an important concept for understanding the behavior of “let” and “const” declarations in JavaScript.
Javascript design patterns are the best practices for common problems in software design and architecture.
These provide guidance for structuring code,improving code maintainability and making is more efficient and scalable.
Common designs are as follows::
The benefits of using design patterns are as follows:
Javascript is a pass-by-value language
Pass by value::
So when the value is passed in a function in javascript as a pass by value then it sends a copy of it and the original value doesn’t get affected if the passed value is changed.
For eg::
function passbyvalue(x) { x = 100;} let a = 200; updateValue(a); console.log(a);
Alternative is pass-by-reference
When you pass a value in a function then a copy of its reference goes and if any change occurs to the pass value then the original value also gets changed.
For eg::
function passbyrefer(obj) { obj.name = 'DATA SCIENCE'; } let course = { name: 'ML' }; updateObject(course); console.log(course.name);
Async/Await | Generators |
Uses async function and await expression | Uses function* and yield |
Uses try/catch block for error handling | try/catch inside the generator for error handling |
More readable and concise | Less intuitive due to management of yield. |
Automatically handles control flow;awaits promise resolution | Require manual iteration with next() and throw() methods. |
It provides a way to control the loading and execution order of scripts in a webpage.
Play a crucial role in optimizing the performance of web pages.
Key Features::
For eg::
<!DOCTYPE html> <html> <head> <title>Deferred Scripts Example</title> </head> <body> <h1>hi users welcome to edureka courses!</h1> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22script1.js%22%20defer%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22script2.js%22%20defer%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> </body> </html>
To effectively use lexical scoping in javascript follow these steps::
Strict mode is a way to introduce better error-checking into your code.
A prompt box is a box that allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is typically used when you want the user to put a value before looking at a page. To move further, the user must click “OK” or “Cancel” in the prompt box that displays after entering an input value.
🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”)
This Edureka Java Full Course will help you understand the various fundamentals of Java programm…
var Y = 1; if (function F(){}) { y += Typeof F;</span> } console.log(y);
The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.
The call() method calls a function with a given this value and arguments provided individually.
Syntax-
fun.call(thisArg[, arg1[, arg2[, ...]]])
The apply() method calls a function with a given this value, and arguments provided as an array.
Syntax-
fun.apply(thisArg, [argsArray])
There are a number of methods you can use to empty an array:
Method 1 –
arrayList = []
Above code will set the variable arrayList to a new empty array. This is recommended if you don’t have references to the original array arrayList anywhere else, because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.
Method 2 –
arrayList.length = 0;
The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.
Method 3 –
arrayList.splice(0, arrayList.length);
The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.
Method 4 –
while(arrayList.length) { arrayList.pop(); }
The implementation above can also empty arrays, but it is usually not recommended to use this method often.
var Output = (function(x) { Delete X; return X; } )(0); console.log(output);
The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don’t affect local variables.
Q86. What do you mean by Self Invoking Functions?
JavaScript functions that execute instantly upon definition without requiring an explicit function call are referred to as self-invoking functions, or immediately invoked function expressions (IIFE).
When you create a function that invokes itself, you may use parentheses or other operators to invoke it immediately after enclosing the function declaration or expression in parenthesis.
A self-invoking function looks like this:
“`javascript
(function() {
// Function body
})();
“`
In this example, the function is defined inside parentheses `(function() { … })`. The trailing parentheses `()` immediately invoke the function. Because it lacks a reference to be called again, the function is only ever run once before being deleted.
In order to keep variables, functions, or modules out of the global namespace, self-invoking functions are frequently used to establish a distinct scope. Code enclosed in a self-invoking function allows you to define variables without worrying about them clashing with other variables in the global scope.
Using a self-invoking procedure to establish a private variable is illustrated in the following example:
“`javascript
(function() {
var privateVariable = ‘This is private’;
// Other code within the function
})();
“`
This means that the variable {privateVariable} cannot be viewed or changed from outside of the self-invoking function and can only be accessed within its scope.
Another technique to run code instantly and give you a chance to assign the result to a variable or return values is by using self-invoking functions:
“`javascript
var result = (function() {
// Code logic
return someValue;
})();
“`
The outcome of the self-invoking function is designated to the `result} variable in this instance. This preserves a clear separation of scope and lets you carry out computations, initialize variables, or run code immediately.
Self-invoking functions offer a useful technique for creating isolated scopes and executing code immediately without cluttering the global scope. They are commonly used in modular patterns to avoid naming collisions or leaking variables.
var X = { Foo : 1}; var Output = (function() { delete X.foo; return X.foo; } )(); console.log(output);
The output would be undefined. An object’s property can be removed using the delete operator. In this case, object x holds the property foo. Since the function is self-invoking, we shall remove the foo property from object x. The outcome is still being determined when we attempt to reference a removed property after doing this.
var Employee = { company: 'xyz' } var Emp1 = Object.create(employee); delete Emp1.company Console.log(emp1.company);
The output would be xyz. Here, emp1 object has company as its prototype property. The delete operator doesn’t delete prototype property. emp1 object doesn’t have company as its own property. However, we can delete the company property directly from the Employee object using delete Employee.company.
//nfe (named function expression) var Foo = Function Bar() { return 7; }; typeof Bar();
The output would be Reference Error. A function definition can have only one reference variable as its function name.
This is an increasingly common practice, employed by many popular JavaScript libraries. This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
Another feature of this technique is to allow for an easy alias for a global variable. This is often used in jQuery plugins.
JavaScript escape characters enable you to write special characters without breaking your application. Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.
For example-
document.write "I am a "good" boy" document.write "I am a "good" boy"
Get the list of angular interview questions with answers , if you are looking for a job javascript with angular.
<!DOCTYPE html> <html> <body> <h2>My first edureka experience</h2> <p>The courses of edureka are the best in terms of experiences </p> <p id="demo"></p> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Adocument.getElementById(%22demo%22).innerHTML%20%3D%2089%2B90%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> </body> </html>
<!DOCTYPE html> <html> <body> <h1>My time with edureka students</h1> <p>so smart and intelligent students </p> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Adocument.write(99%2B12)%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> </body> </html>
<!DOCTYPE html> <html> <body> <h1>how was your day while learning edureka courses</h1> <p>it was the best day i can have with</p> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Awindow.alert(23%2B90)%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> </body> </html>
function edBS(arr, x) { let low = 0; let high = arr.length - 1; let mid; while (high >= low) { mid = low + Math.floor((high - low) / 2); if (arr[mid] == x) return mid; if (arr[mid] > x) high = mid - 1; else low = mid + 1; } return -1; } arr = new Array(1,4,7,20,80,90); x = 80; n = arr.length; result = edBS(arr, x); if (result == -1) console.log("There is no such element please try again") else { console.log("you got the position very good lerners " + result); }
Output
You got the position very good lerners 4
function ed_rotate_print(arr,d,n) { var blank=new Array(n); d=d%n; let k = 0; for (let i = d; i < n; i++) { blank[k] = arr[i]; k++; } for (let i = 0; i < d; i++) { temp[k] = arr[i]; k++; } for (let i = 0; i < n; i++) { console.log(blank[i]+" "); } } let array = [ 0,9,8,7,6,5,4 ]; let n = array.length; let d = 2; ed_rotate_print((arr, d, n);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%0Ahtml%2C%0A%0Abody%20%7B%0A%0Aheight%3A%20200%25%3B%0A%0Awidth%3A%20200%25%3B%0A%0A%7D%0A%0A%26nbsp%3B%0A%0A.button%20%7B%0A%0Adisplay%3A%20flex%3B%0A%0Aalign-items%3A%20center%3B%0A%0Ajustify-content%3A%20center%3B%0A%0A%7D%0A%0A%26nbsp%3B%0A%0A.tasks%20%7B%0A%0Adisplay%3A%20flex%3B%0A%0Ajustify-content%3A%20center%3B%0A%0Aalign-items%3A%20center%3B%0A%0Aflex-direction%3A%20column%3B%0A%0Amargin-top%3A%2020px%3B%0A%0A%7D%0A%0A%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<style>" title="<style>" /> </head> <body> <div class="button"> <button id="addTask">Add task</button> </div> <div class="tasks"></div> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%0A%26nbsp%3B%0A%0Alet%20task%20%3D%20document.getElementsByClassName(%22tasks%22)%3B%0A%0Alet%20addTask%20%3D%20document.getElementById(%22addTask%22)%3B%0A%0AaddTask.addEventListener('click'%2C%20function%20()%20%7B%0A%0Afor%20(let%20i%20%3D%200%3B%20i%20%3C%20task.length%3B%20i%2B%2B)%20%7B%0A%0Alet%20newDiv%20%3D%20document.createElement(%22div%22)%3B%0A%0AnewDiv.setAttribute(%22class%22%2C%20%22list%22)%3B%0A%0AnewDiv.innerText%20%3D%20%22New%20Div%20created%22%3B%0A%0Atask%5Bi%5D.append(newDiv)%3B%0A%0A%7D%0A%0A%7D)%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> </body> </html>
function areAnagrams(s1, s2) { return s1.split('').sort().join('') === s2.split('').sort().join(''); } let str1 = "listen"; let str2 = "silent"; if (areAnagrams(str1, str2)) { console.log("True"); } else { console.log("False"); } str1 = "gram"; str2 = "arm"; if (areAnagrams(str1, str2)) { console.log("True"); } else { console.log("False"); }
With this, we have come to the end of the JavaScript interview questions and answers blog. You can also check Java Collection Interview Questions for more. I Hope these questions will help you in your interviews. In case you have attended interviews in the recent past, do paste those interview questions in the comments section and we’ll answer them. You can also comment below if you have any questions in your mind, which you might face in your JavaScript interview.
Primary data types are basic types of data that does not have objects and methods::
1.string:for char values.
let edureka=”hi welcome to this course”;
2.Number:for integer value in javascript
For eg::
let number1=90 let number2=3.14
3.BigInt::for integer with arbitrary precision
For eg::
let bigInt=12345678900987654321234566789900
4.Boolean::for the logical entity either true or false;
For eg::
let istrue=true let isfalse=false;
5.Undefined:: a variable declared but not assigned.
For eg::
let x; console.log(x);
6.NULL::intentional absence of any object value.
For eg::
let y=null; 7.symbol Represents unique and immutable identifiers. let sym=symbol(“example”);
During the compilation time before the code is executed where variable are moved to the top of their containing scope(either global or function scope)
The hosting works like variable declaration then function declaration then ‘let’ and ‘const’ declarations
1.variable hosting
console.log(edureka); var edureka = 1000000; console.log(edureka);
2.function hosting
sayedureka(); function sayedureka() { console.log("hi welcome to this course"); }
3.hosting with ‘let’ and ‘const’
console.log(edureka); let edureka = 100000; console.log(course); const edurekacourse = 200000;
In javascript::
“=== “ is strict equality
console.log(45 === 45);
console.log(95 === ’95’);
console.log(null === null);
console.log(undefined === null);
“==” is loose equality
For eg::
console.log(‘edureka’ == ‘edureka’); console.log(100 == 'edureka'); console.log(null == undefined); console.log(‘ ' == false);
We can loop in different ways in javascript
1.for loop::
let edarr=[5,7,9,0,4,5]; for(let i=0;i<array.length;i++){ console.log(array[i]); }
2.for…of loop
let edarr=[2,3,5,7,8,9]; for(let element of array){ console.log(element); }
3.forEach method
let edarr = [1,3,5,7,9]; array.forEach(function(element,index){ console.log(element); });
4.for…in loop
let edarr=[0,8,6,4,2]; for(let index in array){ console.log(array[index]);}
Got a question for us? Please mention it in the comments section and we will get back to you.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 22nd February,2025 22nd February SAT&SUN (Weekend Batch) | View Details |
edureka.co
Questions and answers are good but if there will be an example with code that it will be like awesome.
Very good article you publish helpful these question and answer are also important for java script learning students.
This post was really useful in terms of the information provided and the various level-wise questions.
Most of the questions are outdated and no longer asked in Interview.
Kindly hire a PROFESSIONAL and make articles.