JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.
In JavaScript, if you try to use a variable that doesn’t exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined.
Let’s say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.
> var x; // declaring x
> console.log(x); //output: undefined
Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting.
The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined.
var x; // Declaration
if(typeof x === 'undefined') // Will return true
If a variable that is neither declared nor defined, when we try to reference such a variable we’d get the result not defined.
> console.log(y); // Output: ReferenceError: y is not defined
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.
var k = 1;
if (1) {
eval(function foo(){});
k += typeof foo;
}
console.log(k);
The code above will also output 1undefined.
var k = 1;
if (1) {
function foo(){};
k += typeof foo;
}
console.log(k); // output 1function
A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.
The closure has access to variables in three scopes:
Variables declared in their own scope
Variables declared in a parent function scope
Variables declared in the global namespace
var globalVar = "abc";
// Parent self invoking function
(function outerFunction (outerArg) { // begin of scope outerFunction
// Variable declared in outerFunction function scope
var outerFuncVar = 'x';
// Closure self-invoking function
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y";
console.log(
"outerArg = " + outerArg + "\n" +
"outerFuncVar = " + outerFuncVar + "\n" +
"innerArg = " + innerArg + "\n" +
"innerFuncVar = " + innerFuncVar + "\n" +
"globalVar = " + globalVar);
}// end of scope innerFunction)(5); // Pass 5 as parameter
}// end of scope outerFunction )(7); // Pass 7 as parameter
innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.
Thus, the output of the code above would be:
outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc
Below is the answer followed by an explanation to how it works:
function mul (x) {
return function (y) { // anonymous function
return function (z) { // anonymous function
return x * y * z;
};
};
}
Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed.
In JavaScript, a function defined inside another one has access to the outer function’s variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function.
A function is an instance of the Object type
A function can have properties and has a link back to its constructor method
A function can be stored as a variable
A function can be pass as a parameter to another function
A function can be returned from another function
WATCH: Mock technical intervie
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.
For Instance,
var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a','b','c','d','e','f']
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.
For Instance,
var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []
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.
var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // 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.
The output would be 1. The delete operator is used to delete the property of an object. Here x is not an object, but rather it’s the global variable of type number.
The output would be undefined. The delete operator is used to delete the property of an object. Here, x is an object which has the property foo, and as it is a self-invoking function, we will delete the foo property from object x. After doing so, when we try to reference a deleted property foo, the result isundefined.
The main difference is the function foo is defined at run-time whereas function bar is defined at parse time. To understand this in better way, let’s take a look at the code below:
Run-Time function declaration
<script>
foo(); // Calling foo function here will give an Error
var foo = function(){
console.log("Hi I am inside Foo");
};
</script>
<script>
Parse-Time function declaration
bar(); // Calling foo function will not give an Error
function bar(){
console.log("Hi I am inside Foo");
};
</script>
Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark issue.In other words, you can say JScript is same as JavaScript, but it is provided by Microsoft.
Yes.
BOM stands for Browser Object Model. It provides interaction with the browser. The default object of browser is window.
DOM stands for Document Object Model. A document object represent the html document. It can be used to access and change the content of html.
The window object is automatically created by the browser that represents a window of a browser. It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc.
The history object of browser can be used to switch to history pages such as back and forward from current page or another page. There are three methods of history object.
history.back()
history.forward()
history.go(number): number may be positive for forward, negative for backward.
There are two types of data types in JavaScript:
Primitive Data Types
Non-primitive Data Types
The == operator is used to compare values only whereas === is used to compare both values and types. i.e. value must be of same type.
The keyword 'Var' has a 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.
The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a simple example:
document.getElementById('mylocation').innerHTML="<h2>This is heading using JavaScript</h2>";
The innerText property is used to write the simple text using JavaScript dynamically. Let's see a simple example:
document.getElementById('mylocation').innerText="This is text using JavaScript";
3030 because 10+20 will be 30. If there is numeric value before and after +, it is treated is binary + (arithmetic operator).
102030 because after a string all the + will be treated as string concatenation operator (not binary +).
JavaScript Interview Questions JavaScript interview questions and answers for provides a list of top 20 interview questions. The frequently asked JavaScript interview questions with answers for beginners and professionals are given below. 1) What is JavaScript? JavaScript is a scripting language. It is different from Java language. It is object-based, lightweight and cross platform. It is widely used for client side validation. More details... 2) What is the difference between JavaScript and jscript? Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark issue.In other words, you can say JScript is same as JavaScript, but it is provided by Microsoft. 3) How to write a hello world example of JavaScript? A simple example of JavaScript hello world is given below. You need to place it inside the body tag of html. More details... 4) How to use external JavaScript file? I am assuming that js file name is message.js, place the following script tag inside the head tag. More details... 5) Is JavaScript case sensitive language? Yes. 6) What is BOM? BOM stands for Browser Object Model. It provides interaction with the browser. The default object of browser is window. More Details: Browser Object Model 7) What is DOM? What is the use of document object? DOM stands for Document Object Model. A document object represent the html document. It can be used to access and change the content of html. More Details: Document Object Model 8) What is the use of window object? The window object is automatically created by the browser that represents a window of a browser. It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc. More details... 9) What is the use of history object? The history object of browser can be used to switch to history pages such as back and forward from current page or another page. There are three methods of history object. history.back() history.forward() history.go(number): number may be positive for forward, negative for backward. More details... 10) How to write comment in JavaScript? There are two types of comments in JavaScript. Single Line Comment: It is represented by // (double forward slash) Multi Line Comment: It is represented by slash with asterisk symbol as /* write comment here */ More details... 11) How to create function in JavaScript? To create function in JavaScript, follow the following syntax. function function_name(){ //function body } More details... 12) What are the JavaScript data types? There are two types of data types in JavaScript: Primitive Data Types Non-primitive Data Types More details... 13) What is the difference between == and ===? The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type. 14) How to write html code dynamically using JavaScript? The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a simple example: document.getElementById('mylocation').innerHTML="
Undefined value: A value that is not defined and has no keyword is known as undefined value. For example:
int number;//Here, number has undefined value.
Null value: A value that is explicitly specified by the keyword "null" is known as null value. For example:
String str=null;//Here, str has a null value.
The cursor can be set to wait in JavaScript by using the property "cursor". The following example illustrates the usage:
<script>
window.document.body.style.cursor = "wait";
</script>
Three dimensional array.
"View state" is specific to a page in a session whereas "Session state" is specific to a user or browser that can be accessed across all pages in the web application.
Let's see the JavaScript code to submit form on clicking the link.
<form name="myform" action="index.php">
Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
<script type="text/javascript">
document.body.bgColor="pink";
</script>
Surprisingly, these two functions will not return the same thing. Rather:
console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());
will yield:
foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined
JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: "Zara",
age: 10
};
JavaScript uses a hierarchical structure that applies to the objects in a document. There are some objects that show the relationship of one object to another using the language.
Window object :
This is the topmost object in the hierarchy. It represent the content area of browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document object :
This object gets loaded in a window and consists of objects of different kind in the model. It consists of the content that will be written in the script.
Form object :
Form objects are used for more interaction with the users. It represents the form elements inside <FORM>...</FORM> tag.
There are many errors that can occur in a system. JavaScript provides a message for all the errors at run time and dynamically generate the error code. The errors that are present :
Load-time errors :
These are the errors that come when loading a web page like using of improper syntax and the errors gets detected the moment user loads a page.
Run-time errors :
These are the errors that comes due to misuse of the language commands used inside the HTML document. This shows that it has loaded but the functionality is not properly integrated.
Logic errors :
These are the errors that comes due to bad logic performed on a function that is having different operation but it is made to have logic differently.
The variable which are declared in the program but not assigned any value yet is called undefined variable while the variable which are not declared in the program is called undeclared variable.
- For Example :
undeclared variable:
<script>
var p;
alert(p); // This will give error because p is undeclared variable.
</script>
? undefined variable
<script>
alert(p); //This will give error because p is undefined.
</script>
- encodeURI() function is used to encode the URI.
- This function does not encode following special characters :
' = , ? : $ @ / & # + '
- Syntax : encodeURI(uri), Where uri is URI to be encoded.
- For example :
<script>
var uri = “EmpDetails.asp?Emp=årpit&mode=edit”;
document.write(encodeURI(uri) + “<br/>”);
</script>
- If you use innerHTML the content is replaced everytime.
- We cannot use like 'appending to innerHTML'.
- Even if we use += like "innerHTML = innerHTML + ‘html’" then also the old content is replaced by html.
- If we use innerHTML then the entire innerHTML content is re-parsed and build into elements. Therefore it’s much slower.
- The innerHTML doesn't provide validation and therefore we can potentially insert invalid and broken HTML in the document and break it.
- The decodeURI() function is used to decode the URI.
- Syntax :
decodeURI(uri)
Where uri is URI to be decoded
- For example :
<script>
var uri = “EmpDetails.asp?Emp=årpit&mode=edit”;
document.write(encodeURI(uri) + “<br/>”);
document.write(decodeURI(uri) + “<br/>”);
</script>
- Output :
EmpDetails.asp?Emp=%C3%A5&mode=edit
EmpDetails.asp?Emp=årpit&mode=edit.
- The difference is that onDocumentReady is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
- Suppose there is very large image on a page, at that time onDocumentReady will wait until that image is loaded totally.
- So while using the window.onlaod() function the execution will be slow, but the onDocumentReady will not wait until the image is loaded.
- If we want to change only a single property of an element’s style, we can change the CSS of element using the element's style property :
var myelement = document.getElementById("mydiv");
myelement.style.width = "200px";
- If we want to change value of more than one properties, we can use the element’s setAttribute method :
myelement.setAttribute("style","width: 200px; background-color: blue;");
- If the CSS property contains a hyphen, for example” font-family” or “background-color”, we have to use CamelCase notation as follows :
myelement.style.fontFamily = "Arial";
myelement.style.backgroundColor = "rgb(255,222,12)";
- We can also use the element’s setAttribute method to set the style property :
myelement.setAttribute("style","font-family: Arial; background-color: green");
You can define arrays using the array literal as follows −
var x = [];
var y = [1, 2, 3, 4, 5];
An array has a length property that is useful for iteration. We can read elements of an array as follows −
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++) {
// Do something with x[i]
}
A named function has a name when it is defined. A named function can be defined using function keyword as follows −
function named(){
// do some stuff here
}
A function in JavaScript can be either named or anonymous.
An anonymous function can be defined in similar way as a normal function but it would not have any name.
Yes! An anonymous function can be assigned to a variable.
Yes! An anonymous function can be passed as an argument to another function.
Using typeof 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(1); //==> "number", 1
func("1", "2", "3"); //==> "string", 3
Using arguments.length property, we can get the total number of arguments passed to a function. For example −
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(1); //==> "number", 1
func("1", "2", "3"); //==> "string", 3
JavaScript famous keyword this always refers to the current context.
pop() method removes the last element from an array and returns that element.
push() method adds one or more elements to the end of an array and returns the new length of the array.
toString() method returns the string representation of the number's value.
The typeof 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 typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
The onerror event handler provides three pieces of information to identify the exact nature of the error −
Error message − The same message that the browser would display for the given error.
URL − The file in which the error occurred.
Line number − The line number in the given URL that caused the error.
Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling. Void(0) is used to call another method without refreshing the page.
All variables in the JavaScript are object data types.
‘Typeof’ is an operator which is used to return a string description of the type of a variable.
Blur function is used to remove the focus from the specified object.
Variable typing is used to assign a number to a variable and then assign string to the same variable. Example is as follows:
i= 8;
i=”john”;
There are three types of errors:
Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
Run time errors: Errors that come due to misuse of the command inside the HTML language.
Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.
The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.
onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.
A value can be appended to an array in the given manner – arr[arr.length] = value;
A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.
Anonymous function declaration –
var anon = function() {
alert('I am anonymous');
};
anon();
What is NaN property in JavaScript?
NaN represents the "Not-a-Number" value. It indicates a value that is not a legal number. typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
isNaN(345) // retrunt true
What are arrow functions?
Arrow functions are declared without the function keyword. Arrow functions can only be used as a function expression.
If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function
// Traditional Function Expression
var add = function(a,b){
return a + b;
}
// Arrow Function Expression
var arrowAdd = (a,b) => a + b;
// Traditional function expression
var multiplyBy2 = function(num){
return num * 2;
}
// Arrow function expression
var arrowMultiplyBy2 = num => num * 2;
Differences between declaring variables using var, let and const.
var x1 = 7;
let x2 = 10;
function getValues(){
console.log(x1);
console.log(x2);
// Both the variables can be accessed anywhere since they are declared in the global scope
}
window.x1; // Returns the value 7
window.x2; // Returns undefined
Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName. Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.
Trending Tutorials