Jaquery Javascript
Jaquery Javascript
Number
String
Boolean
Object
Undefined
Example:
document.write("This is \a program");
And if you change to a new line when not within a string statement, then
javaScript ignores break in line.
Example:
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.
<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>
11. What are global variables? How are these variable declared and what
are the problems associated with using them?
Global variables are those that are available throughout the length of the
code, that is, these have no scope. The var keyword is used to declare a local
variable or object. If the var keyword is omitted, a global variable is declared.
Example:
The problems that are faced by using global variables are the clash of variable
names of local and global scope. Also, it is difficult to debug and test the code
that relies on global variables.
A prompt box is a box which allows the user to enter input by providing a text
box. Label and box will be provided to enter the text or number.
Timers are used to execute a piece of code at a set time or also to repeat the
code in a given interval of time. This is done by using the
functions setTimeout, setInterval and clearInterval.
Timers are operated within a single thread, and thus events might queue up,
waiting to be executed.
15. Which symbol is used for comments in Javascript?
/* Multi
Line
Comment
*/
'SessionState' is specific to user specific data that can be accessed across all
pages in the web application.
=== is called as strict equality operator which returns true when the two
operands are having the same value without any type conversion.
document.form[0].submit();
Yes JavaScript does support automatic type conversion, it is the common way
of type conversion used by JavaScript developers
document.getElementById("myText").style.fontSize = "20?;
or
document.getElementById("myText").className = "anyclass";
There are two ways to read and write a file using JavaScript
Sponsored by Simplilearn
For
While
do-while loops
i = 10;
i = "string";
24. How can you convert the string of any base to integer in JavaScript?
In order to convert 4F (of base 16) to integer, the code used will be -
"==" checks only for equality in value whereas "===" is a stricter equality test
and returns false if either the value or the type of the two variables are
different.
Since 3 and 2 are integers, they will be added numerically. And since 7 is a
string, its concatenation will be done. So the result would be 57.
27. Explain how to detect the operating system on the client machine?
The delete keyword is used to delete the property as well as its value.
Example
var student= {age:20, batch:"ABC"};
delete student.age;
31. What are all the types of Pop up boxes available in JavaScript?
Alert
Confirm and
Prompt
Void(0) is used to prevent the page from refreshing and parameter "zero" is
passed while calling.
35. What is the difference between an alert box and a confirmation box?
Example:
Cookies are the small test files stored in a computer and it gets created when
the user visits the websites to store information that they need. Example could
be User Name details and shopping cart information from the previous visits.
The pop() method is similar as the shift() method but the difference is that the
Shift method works at the start of the array. Also the pop() method take the
last element off of the given array and returns it. The array on which is called
is then altered.
Example:
No. JavaScript does not have concept level scope. The variable declared
inside the function has scope inside the function.
They are as –
Primitive
Reference types.
Primitive types are number and Boolean data types. Reference types are
more complex types like strings and dates.
Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}
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";
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 push method is used to add or append one or more elements to the end
of an Array. Using this method, we can append multiple elements by passing
multiple arguments
52. What is unshift method in JavaScript?
Unshift method is like push method which works at the beginning of the array.
This method is used to prepend one or more elements to the beginning of the
array.
Both are almost similar. JavaScript is developed by Netscape and Jscript was
developed by Microsoft .
obj["class"] = 12;
or
obj.class = 12;
55. What is the 'Strict' mode in JavaScript and how can it be enabled?
Strict Mode adds certain compulsions to JavaScript. Under the strict mode,
JavaScript shows errors for a piece of codes, which did not show an error
before, but might be problematic and potentially unsafe. Strict mode also
solves some mistakes that hamper the JavaScript engines to work efficiently.
Strict mode can be enabled by adding the string literal "use strict" above the
file. This can be illustrated by the given example:
function myfunction() {
"use strict";
var v = "This is a strict mode function";
}
alert(document.getElementById('checkbox1').checked);
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.
59. How will you explain closures in JavaScript? When are they used?
For example:
function greet(message) {
console.log(message);
return name + " says howdy!! He is " + age + " years old";
greet(message);
console.log(message);
};
JamesGreeter();
arr[arr.length] = value;
In each repetition, one property from the object is associated to the variable
name, and the loop is continued till all the properties of the object are
depleted.
The function .call() and .apply() are very similar in their usage except a little
difference. .call() is used when the number of the function's arguments are
known to the programmer, as they have to be mentioned as arguments in the
call statement. On the other hand, .apply() is used when the number is not
known. The function .apply() expects the argument to be an array.
The basic difference between .call() and .apply() is in the way arguments are
passed to the function. Their usage can be illustrated by the given example.
var someObject = {
myProperty : 'Foo',
myProperty : 'Bar'
};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'
The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be
used in JavaScript.
This can be done by including the name of the required frame in the hyperlink
using the 'target' attribute.
Break statement is used to come out of the current loop while the continue
statement continues the current loop with a new recurrence.
Both web-garden and web-farm are web hosting systems. The only difference
is that web-garden is a setup that includes many processors in a single server
while web-farm is a larger setup that uses more than one server.
71. What is the method for reading and writing a file in JavaScript?
This can be done by Using JavaScript extensions (runs from JavaScript
Editor), example for opening of a file -
fh = fopen(getScriptPath(), 0);
DOM stands for Document Object Model and is responsible for how various
objects in a document interact with each other. DOM is required for
developing web pages, which includes objects like paragraph, links, etc.
These objects can be operated to include actions like add or delete. DOM is
also required to add extra capabilities to a web page. On top of that, the use
of API gives an advantage over other existing models.
Events are the actions that result from activities, such as clicking a link or
filling a form, by the user. An event handler is required to manage proper
execution of all these events. Event handlers are an extra attribute of the
object. This attribute includes event's name and the action taken if the event
takes place.
By default, the parsing of the HTML code, during page loading, is paused until
the script has not stopped executing. It means, if the server is slow or the
script is particularly heavy, then the webpage is displayed with a delay. While
using Deferred, scripts delays execution of the script till the time HTML parser
is running. This reduces the loading time of web pages and they get displayed
faster.
Load-time errors: The errors shown at the time of the page loading are
counted under Load-time errors. These errors are encountered by the
use of improper syntax, and thus are detected while the page is getting
loaded.
Run-time errors: This is the error that comes up while the program is
running. It is caused by illegal operations, for example, division of a
number by zero, or trying to access a non-existent area of the memory.
Logic errors: It is caused by the use of syntactically correct code, which
does not fulfill the required task. For example, an infinite loop.
Screen objects are used to read the information from the client's screen. The
properties of screen objects are -
This method is functional at the starting of the array, unlike the push(). It adds
the desired number of elements to the top of an array. For example -
For Example:
<script>
document.write(escape("Hello? How are you!"));
</script>
Output: Hello%3F%20How%20are%20you%21
<script>
document.write(unescape("Hello%3F%20How%20are%20you%21"));
</script>
EncodeURl() is used to convert URL into their hex coding. And DecodeURI()
is used to convert the encoded URL back to normal.
<script>
var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br>");
document.write(decodeURI(uri));
</script>
Output -
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab
81. Why it is not advised to use innerHTML in JavaScript?
ECMA Script are like rules and guideline while Javascript is a scripting
language used for web development.
Namespacing is used for grouping the desired functions, variables etc. under
a unique name. It is a name that has been attached to the desired functions,
objects and properties. This improves modularity in the coding and enables
code reuse.
85. How can JavaScript codes be hidden from old browsers that don't
support JavaScript?
Add "<!--" without the quotes in the code just after the <script> tag.
Add "//-->" without the quotes in the code just before the <script> tag.
Old browsers will now treat this JavaScript code as a long HTML comment.
While, a browser that supports JavaScript, will take the "<!--" and "//-->" as
one-line comments.
Java JavaScript
Java code needs to be compiled. JavaScript code are all in the form of text.
Undefined
Null
Boolean
String
Symbol
Number
Object
Less server interaction − You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don’t have to wait for a page reload to see
if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
2 name: "Daniel",
3 age: 23
4 };
1 var x = [];
1 function named(){
3 }
1 function func(x){
2 console.log(typeof x, arguments.length);
}
3
func(); //==> "undefined", 0
4
5 func(7); //==> "number", 7
The JavaScript this keyword refers to the object it belongs to. This has different values
depending on where it is used. In a method, this refers to the owner object and in a
function, this refers to the global object.
Q14. What is Callback?
Q16. Name some of the built-in methods and the values returned by
them.
Built-in Method Values
1. You should not use any of the JavaScript reserved keyword as variable name. For
example, break or boolean variable names are not valid.
2. JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or the underscore character. For example, 123name is an invalid variable name
but _123name or name123 is a valid one.
3. JavaScript variable names are case sensitive. For example, Test and test are two
different variables.
The typeof 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.
Syntax :
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 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.
Explore Curriculum
Property- is the value assigned to the property like type=”text”, value=’Name’ etc.
Q23. List out the different ways an HTML element can be accessed in a
JavaScript code.
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:
Inline
Internal
External
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.
Undefined means a variable has been declared but has not yet been assigned a value.
On the other hand, null is an assignment value. It can be assigned to a variable as a
representation of no value. Also, undefined and null are two distinct types: undefined is
a type itself (undefined) while null is an object.
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:
Angular
React
Vue
Window Document
JavaScript window is a global object which holds The document also comes under the window and ca
variables, functions, history, location. be considered as the property of the window.
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.
Q35. What is NaN in JavaScript?
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.
By Value means creating a COPY of the original. Picture it like twins: they are born
exactly the same, but the first twin doesn’t lose a leg when the second twin loses his in
the war.
By Reference means creating an ALIAS to the original. When your Mom calls you
“Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give birth to a
clone of yourself: you are still one, but you can be called by these two very different
names.
For example-
1 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-
4 return x * x;</span>
}
5
export function diag(x, y) {
6
return sqrt(square(x) + square(y));
7
}
8
9
//------ main.js ------</span>
10
{ square, diag } from 'lib';
11 console.log(square(5)); // 25
12 console.log(diag(4, 3)); // 5
13
Now with this, we have reached the final section of JavaScript Interview Questions.
4(35452)
5(7582)
PYTHON DJANGO TRAINING AND CERTIFICATION
Python Django Training and Certification
Reviews
5(3498)
5(15386)
5(2918)
5(2545)
5(2657)
5(5476)
Next
When you use strict mode, you cannot use implicitly declared variables, or assign a
value to a read-only property, or add a property to an object that is not extensible.
You can enable strict mode by adding “use strict” at the beginning of a file, a program, or
a function.
A prompt box is a box which 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
often used if you want the user to input a value before entering a page. When a prompt
box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering
an input value.
1 var Y = 1;
2 if (function F(){})
{
3
y += Typeof F;</span>
4
}
5
console.log(y);
6
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-
The apply() method calls a function with a given this value, and arguments provided as
an array.
Syntax-
1 fun.apply(thisArg, [argsArray])
Method 1 –
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 –
1 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 –
1 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 –
1 while(arrayList.length)
2 {
3 arrayList.pop();
4 }
The implementation above can also empty arrays, but it is usually not recommended to
use this method often.
1
var Output = (function(x)
2 {
3 Delete X;
4 return X;
5 }
)(0);
6
console.log(output);
7
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.
{
3
delete X.foo;
4
return X.foo;
5
}
6
)();
7
console.log(output);
8
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 is undefined.
1 var Employee =
2 {
3 company: 'xyz'
4 }
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.
3 {
4 return 7;
5 };
typeof Bar();
6
The output would be Reference Error. A function definition can have only one reference
variable as its function name.
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.
1. What is JavaScript(JS)?
JavaScript is a lightweight, interpreted programming language with object-
oriented capabilities that allows you to build interactivity into otherwise static
HTML pages.
Is javascript case-sensitive?
Yes, JavaScript is a case-sensitive language. This means that language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
Which built-in method calls a function for each element in the array?
forEach method calls a function for each element in the array.
Which type of variable among global and local, takes precedence over other if names are same?
A local variable takes precedence over a global variable with the same name.
What is SetTimeout()?
When you setTimeout it becomes asynchronous and it has to wait on the stack
to get everything got finished
<html>
<body>
<p id="studentName"></p>
<script>
document.getElementById("studentName").innerHTML =
</body>
</html>
Q #4) In the following Code snippet can you please predict the output or If you get an
error; please explain the error?
<!DOCTYPE html>
<html>
<body>
<p id="sum_first"></p>
<p id="sum_second"></p>
<script>
</script>
</body>
</html>
Answer: This code will not show any error!
The output of the code snippet here is:
The first variable sum is: 70 Sajeesh Sreeni
The second variable sum is: Sajeesh Sreeni 5020
Q #5) What is the difference between test () and exec () methods?
Answer: Both test () and exec () are RegExp expression methods.
Using test (), we will search a string for a given pattern, if it finds the matching text then it
returns the Boolean value ‘true’ and else it returns ‘false’.
But in exec (), we will search a string for a given pattern, if it finds the matching text then it
returns the pattern itself and else it returns ‘null’ value.
<html>
<body>
<p id="display"></p>
<script>
const first_num;
first_num =1000;
</script>
</body>
</html>
Answer: The ‘const’ variable ’first_num’ is not initialized with a value, so the code will
produce a Syntax Error.
The output of the code snippet here is:
Error: Uncaught SyntaxError: Missing initializer in the const declaration
Q #8) Have you used any browser for debugging? If yes, how is it done?
Answer: By, Pressing ‘F12’ key in the keyboard we can enable debugging in the browser.
Chose the ‘Console’ tab to view the result.
In Console, we can set breakpoints and View the value in variables. All the modern
browsers have a built-in debugger with them (For Example: Chrome, Firefox, Opera, and
Safari). This feature can be turned ON and OFF.
Q #9) What is the use of ‘debugger’ keyword in JavaScript code?
Answer: Using the ‘debugger’ keyword in the code is like using breakpoints in the
debugger.
To test the code, the debugger must be enabled for the browser. If debugging is disabled
for the browser, the code will not work. During debugging the code below should stop
executing, before it goes to the next line.
Range Error We will get this error if we use a number outside the range
Syntax Error This error raises when we use the incorrect syntax. (Please refer Ques No: 7)
Reference Error This error is thrown if used an undeclared variable Please refer Ques No: 19
Eval Error Thrown due to the error in eval(). New JavaScript version doesn’t have this error
Type Error Value is outside the range of types used. Please refer Ques No :22
Basically, where we declared the variable inside the code doesn’t matter much.
Q #12) What is JavaScript ‘Strict Mode’?
Answer: ‘Strict mode’ is a restricted variant of JavaScript.
Usually, JavaScript is ‘not very strict’ in throwing errors.
But in ‘Strict mode’ it will throw all types of errors, even the silent errors. Thus, the process
of debugging becomes easier. And the chances for making mistake for the developer is
reduced.
return () } () ;
Here the last ‘()’ parenthesis in the syntax states that it is a function expression.
<html>
<body>
<script>
(function (){
elem = document.getElementById("dispaly_num");
}());
</script>
</body>
</html>
The function is used to set the text property of <p> tag having ‘display_num’ as Id.
<html>
<body>
<p id="dispaly_num"></p>
<script>
first_num = 100; // Assign value 100 to num
elem = document.getElementById("dispaly_num");
"Since second variable is initialised the value is not taken to the top and it's
value is "
+ "<u>"+second_num +"</u> “;
</script>
</body>
</html>
Please refer previous Ques no: 11, as explained there, the interpreter will take all the
variables declared except initialization to the top.
As per this, ‘first_num’ variable is taken to the top and ‘second_num’ variable is initialized
with a value, so it is not taken to the top. The is code will not throw an error. But the value of
‘second_num’ is undefined.
This method will help in solving compatibility issues and UI issues to an extent.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script> <!--
//-->
</script>
</body>
</html>
Here the code snippet after a <script> tag is executed in my browser as I am not using an
older version of the browser.
<html>
<body>
<p id="display"></p>
<script>
document.getElementById("display").innerHTML = first_num;
result();
</script>
</body>
</html>
Answer: Here in the code given above, the value of the ‘first_num’ variable will not be
1000.
In JavaScript, there is no hoisting for variable initialization. The function ‘result ()’ will
choose the local variable ‘first_num’, as it is declared inside the function. Since the variable
is declared after it is used, the value of ‘first_num’ is undefined.
’var’ keyword was introduced in JavaScript code from ‘let’ keyword is introduced in 2015 only.
the beginning Stage itself.
’Var’ keyword has function scope. The variable A variable declared with ‘let’ keyword has a scop
defined with var is available anywhere within the only with in that block. So, let has a Block Scope
function
The variable declared with ‘var’ be hoisted The variable declared with ‘let’ be hoisted
Q #20) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>
<html>
<body>
<p id="display_first"></p>
<p id="display_second"></p>
<script>
if(true){
let second_num=500;
</script>
</body>
</html>
Answer:
The output of the code snippet here is:
First Number :1000
We will get ‘First Number :1000’ as output. There is an ‘Uncaught Reference Error’ error
also. In the code snippet, the scope of ‘second_num’ is only with in the if() block. If a
developer tries to access the value outside the block, he will get a ‘Uncaught Reference
error’.
Uncaught Reference Error: second_num is not defined.
Q #21) What is the difference between ‘==’ and ‘===’?
Answer:
Both ‘==’ and ‘===’ are comparison operators.
It compares Value, do not compare type It compares both value and type.
Q #22) What is the difference between ‘let’ and ‘const’?
Answer :
let const
using ‘let’ we can change the value of variable using ‘const’, after the first assignment of the value w
any number of times cannot redefine the value again
<html>
<body>
<p id="display_first"></p>
<p id="display_second"></p>
<script>
second_num=1001;
document.getElementById("display_second").innerHTML = "Second
Number :"+second_num;
</script>
</body>
</html>
<html>
<body>
<p id="display_add"></p>
<p id="display_sub"></p>
<script>
function add(first_num,second_num){
var first_num=700;
var second_num=300;
</script>
</body>
</html>
Function declarations are hoisted but function expressions are not hoisted.
Q #26) What are ‘settimeout()’?
Answer: (It better to explain this answer with an example)
Consider the code snippet
Settimeout(function() {
},0);
Even though ‘0’ is the timeout period, it doesn’t mean that it will be executed right away.
return add();
</script>
<html>
<body>
<p id="display"></p>
<script>
var x =500;
let y,z,p,q;
q=200;
if(true){
x=y=z=p=q;
</script>
</body>
</html>
<html>
<body>
<p>Click the button to search for a pattern "How“ in the given string "Hello.
Good Morning. How do you feel today?"</p>
<p>If the "How" is found, the method will return the pattern </p>
<button onclick="searchTxt()">Search</button>
<p id="result"></p>
<script>
function searchTxt() {
</script>
</body>
</html>
Answer: This is an example of the test () and exec () method, Refer Ques No: 5 for more
details.
The output of the code snippet here is:
Found the pattern using exec (): How
Using test () the result is: true
Q #30) Can you give an example showing JavaScript Hoisting?
Answer:
<!DOCTYPE html>
<html>
<body>
<p id="dispaly_num"></p>
<script>
elem = document.getElementById("dispaly_num");
</body>
</html>
Here the variable ‘num’ is used before declaring it. But JavaScript Hoisting will allow it.
<html>
<head>
</head>
<body>
<p> Here to test the code, debugger must be enabled for the browser,
<br>during debugging the code below should stop executing before it goes to
the next line. </p>
<p id="wait_result"></p>
<p id="show_result"></p>
<script>
var a = 1000;
var b = 500;
var sum = a + b;
document.getElementById("wait_result").innerHTML = "Adding
numbers......<br>
debugger;
</script>
</body>
</html>
Note: The debugger must be enabled for the browser to test the code. Refer Ques No: 5 for
more details
This is an example of debugging keyword (Browser used: Chrome)
The output of the code snippet here is:
Here to test the code, the debugger must be enabled for the browser,
during debugging the code below should stop executing before it goes to the next line.
Adding numbers…
Select ‘Resume Script execution' to continue:
<Click on ‘Resume Script execution’ Button>
Sum of the numbers: 1500
Q #32) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var first_name='500';
if(first_num == first_name){
</script>
</body>
</html>
Here
typeof(‘100’) is string
typeof(100) is number
the ‘==’ operator will convert the number type, which is on the right side of the
operator to string and compare both values
2 Java is based on Object-Oriented JavaScript is both an object-oriented as well as a
Programming (OOPS)concepts. functional scripting.
4 Java code needs to get compiled as Java JavaScript has no compilation step.
class file. Instead, an interpreter in the browser reads over the
JavaScript code , interprets each line, and runs it.
So, in short, these languages are not at all linked with or dependent on each other.
var y = 3;
For Example,
var x = 2;
var y = 3;
If(x<y){
alert(‘Hi’);
If the above condition ‘x<y’ is true, the alert gets pop up.
Also, the Boolean object can be created using the new operator as follows:
var myobj = new Boolean(true);
#2) Null:
This is a data type that is represented by only one value, the ‘null’ itself. A null value means
no value.
For Example,
var x = null;
#3) Undefined:
This data type means a variable that is not defined. The variable is declared but it does not
contain any value.
For Example,
var x;
x=10;//Assign value to x
The variable ‘a’ has been declared but hasn’t been assigned a value yet.
We can assign a value to a:
#4) Number:
This data type can be a floating-point value, an integer, an exponential value, a ‘NaN’ or an
‘Infinity’.
For Example,
var x=10; // This is an integer value
Also, number object can be created using the ‘new’ operator as follows:
var x= new Number(10);
For Example,
const x = 15n;
const y = BigInt(x);
#6) String:
This data type is used to represent textual data.
For Example,
var strVar1 = “Hi,how are you?”;
JavaScript strings are immutable i.e. once a string is created, it can’t be modified. But
another string can be created using an operation on the original string.
For example:
By concatenating two strings using the concatenation operator (+) or String.concat().
By getting substring using String.substr().
#7) Symbol:
This is a unique and immutable primitive value and used as the key of an Object property.
Symbols are new to JavaScript in ECMAScript 2015
A Symbol value represents a unique identifier.
For example,
var symVar1 = Symbol("Symbol1");
So, many symbols are created with the same description, they are different values.
For example,
var symVar1 = Symbol("Symbol1");
Object refers to a data structure having data and instructions to work with the data. Objects
sometimes refer to real-world things, For example, an employee or a car.
For Example,
In JavaScript objects, values are written as name:value pairs as below:
var car1 = {type:"BMW", model:” The BMW X5“, color:"white"};
var car1 = {
type:"BMW",
color:"white"
};
or objectName[“propertyName”]
car1.type = “Audi”;
Now,
For Example,
console.log (typeof 10);// expected output: "number"
For Example,
Var myvar = null;
if (isNaN(x)) {
return NaN;
return x;
myDaysArray= myDaysString.split(',');
case choice1:
code to be run
break;
case choice2:
code to be run
break;
default:
For Example,
if (some condition)
else
Same code can be written using a ternary operator in a single statement as follows:
result = (condition)?‘result 1’:‘result 2’;
Q #45) Suppose, there is an object called a person
const person = {
name : {
first: ‘Bob',
last: ‘Smith'
}
};
Which of the following is correct way of accessing the object property ‘first' ?
person.name.first
or
person[‘name'][‘first'] ?
Answer: Both are correct ways. i.e. using dots like person.name.first or using bracket
notation like person[‘name'][‘first']
Q #46) What is “this”?
Answer: The ‘this' keyword refers to the current object the code is being written inside.
This is to ensure that the correct values are used when a member's context changes
For Example, there are two different instances of a person having different names and it is
required to print their own name in the alert as follows:
const person1 = {
name: 'Tom',
greeting: function() {
name: 'Jerry',
greeting: function() {
}
Here, the output is Good Morning! I am ‘Jerry'
Q #47) What are Anonymous functions?
Answer: Anonymous functions are functions without having any name and won't do
anything on their own. These are generally used along with an event handler.
For example, in the following code, anonymous function code i.e. alert(‘Hi'); would run on
click of the associated button:
var myButton = document.querySelector('button');
myButton.onclick = function() {
alert('Hi');
Javascript
Javascript is an object-oriented computer programming language commonly used to
create interactive effects within web browsers.It is first used by the Netscape browser,
that provides access to the HTML document object model (DOM), provides access to
the browser object model (BOM). Javascript syntax looks a lot like java, c or c++ syntax.
Undefined
Null
Boolean
String
Symbol
Number
Object
In Javascript close() method is used to close the current window. You must write
window.close() to ensure that this command is associated with a window object and not
some other JavaScript object.
Both var and let are used for variable/ method declaration in javascript but the main
difference between let and var is that var is function scoped whereas let is block
scoped.
Closures are the combination of lexical environment and function within which the
function was declared. This allows JavaScript programmers to write better, more
creative, concise and expressive codes. The closure will consist of all the local variables
that were in-scope when the closure was created.
Sure, closures appear to be complex and beyond the scope, but after you read this
article, closures will be much more easy to understand and more simple for your
everyday JavaScript programming tasks. JavaScript is a very function-oriented
language it gives the user freedom to use functions as the wish of the programmer.
In JavaScript, there is some cool stuff that makes it the best of all. One of them is
Delegation Model. When capturing and bubbling, allow functions to implement one
single handler to many elements at one particular time then that is called event
delegation. Event delegation allows you to add event listeners to one parent instead of
specified nodes. That particular listener analyzes bubbled events to find a match on the
child elements. Many people think it to be complicated but in reality, it is very simple if
one starts understanding it.
JavaScript’s default behavior that allows moving declarations to the top is called
Hoisting. The 2 ways of creating functions in JavaScript are Function
Declaration and Function Expression. Let’s find out more about these:
Function Declaration
A function with the specific parameters is known as function declarations. To create a
variable in JavaScript is called declarations.
e.g:
function hoisted() {
console.log('foo');
}
Function Expression
e.g:
console.log('bar');
};
In modern javascript let & const are different ways of creating variables. Earlier in
javascript, we use the var keyword for creating variables. let & const keyword is
introduced in version ES6 with the vision of creating two different types of variables in
javascript one is immutable and other is mutable.
const: It is used to create an immutable variable. Immutable variables are variables
whose value is never changed in the complete life cycle of the program.
let: let is used to create a mutable variable. Mutable variables are normal variables like
var that can be changed any number of time.
An arrow function is a consise and short way to write function expressions in Es6 or
above.A rrow functions cannot be used as constructors and also does not supports this,
arguments, super, or new.target keywords. It is best suited for non-method functions. In
general an arrow function looks like const function_name= ()=>{}
const greet=()=>{console.log('hello');}
greet();
//index.js
console.log(name);
console.log(age);
//person.js
The module is a plain JavaScript object with an exports property. Exports is a plain
JavaScript variable that happens to be set to module.exports. At the end of your file,
node.js will basically ‘return’ module.exports to the require function. A simplified way to
view a JS file in Node could be this:
// your code
return module.exports;
If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well
because objects are passed around as references in JavaScript, which means that if
you set multiple variables to the same object, they are all the same object; so then
exports and module.exports are the same objects.
But if you set exports to something new, it will no longer be set to module.exports, so
exports and module.exports are no longer the same objects.
Source : https://stackoverflow.com/questions/16383795/difference-between-module-
exports-and-exports-in-the-commonjs-module-system
Example:
objectname.member1;
objectname.member2;
objectname.memberfunc();
“use strict” is a javascript directive that is introduced in Es5. The purpose of using “use
strict” directive is to enforce the code is executed in strict mode. In strict mode we can’t
use a variable without declaring it. “use strict” is ignored by earlier versions of
Javascript.
Event Capture and Bubbling: In HTML DOM API there are two ways of event
propagation and determines the order in which event will be received. The two ways are
Event Bubbling and Event Capturing. The first method event bubbling directs the event
to its intended target, and the second is called event capture in which the event goes
down to the element.
Event Capture
The capture procedure is rarely used but when it’s used it proves to be very helpful.
This process is also called ‘trickling’. In this process, the event is captured first by the
outermost element and then propagated to the innermost element. For example:
<div>
<ul>
<li></li>
</ul>
</div>
From the above example, suppose the click event did occur in the ‘li’ element, in that
case capturing event it will be first handled ‘div’, then ‘ul’ and at last the target element
will be hit that is ‘li’
Event Bubbling
Bubbling just works like the bubbles, the event gets handled by the innermost element
and then propagated to the outer element.
<div>
<ul>
<li></li>
</ul>
</div>
From the above example, suppose the click event did occur in the ‘li’ element in
bubbling model the event will be handled first by ‘li’ then by ‘ul’ and at last by ‘div’
element.
NO, calculations with fractional numbers are not guaranteed to be precise in Javascript
In Javascript variable are declared using the var keyword.A variable must begin with
A letter, $ or _.
onclick
ondblclick
mousemove
mousedown
mouseover
mouseout
mouseup
Example Usage:-
var myString="JavascriptQuestions";
console.log(myString.length-1);
21) How to get the primitive value of a string in Javascript?
Example Usage:
A primitive is a basic data type that’s not built out of other data types. It can only
represent one single value. All primitives are built-in data types by necessity, (the
compiler has to know about them,) but not all built-in data types are primitives.
Example Usage
BOM stands for “Browser Object Modal” that allows Javascript to ‘talk’ to the browser,
no standards, modern browsers implement similar BOMS – window, screen, location,
history, navigator, timing, cookies.
Alert
Confirm
Prompt
By array literal
usage:
var myArray=[value1,value2...valueN];
27) What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict mode is a way to introduce better error-checking into your code. When you use
strict mode, you cannot, for example, use implicitly declared variables, or assign a value
to a read-only property, or add a property to an object that is not extensible.
You can enable strict mode by adding “use strict”; at the beginning of a file, a
program, or a function. This kind of declaration is known as a directive prologue. The
scope of a strict mode declaration depends on its context. If it is declared in a global
context (outside the scope of a function), all the code in the program is in strict mode. If
it is declared in a function, all the code in the function is in strict mode.
28) How to calculate Fibonacci numbers in JavaScript?
function fib(n) {
var a=0, b=1;
for (var i=0; i < n; i++) {
var temp = a+b;
a = b;
b = temp;
}
return a;
}
29) What is the difference between the substr() and substring() functions
in JavaScript?
var s = "hello";
( s.substr(1,4) == "ello" ) // true
The substring() function has the form substring(startIndex,endIndex). It returns the
substring from startIndex up to endIndex – 1.
var s = "hello";
( s.substring(1,4) == "ell" ) // true
There are two types of Inherientence in OOPS Classic and Prototypical Inheritance. Javascript
follows Prototypical Inheritance.
Example:
Usage:
Example Usage:
<script type="text/javascript">
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // This is inner Element
document.getElementById("inner").innerHTML = "Html changed!";
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // Html changed!
</script>
Syntax document.getElementsByClassName('className')
In Programming whenever we need to convert a variable from one data type to another
Typecasting is used. In Javascript, we can do this via library functions. There are
basically 3 typecasts are available in Javascript Programming, they are:
Example usage
Deep copy means copies all values or properties recursively in the new object whereas
shallow copy copies only the reference.
In a deep copy, changes in the new object don't show in original object whereas, in
shallow copy, changes in new objects will reflect in the original object.
In a deep copy, original objects do not share the same properties with new object
whereas, in shallow copy, they do.
Below is the list of few most Popular Javascript Unit Testing Frameworks:
Unit.js
Jasmine
Karma
Chai
AVA
Mocha
JSUnit
QUnit
Jest
It is easy to add a new property in existing function by just giving value to the existing
function it. For example, let we have an existing object person, to give new property
check the below code:
person.country= “India”;
JavaScript Accessors
45) List few difference between primitive and non primitive JavaScript
data types?
The primitive data types are numbers, strings, Boolean, undefined, null and anything
other than these data types are known as non-primitive such as objects and functions.
Primitive data types are immutable while non-primitives are mutable.
Primitives are known immutable as they can't be changed once they created but non-
primitive are changeable, means once an object is created, it can be changed.
Primitives data types are compared with their values, it means two values are strictly
equal if they have the same data type and holds the same value.
Non-primitives are not compared with values. For example, if two objects have the same
properties and values, they are strictly not equal.
Null, Undefined are primitive data types whereas Undeclared is not a primitive data
type.
48) How host objects are different from native objects in JavaScript?
Host objects: These are those objects which environment gives. It means they are
different for different environments. For example, browsers include objects such as
windows but Node.js environments give objects such as Node List.
Native Objects: these are built-in objects in JavaScript. They are also known as Global
Objects because they will be available to you independent of ay environment if you
working in JavaScript.
For example:
console.log(newarray);
// [1, 2, 3, 4, 5, 6]
In above example, instead of appending mid array, it rather expands in the newarray
with the help of spread operator. This is how spread operator works in JavaScript.
There are many ways to remove duplicates from JavaScript array. These are described
below with examples:
function uniquearray(array) {
let unique_array= Array.from(set(array))
return unique_array;}
As in the above code, you created a set of an array which automatically eliminates the
duplicate values.
Milliseconds: required parameter which tells how often the function will execute.
In the above example, this function calls hello function in very 3 seconds.
A promise is an object in JavaScript which is used to produce a value that may give
results in the future. The value can be resolved value or it can be a reason which tells
why the value is not resolved.
The array.slice() removes items from the array and then return those removed items as
an array whereas array.slice() method is selected items from an array and then those
elements as a new array object.
The splice() method affects the original array whereas slice() method doesn’t affect the
original array.
Splice() method takes n number of arguments whereas slice() can take only two
arguments.
JavaScript is single-threaded.
1. Creational design pattern: These patterns dealt with the mechanism of object creation
which optimize object creation with the basic approach.
2. Structural design pattern: these patterns deal with different classes and objects to
provide new functionality.
3. Behavioral Patterns: These patterns are to improve communication between objects
and to recognize patterns.
4. Concurrency design patterns: These patterns handle with multi-thread programming
paradigms.
5. Architectural design patterns: These patterns used to deal with architectural designs.
The scope chain in JavaScript is basically used to resolve the values of the variable.
Without this, it is difficult for a JavaScript to choose a certain value for a variable if there
are many variables defined at different scopes.
We can use array.indexOf method to check a value exists or not. See below example to
remove duplicate values.
function removeDuplicatesValues(arr){
let unique_array = [];
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
console.log(removeDuplicatesValues(duplicates));
There are several ways to redirect page to another page in JavaScript. These are:
1. Using location.href: It is the first approach to redirect page. In this, we can go back to
access the original document. Syntax:window.location.href
=“https://www.onlineinterviewquestions.com/”
2. Using location.replace: Another approach to redirect page. In this, it is not possible to
navigate back to the original document by clicking on the back button as it removes the
URL of the original document. Syntax: window.location.replace("
https://www.onlineinterviewquestions.com/;");
Using in-built functions: the inbuilt function reverse() reverses the string directly.
Here’ how:
str="jQuery";
str = str.split(""); //convert 'jQuery' to array
str = str.reverse(); //reverse 'jQuery' order
str = str.join(""); //then combines the reverse order values.
alert(str);
First split the string to an array, then reverse an array and after that join the characters
to form a string.
MUL means simple multiplication of numbers. It is a techique in which you pass a one
value as an argument in a function and that function returns another function to which
you pass the second value and the process go on. For example: x*y*z can be
representing as:
70) Please explain equality operators in JavaScript?
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 a different operation.
1. Global Scope
2. Local Scope
o Block Scope
o Function Scope
1. let gives you the privilege to declare variables that are limited in scope to the
block, statement of expression unlike var.
2. var is rather a keyword which defines a variable globally regardless of block
scope.
The both are very similar when used like the following, outside a function block.
code
source
Key Points:
1. 'use strict';
2.
3. let x = 'Hi, FullStackTutorials';
4.
5. let x = 'Hello, FullStackTutorials'; // SyntaxError: Identifier 'x' has
already been declared
6.
code
source
1. 'use strict';
2.
3. var y = 'Hi, FullStackTutorials';
4.
5. var y = 'Hello, FullStackTutorials'; // No problem, 'y' is replaced.
6.
1. function myFunc(name) {
2.
3. return `Hello ${name}, Welcome to Advanced JavaScript Interview Questions`;
4.
5. }
6.
7. console.log(myFunc("User"));
8.
9.
10.
11. //Output
12.
13. Hello User, Welcome to Advanced JavaScript Interview Questions
14.
Function Expression:
A function expression can be stored in a variable and the variable can be used as a
function
code
source
code
source
1. (function () {
2.
3. statements
4.
5. })();
6.
Example
code
source
variables and function declarations are moved to the top of their scope before code
execution.
In JavaScript, a variable can be declared after it has been used. In other words, a
variable can be used before it has been declared.
code
source
x = 5; console.log(x); // Output: 5
var x;
code
source
var x = 5;
2.
4.
var y = 10;
6.
7.
8.
code
source
2.
4.
6.
code
source
function myFunc(){
2.
4.
6.
Shorter Syntax
No binding of this
code
source
//Regular Function
2.
function myFunc(){
4.
6.
//Arrow Function
12.
14.
16.
18.
Unlike a regular function, an arrow function does not bind this. Instead, this is
bound lexically (i.e. this keeps it's meaning from its original context).
An arrow function does not have its own this. this value of the enclosing lexical
scope is used by arrow functions. So if this is not present in current scope, an
arrow function ends up looking into lexical scope.
code
source
2.
3.
4.
var TV = {
6.
8.
Price: "15000",
10.
Color: "Black",
12.
14.
// Code Snippet
16.
},
18.
20.
22.
23. }
24.
26.
Object Literals
Object Constructor
Object.create Method
using Function
using Class
Object Literals:
code
source
let obj = {}
2.
code
source
let person = {
2.
name: "FullStackTutorials",
4.
getName: function() {
6.
return this.name;
8.
10.
11. };
12.
Object Constructor:
code
source
2.
person.name = "FullStackTutorials",
4.
person.getName = function(){
6.
return this.name ;
8.
};
10.
Object.create()
code
source
2.
4.
code
source
let data = {
2.
name: "FullStackTutorials",
4.
getName: function() {
6.
return this.name;
8.
10.
11. };
12.
14.
Using Function:
code
source
function Person(name){
2.
this.name = name
4.
this.getName = function(){
6.
return this.name
8.
10.
11. }
12.
13.
14.
16.
console.log(obj);
18.
code
source
2.
3.
4.
function Person(name) {
6.
this.name = name;
8.
10.
Person.prototype.getName = function() {
12.
return this.name;
14.
};
16.
Using Class:
code
source
class Person {
2.
constructor(name, age) {
4.
this.name = name;
6.
this.age = age;
8.
}
10.
getInfo() {
12.
14.
16.
18.
20.
code
source
let Person = {
2.
age : 21,
4.
getIntro: function () {
6.
8.
}
10.
};
12.
14.
16.
18.
personObj1.getIntro();
20.
21.
22.
24.
25. personObj2.getIntro();
26.
27.
28.
29. //Output
30.
32.
34.
code
source
2.
4.
person1.getName = function(){
6.
return this.name ;
8.
};
10.
11.
12.
14.
16.
person2.age = 25,
18.
person2.getName = function(){
20.
return this.name ;
22.
23. };
24.
25.
26.
console.log(person1);
28.
console.log(person2);
30.
31.
32.
33. //Output
34.
36.
38.
Primitives data types like strings and numbers are compared by their value, while
objects like arrays, dates, and plain objects are compared by their reference.
The comparison by reference basically checks to see if the objects given refer to the
same location in memory.
code
source
var a = {};
2.
var b = {};
4.
var c = a;
6.
7. console.log(a==b); //false
8.
9. console.log(a===b); //false
10.
12.
14.
A closure is a feature in JavaScript where an inner function has access to the outer
(enclosing) function's variables.
It has access to it's own scope i.e. variables defined between its curly
brackets.
code
source
function outer() {
2.
var a = 10;
4.
function inner() {
6.
var b = 20;
8.
console.log(a+b);
10.
12.
14.
16.
code
source
2.
setTimeout(() => {
4.
5. console.log(i);
6.
}, 1000);
8.
10.
11.
12.
13. //Output
14.
(5) 5
16.
Closure
let
Closure It creates a unique scope for each iteration, storing each unique value of
the variable within it's scope.
code
source
2.
(function(x) {
4.
5. setTimeout(() => {
6.
console.log(x);
8.
}, 1000);
10.
})(i);
12.
14.
15. //Output
16.
18.
20.
22.
24.
25. 4
26.
code
source
2.
setTimeout(() => {
4.
5. console.log(i);
6.
}, 1000);
8.
10.
11.
12.
//Output
14.
16.
18.
20.
21. 3
22.
24.
Reason: let has block level scope so variable i is only seen in the for loop's block
scope.
code
source
2.
4.
5. callback();
6.
}
8.
function alertFinished(){
10.
alert('Finished my homework');
12.
14.
16.
JavaScript is an event driven language. This means that instead of waiting for a
response before moving on, JavaScript will keep executing while listening for other
events.
Callbacks are a way to make sure certain code doesn't execute until other code has
already finished execution.
In JavaScript, objects have a special hidden property [[Prototype]] (as named in the
specification), that is either null or references another object. That object is
called "Prototype".
That [[Prototype]] has a "magical" meaning. When we want to read a property from
object, and it’s missing, JavaScript automatically takes it from the prototype. In
programming, such thing is called "prototypal inheritance"
The property [[Prototype]] is internal and hidden, but there are many ways to set it.
via __proto__or Object.getPrototypeOf // old-way
obj.__proto__
// new-way
Object.getPrototypeOf(obj)
The __proto__ is considered outdated and somewhat deprecated (in browser-only part of
the Javascript standard).
code
source
2.
4.
6.
7.
8.
10.
12.
16.
Promise States:
code
source
2.
const A = "fullstacktutorials";
4.
5. const B = "fullstacktutorials"
6.
if(A === B) {
8.
resolve();
10.
} else {
12.
reject();
14.
16.
});
18.
19.
20.
21. promise.
22.
then(function () {
24.
26.
}).
28.
catch(function () {
30.
33. });
34.
code
source
2.
4.
6.
8.
} else {
10.
12.
14.
})
16.
return p
18.
}
20.
21.
22.
23. compareToTen(15)
24.
26.
28.
29.
30.
compareToTen(8)
32.
34.
36.
apply():
The apply() method calls a function with a given this value, and arguments provided
as an array.
call():
The call() method calls a function with a given this value and arguments provided
individually
source
2.
4.
5. }
6.
7. myFunction("John", "Developer");
8.
10.
12.
13.
14.
//Output:
16.
18.
20.
22.
23.
24.
bind():
bind allows you to set the this value now while allowing you to execute the function
in the future, because it returns a new function object.
The spread operator (…) is a new operator introduced in ES6. It allows the expansion
of an iterable (e.g., Array) into its constituent elements.
code
source
2.
4.
5.
6.
7. console.log(finalArr);
8.
10.
code
source
2.
3.
4.
5. function removeDuplicates(array) {
6.
8.
10.
11.
12.
14.
After we have done that, we simply convert the Set back to an array by using the
spread operator.
code
source
2.
4.
8.
uniqueNames.push(el);
10.
12.
13. });
14.
16.
Lightweight: JavaScript can be executed within the user’s browser without having to
communicate with the server, saving on bandwidth.
Speed: Client-side JavaScript is very fast because it can be run immediately within
the client-side browser.
Rich Interfaces: From drag-and-drop blocks to stylized sliders, there are numerous
ways that JavaScript can be used to enhance a website’s UI/UX.
Prototypal Inheritance: Objects can inherit from other objects, which makes
JavaScript so simple, powerful, and great for dynamic applications.
Platform Independent: JavaScript is platform independed language. Any JavaScript-
enabled browser can understand and interpreted JavaScript code.
As the name suggests, these patterns are for handling object creational mechanisms.
Constructor pattern
Factory pattern
Prototype pattern
Singleton pattern
This pattern helps to obtain new functionalities without tampering with the existing
ones.
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
These patterns are concerned with improving communication between dissimilar objects
Iterator pattern
Observer pattern
Template pattern
Strategy pattern
State pattern
Command pattern
No, JavaScript does not support overloading!. JavaScript supports overriding not
overloading.
code
source
2.
return n1 + n2 + n3;
4.
6.
8.
return n1 + n2;
10.
12.
14.
15. console.log(sum); // 5
16.
If you will define two or more functions with the same name, the last one will
override the previously defined functions and when a call will be made to the
function, the last defined function will get executed.
Yes, it's true. since null is a primitive datatype still typeof null return object.
code
source
2.