JavaScript Interview Questions
This page consists of JavaScript interview questions and answers.
We can create arrays in JavaScript in the following three ways.
In the following example we are creating an array having three elements using array literal approach.
var arr = [1, 2, 3];
In the following example we are creating an array having three elements by instantiating Array.
var arr = new Array();
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
In the following example we are creating an array having three elements using array constructor.
var arr = new Array(1, 2, 3);
We can create an object in JavaScript in the following ways.
In the following example we are creating an object having three properties using object literal approach.
var obj = {
name: 'Yusuf Shakeel',
score: 10,
username: 'yusufshakeel'
};
In the following example we are creating an object having three properties by instantiating Object.
var obj = new Object();
obj.name = 'Yusuf Shakeel';
obj.score = 10;
obj.username = 'yusufshakeel';
In the following example we are creating an object having three properties using object constructor.
var User = function(name, score, username) {
this.name = name;
this.score = score;
this.username = username;
};
var obj = new User('Yusuf Shakeel', 10, 'yusufshakeel');
JavaScript was initially named Mocha.
Negative infinity is a number we get when we divide negative numbers by zero.
The following code will give us -Infinity
.
console.log(-1/0);
Following are the pop up boxes in JavaScript.
Alert box is used to alert a message to the user.
In the following example we are creating an alert box that alerts a message to the user.
alert("Welcome back!");
Confirm box is used to verify or confirm some action by the user.
If the user confirms then confirm box returns true
otherwise, false
.
In the following example we will print "Accepted" if the user confirm otherwise, we will print "Rejected".
var isConfirmed = confirm('Do you want to proceed?');
if (isConfirmed === true) {
console.log('Accepted');
} else {
console.log('Rejected');
}
Prompt box is used to get user input.
If user provides some data and clicks the "OK" button then the prompt box returns the submitted data. Otherwise, we get null
.
In the following example we are creating a simple prompt box.
var name = prompt('Enter your name');
console.log(name);
Hoisting is a default JavaScript behaviour of moving all the declarations at the top of the current scope (top of the current script or top of the current function).
The following code is an example of hoisting.
console.log("Value of x: " + x);
var y = x + 10;
console.log("Added 10 to x and assigned it to y. So y = " + y);
// now declaring x and assigning value
var x = 10;
Output:
Value of x: 10
Added 10 to x and assigned it to y. So y = 20
function foo() {
console.log(x);
}
var x = 10;
foo();
The answer is 10.
This is because of hoisting.
ADVERTISEMENT