Developed by Brendan Eich in 1995, JavaScript is one of the most widely used web development languages. It was originally developed to create dynamic websites. A script is a JS program that can be added to the HTML of any web page. When the page loads, these scripts will run automatically. Today most of the big companies use JavaScript like Google, Facebook, Wipro etc. So today we are sharing your best JavaScript interview questions and answers that will help you crack your tech round. So let’s start.
Following are the data types available in javascript
Yes, JavaScript is case sensitive. In this Language keywords, variables, function names, and other identifiers should always be case sensitive.
JavaScript supports Object concept very well. You can create an object using the object literal as follows
Example
var emp = {
name: "Sachin",
age: 35
};
The function which has named at the time of definition is called a named function.
Example
function Welcome()
{
document.writeln("Named Function");
}
Welcome();
In this function which has no name. These functions are declared dynamically at runtime using the function operator in place of the function declaration. The function operator is greater bendy than a function declaration. It may be without difficulty used in the place of an expression.
Example
var Welcome=function()
{
alert("Anonymous Function is invoked");
}
display();
isNaN means not a number in this function returns true if the argument is not a number; otherwise, it is false.
Example
isNaN("Hello") // Returns true
isNaN(345) // Returns false
isNaN('1') // Returns false, since '1' is converted to Number type which results in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ 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"
From the very beginning, the ‘var’ key-word changed into utilized in JavaScript programming while the key-word ‘let’ changed into simply brought in 2015.
The keyword ‘Var‘ has function scope. Anywhere in the function, the variable specified using var is accessible but in ‘let’ the scope of a variable declared with the ‘let‘ keyword is limited to the block in which it is declared. Let’s start with a Block Scope.
‘var‘ declares a variable that will be hoisted but ‘let’ declares a variable that will not be hoisted.
Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.
Example 1
a = 13;
console.log(a); // outputs 13 even when the variable is declared after it is initialized
var hoistedVariable;
Example 2
// Hoisting takes place in the local scope as well
function printAge(){
x = 33;
console.log(x);
var x;
}
printAge(); // Outputs 33 since the local variable “x” is hoisted inside the local scope
Undeclared variables are the ones that don’t exist in a application and aren’t declared. If this system attempts to examine the fee of an undeclared variable, then a runtime mistakess is encountered.
Example
console.log(x); //Here error will come for x variable for undeclared
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.
Example
var x;
console.log(x); //Here error will come for x variable for undefined
‘this’ keyword refers to the object from where it was called.
Example
function welcome() {
console.log(this);
}
welcome();
In the above example this refer to welcome function.
call(): It’s a predefined method in javascript. This method invokes a method (function) by specifying the owner object.
Example 1
function sayHello(){
return "Hello " + this.name;
}
var obj = {name: "DD Academy"};
sayHello.call(obj);
// Returns "Hello DD Academy"
Example 2
var person = {
age: 30,
getAge: function(){
return this.age;
}
}
var person2 = {age: 54};
person.getAge.call(person2);
// Returns 84
apply() : This method same as call() method only difference is call() method takes arguments separately whereas, apply() method takes arguments as an array.
Example
function saySomething(message){
return this.name + " is " + message;
}
var person = {name: "DD Academy"};
saySomething.apply(person, ["awesome"]);
External JavaScript is the JavaScript Code (script) written in a separate record with the extension.js, after which we hyperlink that record in the or detail of the HTML record wherein the code is to be placed.
Some advantages of external javascript are
‘ViewState’ is specific to a page in a session.
‘SessionState’ is specific to user-specific data that can be accessed across all web application pages.
Yes, JavaScript does support automatic type conversion. It is the common way of type conversion used by JavaScript developers
There are two ways to read and write a file using JavaScript
In JavaScript Extensions, you can use fo = fopen(getScriptPath(), 0); to open a file
Using ActiveX objects, following should be included in your code to read a file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\example.txt", 1, true);
Using the navigator.appVersion or navigator.userAgent property we can detect the client operating system in JavaScript.
Example
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
// Display the OS name
document.getElementById("OS").innerHTML = OSName;
The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number, and no array object.
DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.
The window object is created automatically by the browser that represents a window of a browser. It is not an object of JavaScript. It is a browser object.
Below are some window object we used at a time of development.
The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.
The innerHTML property is used to write the HTML code using JavaScript dynamically.
Example
document.getElementById('location').innerHTML="<h2>This is heading using JavaScript</h2>";
Client-side JavaScript contains the primary language and predefined items which might be applicable to running JavaScript in a browser. The client-side JavaScript is embedded without delay via way of means of in the HTML pages. The browser translates this script at runtime.
Server-side JavaScript additionally resembles client-side JavaScript. It has a applicable JavaScript that’s to run in a server. The server-side JavaScript are deployed only after compilation.
In JavaScript, the event.preventDefault() method is used to prevent the default behavior of an element.
For example: If you use it in a form element, it prevents it from submitting. If used in an anchor element, it prevents it from navigating. If used in a contextmenu, it prevents it from showing or displaying.
On the other hand, the event.stopPropagation() method is used to stop the propagation of an event or stop the event from occurring in the bubbling or capturing phase.
Negative Infinity is a number in JavaScript which can be derived by dividing the negative number by zero.
Example
var num=-500;
function display()
{
document.writeln(num/0);
}
display();
//expected output: -Infinity
Let’s see the below JavaScript code to submit the form by clicking the link.
Example
<form name="submitForm" action="index.php">
Search: <input type='text' name='search' />
<a href="javascript: fncSubmitForm()">Search</a>
</form>
<script type="text/javascript">
function fncSubmitForm()
{
document.submitForm.submit();
}
</script>
JavaScript did not display any error message in a browser. However, those errors can have an effect on the output. The satisfactory exercise to discover the mistake is to debug the code. The code may be debugged effortlessly through the usage of internet browsers like Google Chrome, Mozilla Firebox.
To perform debugging, we can use any of the following approaches:
Using console.log() method
Using debugger keyword
JavaScript debugger keyword sets the breakpoint through the code itself. The debugger stops the execution of the program at the position it is applied. Now, we can start the flow of execution manually. If an exception occurs, the execution will stop again on that particular line.
Example
function display(){
x = 10;
y = 15;
z = x + y;
debugger;
document.write(z);
document.write(a);
}
display();
The JavaScript strict mode is used to generates silent errors. It provides “use strict”; expression to enable the strict mode. This expression can only be placed as the first statement in a script or a function.
Example
"use strict";
x=10;
console.log(x);
JavaScript variables can belong to the local or global scope. As per official following is the defination.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
Example
function init() {
var name = 'developerdiary'; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
init();
init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
JavaScript is a single-threaded synchronous programming language. It means that the main thread where JavaScript code is run, runs in one line at a time manner and there is no possibility of running code in parallel.
Example
console.log("Before delay");
function delayBySeconds(sec) {
let start = now = Date.now()
while(now-start < (sec*1000)) {
now = Date.now();
}
}
delayBySeconds(15);
console.log("After delay");
Output
Before delay
(... waits for 15 seconds)
After delay
PHP OOPS Interview Questions And Answers (2022)
Latest MySQL Interview Questions And Answers
Laravel Interview Questions And Answers
PHP Interview Questions And Answers
I believe that these JavaScript interview questions and answers would help you understand what kind of questions may be asked to you in an interview, and by going through these JavaScript interview questions, you can prepare and crack your next interview in one go. And I will try to update interview questions and answers here more. So you can get more into it.
Introduction Git tags are an essential feature of version control systems, offering a simple way…
Introduction The methods that browsers employ to store data on a user's device are referred…
Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…
Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…
Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…
Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…