Interview Questions of Javascript

Javascript interview questions

What is javascript?+

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.


What is the difference between undefined and not defined in JavaScript?

What is the difference between undefined and not defined in JavaScript?+

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


What will be the output of the code below?
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);

What will be the output of the code above? +

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


What is a “closure” in JavaScript? Provide an example

What is a “closure” in JavaScript? Provide an example +

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


Write a mul function which will produce the following outputs when invoked:

javascript console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48

Write a mul function which will produce the following outputs when invoked +

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


How to empty an array in JavaScript ?

For instance,

var arrayList = ['a','b','c','d','e','f'];

+

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 []


What will be the output of the following code?

var output = (function(x){
delete x;
return x;
})(0);

console.log(output);

What will be the output of the following code?+

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.


What will be the output of the following code?

var x = 1;
var output = (function(){
delete x;
return x;
})();

console.log(output);

What will be the output of the following code? +

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.


What will be the output of the code below?

var x = { foo : 1};
var output = (function(){
delete x.foo;
return x.foo;
})();

console.log(output);

What will be the output of the code below?+

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.


What is the difference between the function declarations below?

var foo = function(){
// Some code
};
function bar(){
// Some code
};

What is the difference between the function declarations above? +

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>


What is the difference between JavaScript and jscript?

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.


Is JavaScript case sensitive language?

Is JavaScript case sensitive language? +

Yes.


What is BOM?

What is BOM? +

BOM stands for Browser Object Model. It provides interaction with the browser. The default object of browser is window.


What is DOM? What is the use of document object?

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.


What is the use of window object?

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.


What is the use of history object?

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.


What are the JavaScript data types?

What are the JavaScript data types?+

There are two types of data types in JavaScript:
Primitive Data Types
Non-primitive Data Types


What is the difference between == and ===?

What is the difference between == and ===? +

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.


What is the difference between var and let?

What is the difference between var and let? +

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.


How to write html code dynamically using JavaScript?

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="<h2>This is heading using JavaScript</h2>";


How to write normal text code using JavaScript dynamically?

How to write normal text code using JavaScript dynamically? +

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";


What is the output of 10+20+"30" in JavaScript?

What is the output of 10+20+"30" in JavaScript?+

3030 because 10+20 will be 30. If there is numeric value before and after +, it is treated is binary + (arithmetic operator).


What is the output of "10"+20+30 in JavaScript?

What is the output of "10"+20+30 in JavaScript?+

102030 because after a string all the + will be treated as string concatenation operator (not binary +).


What is the real name of JavaScript?

What is the real name of JavaScript? +

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="

This is heading using JavaScript

"; More details... 15) How to write normal text code using JavaScript dynamically? 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"; More details... 16) How to create objects in JavaScript? There are 3 ways to create object in JavaScript. By object literal By creating instance of Object By Object Constructor Let's see a simple code to create object using object literal. emp={id:102,name:"Rahul Kumar",salary:50000} More details... 17) How to create array in JavaScript? There are 3 ways to create array in JavaScript. By array literal By creating instance of Array By using an Array constructor Let's see a simple code to create array using object literal. var emp=["Shyam","Vimal","Ratan"]; More details... 18) What does the isNaN() function? The isNan() function returns true if the variable value is not a number. 19) What is the output of 10+20+"30" in JavaScript? 3030 because 10+20 will be 30. If there is numeric value before and after +, it is treated is binary + (arithmetic operator). 20) What is the output of "10"+20+30 in JavaScript? 102030 because after a string all the + will be treated as string concatenation operator (not binary +). 21) Difference between Client side JavaScript and Server side JavaScript? Client side JavaScript comprises the basic language and predefined objects which are relevant to running java script in a browser. The client side JavaScript is embedded directly by in the HTML pages. This script is interpreted by the browser at run time. Server side JavaScript also resembles like client side java script. It has relevant java script which is to run in a server. The server side JavaScript are deployed only after compilation. 22) In which location cookies are stored on the hard disk? The storage of cookies on the hard disk depends on OS and the browser. The Netscape navigator on Windows uses cookies.txt file that contains all the cookies. The path is : c:\Program Files\Netscape\Users\username\cookies.txt The Internet Explorer stores the cookies on a file username@website.txt. The path is: c:\Windows\Cookies\username@Website.txt. 23) What is the real name of JavaScript? The original name was Mocha, a name chosen by Marc Andreessen, founder of Netscape. In September of 1995, the name was changed to LiveScript. In December 1995, after receiving a trademark license from Sun, the name JavaScript was adopted.


What is the difference between undefined value and null value?

What is the difference between undefined value and null value?+

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.


How to set the cursor to wait in JavaScript?

How to set the cursor to wait in JavaScript?+

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>


What is this? var myArray = [[[]]];

What is this? var myArray = [[[]]]; +

Three dimensional array.


What is difference between View state and Session state?

What is difference between View state and Session state? +

"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.


How to submit a form using JavaScript by clicking a link?

How to submit a form using JavaScript by clicking a link?+

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>


How to change the background color of HTML document using JavaScript?

How to change the background color of HTML document using JavaScript? +

<script type="text/javascript">
document.body.bgColor="pink";
</script>


Consider the two functions below. Will they both return the same thing? Why or why not?

function foo1()
{
return {
bar: "hello"
};
}

function foo2()
{
return
{
bar: "hello"
};
}

Consider the two functions below. +

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


How can you create an Object in JavaScript?

How can you create an Object in JavaScript? +

JavaScript supports Object concept very well. You can create an object using the object literal as follows −

var emp = {
name: "Zara",
age: 10
};


What are the different objects used in JavaScripts?

What are the different objects used in JavaScripts? +

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.


What are the different types of errors supported by JavaScript?

What are the different types of errors supported by JavaScript?+

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.


What is difference between undefined variable and undeclared variable?

What is difference between undefined variable and undeclared variable?+

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>


What is encodeURI() function?

What is encodeURI() function? +

- 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>


What is the disadvantages using innerHTML in JavaScript?

What is the disadvantages using innerHTML in JavaScript?+

- 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.


What is decodeURI() function?

What is decodeURI() function? +

- 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.


What is the difference between window.onload and onDocumentReady?

What is the difference between window.onload and onDocumentReady?+

- 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.


How to change style on an element?

How to change style on an element?+

- 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");


How can you create an Array in JavaScript? +

You can define arrays using the array literal as follows −

var x = [];
var y = [1, 2, 3, 4, 5];


How to read elements of an array in JavaScript? +

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]
}


What is a named function in JavaScript? How to define a named function?+

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
}


How many types of functions JavaScript supports? +

A function in JavaScript can be either named or anonymous.


How to define a anonymous function? +

An anonymous function can be defined in similar way as a normal function but it would not have any name.


Can you assign a anonymous function to a variable? +

Yes! An anonymous function can be assigned to a variable.


Can you pass a anonymous function as an argument to another function?+

Yes! An anonymous function can be passed as an argument to another function.


How can you get the type of arguments passed to a 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


How can you get the total number of arguments passed to a function? +

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


What is the purpose of 'this' operator in JavaScript? +

JavaScript famous keyword this always refers to the current context.


Which built-in method removes the last element from an array and returns that element? +

pop() method removes the last element from an array and returns that element.


Which built-in method adds one or more elements to the end of an array and returns the new length of the array?+

push() method adds one or more elements to the end of an array and returns the new length of the array.


Which built-in method returns the string representation of the number's value? +

toString() method returns the string representation of the number's value.


How typeof operator works?+

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.


What is purpose of onError event handler in JavaScript? +

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.


What is the use of Void(0)?

What is the use of Void(0)? +

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.


What is the data type of variables of in JavaScript?+

All variables in the JavaScript are object data types.


What is the use of type of operator?+

‘Typeof’ is an operator which is used to return a string description of the type of a variable.


What is the use of blur function? +

Blur function is used to remove the focus from the specified object.


What is variable typing?+

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”;


What are the different types of errors in JavaScript?+

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.


Explain window.onload and onDocumentReady? +

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.


How can a value be appended to an array?+

A value can be appended to an array in the given manner – arr[arr.length] = value;


Describe the properties of an anonymous function in JavaScript? +

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?

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?

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.

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.


+


+


+


+


+


+


+


+


+


+


+


+


+


+


Output :-






Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here