Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREJavaScript is a high-level, dynamic, object-oriented programming language that adds interactivity and functionality to web pages, allowing users to interact with web content in a more dynamic and responsive way. Apart from Web Development, it is also used for server-side programming and desktop application development. You can stay in the know with the frequently asked JavaScript interview questions with answers that will help you crack your next JavaScript interview and land your dream career as a JavaScript Developer. We have compiled questions on important JavaScript topics such as Closure, Event bubbling, Capturing, and Template Strings in ES6, meant for beginners, intermediate and expert professionals at the same time. Take your JavaScript proficiency to the next best level well with these expert-curated JavaScript interview questions and answers. Let us get started with the questions and answers.
Filter By
Clear all
Let’s first understand what is an compiled language and interpreted language.
gcc hello.c -o hello
If no error it will generate an executable “hello” and we will run it by:
./hello
python hello.py
The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.
However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.
Let consider the below example. The compilation steps mainly looks at the var keyword. It is not bothered with what is assigned in these variables.
var a = 10; var b = 20; console.log(a+b)
When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.
For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it. Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”.
Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.
The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser.
The variables "let” and “const” were introduced recently in ES6(In 2015). There were some design mistakes made with “var” and these were rectified with “let” and “const”.
The problem is that “var” is function scoped and it causes a lot of problems.
Consider the below example where we are using “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.
for(var i=0; i<5; i++) { console.log(i); //Output- 0 1 2 3 4 } i = i + 2; console.log(i); //Output- 7
Since, “var” is function scope so we can put our “for” loop inside a function and then “i” won’t be accessible outside.
function incrementI() { for(var i=0; i<5; i++) { console.log(i); } } incrementI(); //Output- 0 1 2 3 4
i = i + 2; console.log(i);
//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:9:1 */
Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.
The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.
for(let i=0; i<5; i++) { console.log(i); //Output- 0 1 2 3 4 } i = i + 2; console.log(i);
//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:6:1 */
We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like integers and strings.
const c = 12; c = 14; console.log('c is ', c);
/*
Exception: TypeError: invalid assignment to const `c'
@Scratchpad/6:2:1
*/
But can add or update values for non-primitive like arrays and objects.
const arr = [1, 2, 3]; arr.push(4); console.log('arr is ', arr); // [ 1, 2, 3, 4 ] const obj = { name: 'Robin', skill: 'JS' }; obj.skill = 'React'; obj.profession = 'Developer'; console.log('obj is ', obj); // { name: "Robin", skill: "React", profession: "Developer" }
This is one of the most frequently asked JavaScript interview questions for freshers in recent times.
JavaScript has both strict and type-converting equality comparison. For strict comparison we use === and for type-converting comparison we use == . Let’s look at each of it in details :
Strict Comparison(===)
For strict comparison the items been compared must be the same type.
console.log("Coder" === "Coder"); //true console.log("Coder" === "coder"); //false
console.log(23 === 23); //true console.log(NaN === NaN); //false console.log(0 === -0); //true
console.log(true === true); //true console.log(false === false); //true
var obj = {}; var newObj = obj; console.log(newObj === obj); //true
console.log(null === undefined); //false console.log(null == undefined); //true
Type-converting comparison
The == does a type conversion before comparing, if both items are of different types.
As you can see in the below example. String 1 is equal to numeric 1, when using ==. It is because the type of String 1 is converted to Number before comparison.
It is the similar case with “1 == true”. The 1 is converted into Boolean, which is true before comparison.
Same expressions are not true while using ===, as we know it doesn’t do any type conversion.
console.log('1' == 1); //true console.log(1 == true); //true console.log(1 === true); //false console.log('1' === 1); //false
Both null and undefined represents empty values. Let’s understand them first and then we will see what is the difference.
undefined
To understand “undefined” we have to understand what is declaration and definition of variables. When we declare a variable as in below diagram by “var value”, the compiler makes space for a variable “value”. The definition means that we assign a value to the variable and it’s allocated in that space. You can also do these two together by
var value = 42;
So, every language have a way of handling the value of a variable between function declaration and definition.
In JavaScript that is handled by type “undefined”. The type undefined is a primitive type which have only one value possible i.e. undefined.
null
It is also similar to “undefined” and is a primitive type. It also have only one possible value i.e. null. It is also used to represent empty values, but is generally assigned by the users.
var a; console.log(a); //undefined a = null; console.log(a); //null
Function declaration is like most other traditional languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we pass function as arguments to other function or return an function.
function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); } console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //Function expression
One of the key difference is that, we can call a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top.
console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //ReferenceError function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); }
/*
Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization
@Scratchpad/7:2:1
*/
But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.
This is one of the most frequently asked JavaScript interview questions for freshers in recent times. Be careful with the expression this one.
Closures are one of the most complex topic in JavaScript, but they are everywhere in JavaScript.
Closures are basically, the inner function having access to the variables in the outer function scope, even after the outer function has returned. To use a closure, simply define a function inside another function and expose it. To expose a function, return it.
Consider the below code. The variable b have an scope in outer function i.e. from line 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.
So, how does the innerFn() access the value of b. This is where the JS feature of Closures comes into play.
When the “var inner” is created at line 6, the JS engine not only stores the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.
Now it doesn’t matter where you call inner, whether in this file or some third party file. It will always remember the value of a and b, as if a snapshot is been taken.
var a = 10; function outer() { var b = 20; var inner = function() { console.log(a); console.log(b); }; return inner; } var innerFn = outer(); innerFn();
Output
//10 //20
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one. Here is how to answer this -
JavaScript “this” keyword simply means that whatever scope you are inside, it belongs to that. Now the scope can be a function or and Object. Although, there are some exception to this rule. We can have “this” in various context. Let’s go through them.
“this” in simple function
In a normal JS function like below, the “this” refers to global window object.
function foo() { console.log(this); console.log(this === window); } foo();
Running the above code will give.
There is a special case with strict mode.
In strict mode “this” to be undefined , as global object refers to undefined instead of window object.
function foo() { 'use strict'; console.log(this); console.log(this === window); } foo();
“this” in an object property
In an object which have a property as a function, the value of “this” is the Object itself.
var obj = {}; obj.foo = function() { console.log("Inside obj foo"); console.log(this); } obj.foo();
this is Object itself
“this” with constructor function
When a function is called with “new” keyword, it is known as constructor function. And the value of “this” refers to the newly created instance.
function Person(fn, ln) { this.first_name = fn; this.last_name = ln; this.displayName = function() { console.log(`Name: ${this.first_name} ${this.last_name}`); console.log(this); } } let person = new Person("Tim", "Horton"); person.displayName(); let person2 = new Person("Mary", " Poppins"); person2.displayName();
The newly created instance is nothing but an object, because everything in JS is an object.
One The for..in loop is mainly used to iterate over properties of an Objects.
In JavaScript Arrays are also Objects and each characters in an string have an index. So, we can use them also to iterate over Arrays and Strings also.
//Object example
const obj = { 'frontend developer': 'Thomas', 'designer': 'Mary', 'backend developer': 'Harry', 'engineering manager': 'Vikas' } for(const key in obj) { console.log(`${key}: ${obj[key]}`) }
//Array example
const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager']; for(const index in array){ console.log(array[index]); }
//String example
const string = 'frontend developer'; for(const index in string){ console.log(string[index]); }
The for..of loop was introduced in ES6 and is used to iterate over Objects that have [Symbol.iterator] property. This includes array, strings, Map, Set and NodeList. They cannot be used to iterate over Objects are not iterable.
If we check the __proto__ of an array, we can find the [Symbol.iterator] property.
But it is not the case with Objects as it is not iterable.
Some use of for..of loop are below:
//Array example
const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];
for(const item of array){ console.log(item); }
//String example
const string = 'developer'; for(const char of string){ console.log(char); }
//Map example
const map = new Map(); const emp1 = {name: 'Vikas', Degree: 'MS'}; const emp2 = {name: 'Thomas', Degree: 'MBA'}; map.set(emp1, 'frontend developer'); map.set(emp2, 'engineering manager'); for(const [key, item] of map) { console.log(key, '-', item); }
Hosting means we can use a variable even before declaring it. When the compiler runs(details in Question 1) and finds all the var declaration, it move them to the top of the file.
Let’s consider this below example. Here we are assigning values to on name , age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throws a runtime error. It is because it doesn’t matter where the variables are declared. They are always hoisted to the top by when the compiler makes the first pass.
name = "Thomas"; age = 45; profession = "Engineering Manager"; console.log(`${name} aged ${age} is ${profession}`); //Thomas aged 45 is Engineering Manager var name; var age; var profession;
This is also true for function declaration, as the compiler also treats function declaration as variable declaration as in JS all function declaration are object declaration. But same is not true for function expression and it will give reference error.
console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //ReferenceError function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); } /*
Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization
@Scratchpad/7:2:1
*/
But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.
The output right now will be as below, as the method chaining is not understood by the compiler.
/* Exception: TypeError: A.x(...) is undefined @Scratchpad/1:14:1 */
We can get the desired output by “return this” in each function.
Now “this” is the object “A”. So, A.x() will result in console logging ‘x’ followed by returning the object “A” to y().
After that the function A.y() will print ‘y’ followed by returning the object “A” to z().
Finally, ‘z’ is printed on console.
var A = { x: function() { console.log('x'); return this; }, y: function() { console.log('y'); return this; }, z: function() { console.log('z'); return this; } } A.x().y().z(); //Output x y z
The sort() method is used to sort the elements of an array. But the output of the above is not what expected out of sort() function. The output will be [ 1, 15, 2, 30, 4, 45, 7 ] and it is far from desired.
This is because the default sort is according to tring Unicode points. The fix to it is by adding an anonymous function and tell to sort according to ascending or descending order.
Ascending order is as below:
const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> a-b)); //[ 1, 2, 4, 7, 15, 30, 45 ]
Descending order is as below:
const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> b-a)); //[ 45, 30, 15, 7, 4, 2, 1 ]
The most obvious answer to think is the value of “i” will be 0. So, let’s put i = 0 and see what happens.
let i = 0; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives NaN
Everything is ok, but the last one produce NaN(Not a Number) because “0 divide by 0 will produce infinity”
So, we need a number which is like zero but gives 1 if we divide it by itself. Fortunately there is such a number in JavaScript. The number is the minimum value that is allowed in JavaScript and is represented by Number.MIN_VALUE
let i = Number.MIN_VALUE; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives 1
Now, what is this MIN_VALUE and why it produces the above correct desired result. If we console log it we can see it’s a very small number 5e-324.
console.log(Number.MIN_VALUE); //5e-324
Now, this number in most cases behaves like a zero(0). Like when we multiply it by itself(i * i), add it to 1(i + 1) or substract it from 1(i -1).
But when we divide this small number by itself it produces 1.
When an event happens on an element, it first runs on which it was clicked, then on its parent, then all the way up on other ancestors. It is the default behaviour of the browser.
Event capturing is the opposite of bubbling and it means when you click on parent element, it goes till the child.
We will first see Event Bubbling. The HTML contains an parent element containing a child element called Child1. When we click on the “Child1” button, first the console log of child is displayed and then the parent is displayed.
We will now see Event Capturing. The HTML contains an parent element containing a child element called Child1. When we click on the button, first the console log of parent is displayed and then the child is displayed. Notice that in addEventListener we have to pass a value of true.
IIFE means Immediately Invoked Function Expression. Let’s first see a normal way to create function in JavaScript, also known as function as “Function declaration”. This is most similar, to the syntax of declaring functions in most other traditional languages like C++ and Java.
Consider the below example which have a simple function to add two numbers. Notice that these function definitions always start with the function keyword. You can’t omit it as it’s invalid syntax.
In JavaScript functions are first class citizens. So, there is another way to declare them. It is known as “Function Expression”. We will refactor the above addNumbers() code. Here we are treating as if addNumbers is a variable declaration. But then assigning an anonymous function to it.
IIFE(Immediately Invoked Function Expression) is nothing but a function expression, but it is defined and invoked at the same time. Here we had got rid of the addNumbers name itself and calling it also at the same time. Notice, that we are passing 2,3 immediately after the anonymous function is declared.
As JavaScript for most part is function scoped, so IIFEs are great way to create private variables.
Promises in JavaScript are like promises in real life. You promise to do something, and then it is done or not done. A promise may be in one of 3 possible states: resolve, rejected, or pending.
They are mainly used to do asynchronous task like calling a REST api and getting the result back. So, these network calls takes time. When the network call is been made, the promise is in Pending state. Once the network call is successful the promise returns a resolve and if it fails it returns resolve.The resolve is captured by the then() callback function and reject captured by catch() callback function.
Consider the below example. Here inside promiseCleanRoom we generate a random number between 0 and 1. If the number is greater the 0.5, we send a resolve or else we send a reject.
Depending on the case either .then is executed or .catch is executed.
Below is the resolve case
Expect to come across this, one of the top JavaScript interview questions for experienced professionals in web development, in your next interviews.
A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is executed inside the that Function.
Callback function are used everywhere in JavaScript. In JavaScript, functions are first-class citizens. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”.
Let’s look at the example below. Here we call function mainFunc with function “x” as argument and then from inside mainFunc, calling it after some console log.
When we use anonymous function inside our function call for callback like in the below code.
The in-built for Each, map, reduce, filter uses callback functions internally. Check the below example and here we are passing a function, just like above calc code.
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result.
Now, in recursive function there are two parts. One is termination condition and other is the recursion itself. The termination condition is very important or else the recursion never stops and goes into infinite loop.
Let consider the below simple example to add numbers from the current passed number backwards till 1. Say we pass 3, then 3+2+1 = 6. In the below example If(n≤0) is the termination condition and return n + add(n-1); is the recursion.
The recursion works as shown in the diagram below.
It works like loop, so the first call will go to recursion part and give “3 + add(2)”.
Now the add(2) will be called and will be expended into “2 + add(1)”.
After that add(1) will be called and expanded into “1 + add(0)”.
Finally the add(0) will trigger the termination condition If(n≤0) and produce 0.
After this everything will be added 3 + 2 + 1 + 0 to give 6.
A Higher Order Function is a function that takes one or more function as argument. We use them at many places in JavaScript, and are also called callback functions.
Consider, the below JS code which uses filter to filter-out Adult people. Here, we have a callback function isAdult which is called on every item.
These callbacks are usually defined inline as anonymous function. So, the refactored code is below.
We can further refactor it using arrow functions as below.
So, the array methods of map(), filter(), reduce(), forEach() are all Higher Order Functions.
Beside this eventListener like below are also Higher Order Function, as they use a callback function.
Template Strings are also known as Template Literals. They are the new way to write Strings in JavaScript and been introduced in ES6. We can now write Stings using back-ticks(``), which have a special way to interpolate variables.
They are very useful in Expression interpolation and Multi-line strings. Although they don’t add any new feature to JavaScript, but they are a better visual way to write strings.
Expression interpolation
The old JavaScript way is quite cumbersome and we have to use many + operators to concatenate Strings, whereas with back-ticks we interpolate variable name using ${}.
Multi-line strings
The old way to have multiline strings is to have a newline(\n) inserted after where we want the next line.
Template strings provides a new way. You just go to the next line and the text will be displayed in next line.
Default parameters are the parameters, which are used if we don’t pass the value to that argument in a function while calling it.
Earlier to ES6, it was a bit difficult to handle a situation like this. In the below example if user didn’t supplied a value to argument , we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”.
So, now we can handle all three situation successfully like when we pass no arguments, or pass only value of ‘a’ or pass only value of ‘b’.
The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.
Spread operators(…) were introduced in JavaScript in ES6 version. Just like plus(+) and minus(-) are operators, spread(…) is also an operator in JavaScript. Basically Spread operator spreads on demand.
When you pass arguments to a function using Spread operators they are called Rest parameters.
Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function the arr gets converted into and array. This functionality is quite similar to arguments object.
Now see the restFunc, here we are using rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into array.
The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects.
Consider that we want to copy an array to other array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x.
In the first solution, we use the new JavaScript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”.
But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array.
Another use it that if we pass an array to build in functions, which expects normal arguments. Consider the below examples.
We can also use Spread operator in Objects. So, by it we can do both clone and merge as shown in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys.
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. You can also handle nested structure by using nested destructuring syntax.
Object Destructuring
Consider the old way to assign variable to Object properties without destructuring.
Now we will refactor the above using “Object Destructuring”. Basically, you use an object literal on the left-hand-side of an assignment expression for object destructuring.
Nested Object Destructuring
If there is nested object as in below case, we can destructure it by adding it’s value to another object syntax
Array Destructuring
Let’s first see how to do it without destructuring. Here we use the index to assign the variables.
Array destructuring is similar to object destructuring, but here instead of keys you assign any variable.
Skipping Items
It is possible to skip items in array destructuring by omitting items with comma(,).
A must-know for anyone looking for top JavaScript coding interview questions. This is one of the frequently asked JavaScript questions today.
ES6 introduced the keyword class in JavaScript. But class in JavaScript is still different than those used in Object Oriented Programming languages like C++ and Java. The ES6 classes are nothing but synthetic sugar for constructor function and internally behaves exactly the same.
Consider the below example of Constructor function. Here we have a constructor function named “Mammal”. It have two properties of legs and name. It also have a function called walk(), which uses the legs and name property. We are creating an instance called person, which then is calling the walk function.
The same can be written with ES6 classes with constructor, but it is exactly the same.
Async await help in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.
Async await are basically promises under the hood. But they have made the code for promises very easier to implement. If promises had simplified the code for callbacks, then async await have simplified the code for promises.
Let’s first check a nested promise example. Here we have three functions which return promises- cleanRoom, removeGarbage and winPizza. Now, when the cleanRoom function is run and resolve is returned from the promise, then the immediate .then block will be run . In the .then we are returning the next removeGarbage and in its .then we are returning the winPizza. We are passing the message from one function to other, so it will be appended.
We will refactored the code with async await. Here, instead of three functions we have one function cleaningTheRoom, which have a keyword “async” infront of it. It means that the function will have await statement(s). In the “await” we can have the value returned by a Promise stored in a variable. This type of code is much more cleaner then promise.
The Promise.all method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
Let’s refactor the async await code from previous question to use Promise.all. Notice, that we are also using array destructuring at line 6, to receive all the values returned by the promise.
We should use Promise.all in only cases like above, where the result of one Promise is not dependent on other promise.
In Promises we handle any error or reject in the .catch block. Let’s look at the below example, where we are sending reject() from cleanroom(). So, now the error will be caught by the .catch block and then we are displaying the same in console log.
Now, when we refactor the above code using async-await, we don’t have any .catch block. So, we take help from the good old try…catch block available in JavaScript.
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
Constructor functions are the equivalent of classes of traditional programming languages like C++ and Java. Sometimes people will refer to them as reference types, classes, data types, or simply constructors.
If you aren’t familiar with classes, they are a construct that allows you to specify some properties and behaviours (functions), and multiple objects can be created with those properties and behaviours.
A common analogy you’ll often hear is, a class is an architecture’s map and an object is a house created using it. Multiple houses can be created from a single map, as multiple objects can be created from a class.
Let’s start with creating a simple function using object to create employee objects.
Now consider the line var newObj = {} and return newObj. They will be same in every function which we create. So, JavaScript gives us a special type of function known as Constructor function to create them.
We will refactor the above to use Constructor function. Look at the below code.
We are adding the keyword new to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name this.
Note, that we don’t need to put those two line in our code and automatically put by JavaScript engine.
We can also add methods to a Constructor function and then it can be called with any object created with new keyword.
Let us first consider the below code for normal Constructor function. Here we can directly access the variable “name” by person.name.
Now, this might be not desirable at many places and in Traditional languages like C++ and Java, this is solved by the having “private” variables in class and then having “Getters” and “Setters” to access them.
Now, we implement the same in JavaScript using Closures. We have two closure functions setName and getName which are basically “setters” and “getters”. Now, the variable _name is private and cannot be accessed outside the function by person._name and we can access it only by person.getName()
In JavaScript everything is an Object. So whenever we create an function, there is a one object which is created for that function. But actually there is another object which is created which is known as the Prototype object.
Now to access the Prototype object we have a reference on the function object also known as prototype. Notice the small “p”.
When we create an instance of the function with the new keyword interesting things happens. It create something known as __proto__. This is created by the JavaScript engine for every function call using the new keyword.
Now, let’s look how to create an function using prototype and the benefit of it. The below code have two function haveFun and drinkBreak. The function haveFun is an normal function inside the Constructor function. The function drinkBreak is created outside and added to the Prototype Object using it’s reference prototype.
Both the function seems to be doing the same thing, then what’s the benefit.
The benefit of declaring function using prototype is that it’s created once in the Prototype object. So, now whenever we create a new instance of the Constructor function the function is not created again. As in the below screenshot, you can see that emp1 and emp2 both have name and haveFun. But the drinkBreak is inside the __proto__, which is a reference to Prototype object.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
Let us now see why JavaScript is needed:
You can validate input before sending it to the server. This leads to faster loading on the server.
Executing JavaScript code is not a tedious task. Add your code in an HTML document. When user requests this HTML page with JavaScript in it, the script is sent to the web browser.
JavaScript can load content into the document whenever you need it. And while doing that, you don’t need to reload the complete page.
Use JavaScript to show and hide information on click. Move DOM elements around the page based on some pattern using JavaScript.
With JavaScript, you can also animate text.
You can develop games as well if you have advanced knowledge of JavaScript and its practical implementation.
JavaScript validates form data on the client's computer. And this task is accomplished before sending the data to the server.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
Java is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform independent object-oriented language.
The following is the difference between Java and JavaScript:
Basis | Java | JavaScript |
---|---|---|
Definition | Java is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform independent object-oriented language. | JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997. |
OOP | Java is an OOP programming language | JavaScript is an OOP scripting language. |
Running on Browser | Java creates applications that run in a virtual machine or browser | JavaScript code is run on a browser only. |
Compiled vs. Interpreted | Java Program is compiled. | JavaScript scripts are Interpreted. |
Type Checking | Java has static type checking. The type of a variable is checked at compile-time. | JavaScript has dynamic typing. The type safety is verified at runtime. |
Type of Variable | The type of variable should be specified. | It is not required to specify the type of variable. |
JavaScript is a lightweight and interpreted scripted/ programming language introduced in by Brendan Eic. It has a lot of advantages like validation, animation, interactions, etc. However, like any other programming language, it has some limitations too like you cannot write files on server, browser compatibility issues, etc.
Let us see the limitations of JavaScript one by one:
Writing files on server
JavaScript cannot directly write files on server. However, they can do this using server-side script.
Disable JavaScript
Due to security reasons, every web browser provides an option to disable JavaScript.
The screenshot displays how to enable or disable JavaScript:
It cannot be used for Networking applications.
Applications may behave differently in different web browsers. To support all modern browsers, you need to write cross browser codes.
Since the code executes on client’s computer, the chances are high for vulnerability and can be exploited for malicious purposes
JavaScript cannot access databases. You need AJAX and a server-side script for this.
Note: New developments in JavaScript introduced accessing client-side databases.
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The === is a comparison operator in JavaScript. It checks for the value as well type.
Same value and type
Let us see an example wherein we have assigned a numeric value to variable “val1” and checked it with a numeric value for equality (type and value):
<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val1 = 20; document.getElementById("test").innerHTML = (val1 === 20); </script> </body> </html>
The output displays that the variable has the same value and type. Therefore, true is returned as output:
Same Value and Different Type
Let us see an example wherein we have assigned a numeric value to variable “val2” and checked it with a value of another type for equality (type and value):
<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val2 = 5; document.getElementById("test").innerHTML = (val2 === "5"); </script> </body> </html>
The output displays that the variable has same value but different type. Therefore, false is returned as output:
Yes, JavaScript is case-sensitive. Therefore, the following identifiers are different:
Knowledge KNOWLEDGE
The case-sensitivity feature remains the same for variables, function names, and any other identifiers. The consistent capitalization of letters should be considered. For example, “for loop” should be written as “for”, not “FOR” or “For”.
Let us see an example wherein we have three variables with different case. All of these 3 variables are considered different:
<!DOCTYPE html> <html> <body> <h3>Popular Programming Languages</h3> <p id="test"></p> <script> var language, LANGUAGE, Language; language = "C#"; LANGUAGE = "Java"; Language = "Python"; document.getElementById("test").innerHTML = LANGUAGE; </script> </body> </html>
The output:
Let’s see the following two ways with which you can create an object in JavaScript:
Let us understand them one by one:
To create an object in JavaScript, use “new” as shown below. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create an object using Object() constructor:
<html> <head> <title>Objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance"; department.id = 005; department.location = "North";
Object creation with Object Literal
An object can also be created in JavaScript using object literal as shown below:
var department = { id: 11, name : "Finance", Location : "North" };
We can write it as:
var department = { id: 11, name : "Finance", Location : "North"};
Let us see another example:
<!DOCTYPE html> <html> <body> <h2>Department Details</h2> <p id="test"></p> <script> var department = { id: 11, name : "Finance", Location : "North"}; document.getElementById("test").innerHTML = department.name + " Department is in " + department.Location + " location."; </script> </body> </html>
The output:
The array variable is to be set empty if you want to empty an array.
Let’s say we have the following array:
var myArr = ["shirt", "trousers", "watch"];
To empty the above array, just set it to empty:
myArr = [];
Here we converting our array to empty array:
<html> <head> <title>Empty Array in JavaScript</title> <script> var myArr = ["shirt", "trousers", "watch"]; document.write("<br />Array: " + myArr ); // set array to empty myArr = []; document.write("<br />New array (Empty now): " + myArr ); </script> </head> <body> </body> </html>
The output:
Array: shirt,trousers,watch New array (Empty now):
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one. Here is how to answer this -
Using the <scrip>t tag you can store the JavaScript code in an external .js extension file. The tag with the “src” attribute allows you to include this js file in your HTML.
If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time.
Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The ”src” attribute is used to include the external JavaScript file in your HTML:
<script src="myfile.js" ></script>
Let’s say the following is the content of our external JS file “myfile.js”:
function show () { alert("Learning is fun!"); }
The following is our HTML file, wherein we will include the external file “myfile.js”:
<html> <body> <form> <input type="button" value="Click" onclick="show()"/> </form> <script src="show.js"> </script> </body> </html>
On running the above “myfile.js” file, the following is visible. Press the button “Click”:
On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function:
Events handle JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a window also comes under event.
The following are the events. A function in JavaScript gets executed against the event:
Events | Triggers |
---|---|
onblur | When the window loses focus |
onchange | When an element change. |
onclick | On a mouse click |
ondblclick | On a mouse double-click |
ondrag | When an element is dragged |
ondragen | At the end of a drag operation |
ondragenter | When an element has been dragged to a valid drop target |
ondragleave | When an element is being dragged over a valid drop target |
ondragover | At the start of a drag operation |
ondragstart | At the start of a drag operation |
ondrop | Dragged element is being dropped |
ondurationchange | When the length of the media is changed |
onerror | When an error occurs |
oninput | When an element gets user input |
oninvalid | When an element is invalid |
onkeydown | When a key is pressed |
onkeypress | When a key is pressed and released |
onkeyup | When a key is released |
onmousedown | Triggers when a mouse button is pressed |
onmousemove | Triggers when the mouse pointer moves |
onmouseout | Triggers when the mouse pointer moves out of an element |
onmouseover | Triggers when the mouse pointer moves over an element |
onmouseup | Triggers when a mouse button is released |
onmousewheel | Triggers when the mouse wheel is being rotated |
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output:
Event gets triggered when you click on the button “Display” to agenerate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
In JavaScript, you can use the same variable to hold different data types. This is why it is called that JavaScript has dynamic types.
It is not required to specify the type of variable in JavaScript. For example, the following is a variable, which is a number:
var val = 10;
Now, the same variable is a String:
var val = “Bingo”;
Now, you can also set it as a Number with decimal:
var val = 3.6;
Let us see them in an example to understand the dynamic types wherein we are showing the same variable can easily hold different types:
<!DOCTYPE html> <html> <body> <h2>Dynamic Types</h2> <p id="myid"></p> <script> var a; // a is undefined a = "Bingo"; // a is a String a = 10; // a is a Number a = 3.6; // a is a Number with Decimal document.getElementById("myid").innerHTML = a; </script> </body> </html>
The output:
In the above example, we have set different types for the same variable “a”:
var a; // a is undefined a = "Bingo"; // a is a String a = 10; // a is a Number a = 3.6; // a is a Number with Decimal
If you want to check the type of an object at runtime, then use the instanceof operator. The result is a boolean.
Check for Array
Let’s say we are checking if a variable is an array or not using instanceof operator. The syntax:
variable_name instanceof Array
The following is our example and we are checking whether array exists or not:
<html> <body> <script> var department = [ "Finance", "Operations", "Marketing", "HR" ]; if (department instanceof Array) { alert('This is an Array!'); } else { alert('This is not an array!'); } </script> </body> </html>
The output displays that array exists since the if condition is true:
Check for Object using instanceof
To check for an object, use the instanceof operator, the following is the example:
<html> <body> <script> var myObj = {}; if (myObj instanceof Object) { alert('This is an object!'); } else { alert('This is not an object!'); } </script> </body> </html>
The output displays ‘this is an object!’ in an alert box, since the if condition is true:
Remove a Single Element
To remove a single element from an array in JavaScript, the splice() method is used. With that you can also replace, and/or add elements in an array.
Let’s say we have the following array:
var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];
We are using the splice() method to remove a single element by setting the location from where it start, and the number of elements to be removed. Here, we have set 1, therefore only a single element will get removed:
myArr.splice(3, 1);
The following is an example:
<html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing an element = " + myArr ); rem = myArr.splice(3, 1); document.write("<br />Removed element = " + rem); document.write("<br />Array after removing an element = " + myArr ); </script> </body> </html>
The output:
Array before removing an element = Java,PHP,HTML,jQuery,Eclipse,NetBeans Removed element = jQuery Array after removing an element = Java,PHP,HTML,Eclipse,NetBeans
Remove more than one element
To remove more than one element and in a range, use the splice() method.
Let’s say we have the following array:
var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];
We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:
We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:
myArr.splice(2, 3);
In the following example, we are deleting 3 elements starting from the 3rd position:
<html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing 3 elements = " + myArr ); // removing multiple elements rem = myArr.splice(2, 3); document.write("<br />Array after removing 3 elements = " + myArr ); </script> </body> </html>
The output displays the array after removing 3 elements:
Array before removing 3 elements = Java,PHP,HTML,jQuery,Eclipse,NetBeans Array after removing 3 elements = Java,PHP,NetBeans
ECMAScript introduced to standardize JavaScript. The implementations of ECMAScript include JavaScript, ActionScript, JScript, etc. ECMAScript is a standard for these. It is a trademark scripting language specification.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
ECMAScript is a standard for JavaScript. The first edition of ECMAScript came in 1997. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard. The 8th edition of ECMAScript is ECMAScript 2017, introduced in June 2017. The full form of ECMA is European Computer Manufacturers Association
The current version is the 9th edition of ECMAScript, which came in the year 2018. The ECMA-262 Specification defined a standard version of the core JavaScript language.
Let’s say the following is our variable declaration of strings:
var val = "e\nx\na\nm\np\nl\ne";
To replace newlines, use the replace() method. The method replaces all occurrences of a character in the given string. The replace(char1, char2) has the following parameters:
Here the g flag on the regular expression to perform a global match. The 2nd parameter is a space (“ “), which we want in place of new line (\n):
val = val.replace(/\n/g, " ");
The following is an example that replace newline with spaces:
<!DOCTYPE html> <html> <body> <script> var val = "e\nx\na\nm\np\nl\ne"; val = val.replace(/\n/g, " "); document.write("After removing new line: "+val); </script> </body> </html>
The output:
After removing new line: e x a m p l e
Library in JavaScript has a function with a leading semicolon:
;(function ) { }
Let us see the different uses of including a leading semicolon:
The purpose to include semicolon is to safely concatenate several JS files into one.
A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.
The leading semicolon in immediately-invoked function expressions prevent errors when appending the file during concatenation. This concat is to a file containing an expression improperly concluded with a semicolon
Let’s see an example. Let’s say we are concatenating two files with self-invoking functions:
(function(){...ONE...})()
(function(){...TWO...})()
(function(){...ONE...})() (function(){...TWO...})()
!(function(){...TWO...})()
(function(){...ONE...})();(function(){...TWO...})()
This helps in preventing any kind of errors when appending the file during concatenation.
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The comma operator in JavaScript evaluates each of its operands. It returns the value of the last operand.
With the usage of comma operator, you can easily add multiple expressions. The syntax:
exp1, exp2, exp3, ……exp
Here, exp1, ex,2 exp3 are the expressions.
Add multiple parameters in a for loop using the comma operator:
for (var a = 0, b = 5; a <= 5; a++, b--)
Use the comma operator in a return statement. Process before returning using comma:
function show() { var x = 0; return (x += 1, x); }
With comma operator, you can declare multiple variables at once. Let’s say you have three variables. To declare and initialize them on new lines, you can declare them in a single line as shown below:
var a = 5, b = 10, c = 30;
You can also use the comma operators to call multiple arguments in a function call. Let’s say you have a function “calculate” and you need to find the multiplication of three numbers. For that, use the comma operators
calculate(33, 47, 79);
JavaScript used previously had the type attribute usage like this:
<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Demo!") //--> </script> </body> </html>
Above, you can see we have set the script language as “javascript” and the type as “text/javascript”.
The usage of type=”text/javascript” was necessary before the introduction of HTML5. But, when HTML5 came, JavaScript became its default language. Therefore, adding “text/javascript” is optional.
To validate decimal numbers in JavaScript, you can use regular expressions for matching with the match() method:
Let’s say we have the following decimal with string representation:
var val = "5.9";
The following regular expression you can use:
var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg );
For validation, we used the above regular expression and test it using the match() method. It gives us whether the given value is decimal or not:
<html> <body> <script> var val = "5.9"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output displays ‘decimal’ since the if statement is true:
Decimal!
Let us see another example with a different input i.e. a number:
<html> <body> <script> var val = "7"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output is ‘not a decimal!’, since the if statement is false:
Not a decimal!
Let us see another example and check for string:
<html> <body> <script> var val = "abc"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output displays ‘not a decimal!’ since the if statement is false:
Not a decimal!
Arrays in JavaScript are used to store multiple values in a single variable. Let us see the two ways to create an array in JavaScript:
Using Array Literal
The easiest way to create an array in JavaScript is with array literal. Here, we have a variable and we are setting multiple values to it in an array:
var cars = ["Saab", "Volvo", "BMW"];
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = ["HR", "Finance", "Operations", "Marketing"]; document.getElementById("myid").innerHTML = department; </script> </body> </html>
The output:
HR,Finance,Operations,Marketing
Using keyword new
With JavaScript, you can also create an array using the new operator:
var department = new Array("HR", "Finance", "Operations", "Marketing");
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = new Array("HR", "Finance", "Operations", "Marketing"); document.getElementById("myid").innerHTML = department; </script> </body> </html>
The output:
HR,Finance,Operations,Marketing
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
Yes, constants do exist in JavaScript. The “const” keyword is used to create constant in JavaScript.
The const variables in JavaScript must be assigned a value when they are declared. Once declared, you cannot change and declare the value of constant again.
For example:
const val = 100;
Another example include:
const PI = 3.14159265359;
With const, you can declare local variables with block scope rather than function scope. Let’ say we have a constant variable “a”. After declaring a value like a constant variable, you can’t assign a new value to it.
Here’s an example wherein we are trying to reassign value to a const variable. As expected an error generates:
// declared a constant variable. const val= 150; // Error, since we try to assign a new value to the constant val = 0;
The following also gives an error since we are trying to change the primitive value:
const PI = 3.14159265359; PI = 3.14;
You cannot even reassign a constant array. Let us see an example for this:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> try { const department = ["Finance", "HR", "Marketing", "Operations"]; department = ["Operations", "IT", "Accounting", "Production"]; // error } catch (e) { document.getElementById("myid").innerHTML = e; } </script> </body> </html>
The output displays an error as shown below since we cannot assign to a constant variable:
TypeError: Assignment to constant variable.
To compare two dates in JavaScript, firstly add two date objects and set dates.
Here, our first date is the current date:
To compare two dates in JavaScript, firstly add two date objects and set dates.
Here, our first date is the current date:
var one, two; one = new Date(); two = new Date( "Mar 10, 2017 20:15:10" );
And the second date we have set as past date:
two = new Date( "Mar 10, 2017 20:15:10" );
Now, let us compare the above two dates using the below given code:
<!DOCTYPE html> <html> <body> <script> var one, two; one = new Date(); document.write(one); two = new Date( "Mar 10, 2017 20:15:10" ); document.write("<br>"+two); if (one > two) { document.write("<br>First date is the recent date."); } else { document.write("<br>Second date is the recent date."); } </script> </body> </html>
Let’s say the following is our string with numbers:
var strNum = "only123!";
To fetch the digits from the above string, the following RegExp is used:
/\d/g
Above we have set the g flag to perform global match.
The following is the code:
<html> <head> <title>Regular Expression in JavaScript</title> </head> <body> <script> var strNum = "only123!"; var regExp = /\d/g; document.write("String with numbers: "+strNum) var res = strNum.match(regExp); document.write("<br>Getting Digits = "+res); </script> </body> </html>
The output:
String with numbers: only123! Getting Digits = 1,2,3
The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can also be declared with var, but the usage of var are scoped to the function block level.
Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block.
Example of let
Let us see an example of let. The variable declared in the loop does not redeclare the variable outside the loop:
<!DOCTYPE html> <html> <body> <h3>JavaScript let</h3> <p id="myid"></p> <script> let i = 2; for (let i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays 2 as the variable i value:
Example of var
Let us see the same example using var this time instead let keyword:
<!DOCTYPE html> <html> <body> <h3>JavaScript var</h3> <p id="myid"></p> <script> var i = 2; for (var i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays 10 as the value of variable i:
To search for a string in a string, use the search() method. The method searches a string for a specified value. The returned value is the position of the match. However, -1 is returned if the match isn’t found.
Let’s say we have the following string:
var myStr = "Popular Programming Languages";
We want to search the below string from the above string:
Languages
For that, use the search() method:
var res = myStr.search("Languages");
Let us see the example wherein the string is successfully searched and the result (position) is displayed on button click:
<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "Popular Programming Languages" var res = myStr.search("Languages"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays the position:
Let us now see another example, wherein -1 is returned since the string to be found isn’t there:
<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "This is an example!" var res = myStr.search("demo"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output on button click displays -1:
In the unsigned right shift operator (>>>), the bits shifted on the left are always zero.
The zeros get filled in from the left with the operator. It shifts all bits in a 32-bit number to the right.
The following is an example:
<html> <body> <script> var val1 = -23; var val2 = 2; document.write("val1 >>> val2 = "); res = (val1 >>> val2); document.write(res); </script> </body> </html>
The output:
val1 >>> val2 = 1073741818
Let us see another example wherein we have a positive number. In this case the operator works the same as a signed right shift:
<html> <body> <script> var val1 = 7; var val2 = 2; document.write("val1 >>> val2 = "); res = (val1 >>> val2); document.write(res); </script> </body> </html>
The output:
val1 >>> val2 = 1
Cookies has a plain text record of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It stores information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.
Let us see how we can create a cookie in JavaScript:
The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.
Create a cookie:
document.cookie = "username=Knowledge Hut";
Add an expiry date to the cookie created above:
document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";
To read a cookie in JavaScript:
var a = document.cookie;
The above displays the cookies in name-value form i.e.:
cookie1=value; cookie2=value;
To delete a cookie, you need to just set the cookie to the past date (expire). The date is included using the expires parameter:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Let us see an example that creates a cookie:
<html> <head> <script> <!-- function displayCookie() { if( document.one.dept.value == "" ){ alert("Enter some value!"); return; } val = escape(document.one.dept.value) + ";"; document.cookie="name=" + val; document.write ("Setting Cookie <br> " + "name=" + val ); } //--> </script> </head> <body> <form name="one" action=""> Enter Department: <input type="text" name="dept"/> <input type="button" value="Input Cookie" onclick="displayCookie();"/> </form> </body> </html>
The output displays an input box, wherein we add a value to set as cookie:
On clicking “Input Cookie” above, you can see that we have set the cookie successfully:
The typeof operator is a unary operator in JavaScript. It is used to check the data type of its operand, like a variable is string, numeric, boolean, etc.
Let us see a simple example for number:
<html> <body> <script> var val = 10; document.write(typeof val); </script> </body> </html>
The output displays that it is a number:
Number
Let us now see another example for string:
<html> <body> <script> var val = "Sachin"; document.write(typeof val); </script> </body> </html>
The output displays that it is a string:
String
In the same way, we can check the type of a value entered, which is a boolean:
<html> <body> <script> var val = true; document.write(typeof val); </script> </body> </html>
The output display that the value entered is a boolean:
boolean
As we saw some examples above, here is the list of the values returned by the typeof operator:
Type | String Returned |
---|---|
Number type | Returns “number” |
String type | Returns “string” |
Object type | Returns “object” |
Boolean type | Returns “boolean” |
Null | Returns “null” |
The following are the different ways in which we can include JavaScript code in an HTML file. We can add JavaScript in the same file or an external file:
Java Script in the same file
Add the JavaScript code in the same HTML file using any of the following ways:
In head section
If you want the script to run on some event, then add the JavaScript code in the head section of the HTML file. Let us see an example:
<html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input type="button" onclick="show()" value="Click" /> </body> </html>
In body section
If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example:
<html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html>
JavaScript in an external file
Using the <script> tag you can store the JavaScript code in an external .js extension file. The tag with the “src” attribute allows you to include this js file in your HTML.
If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time.
Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the <script> tag. The src attribute is used to include the external JavaScript file in your HTML:
<script src="myfile.js" ></script>
Let’s say the following is the content of our external JS file “myfile.js”:
function show () { alert("Learning is fun!"); }
The following is our HTML file, wherein we will include the external file “myfile.js”:
<html> <body> <form> <input type="button" value="Click" onclick="show()"/> </form> <script src="show.js"> </script> </body> </html>
Press the button “Click”:
On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function:
The following are the types of pop-up boxes available in JavaScript:
Alert Box
The alert box is for an alert or message to the user. User needs to click “OK”. The alert() method is used to add a message in the alert:
Let us see an example:
<!DOCTYPE html> <html> <body> <h1>Alerts in JavaScript</h1> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output displays an alert on the click of a button:
On clicking the above button, the following alert generates:
Prompt Box
To input a value from the user and display it, use the prompt box. Users need to click “OK” to return the entered input, else click “Cancel” to return null.
Let us see an example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var res; var department = prompt("Enter your Department", "Operations"); if (department == null || department == "") { res = "Prompt cancelled!"; } else { res = "Department is " + department; } document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output first displays the button which you need to click:
On clicking the above button, a prompt box is visible wherein user input is requested:
On clicking “Ok”, the input is displayed on the web page:
Confirm Box
The confirm box is used in JavaScript to take user’s consent or accept something. User need to click “OK” to return true, else click “Cancel” to return false.
Let us see an example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var res; if (confirm("Press a button!")) { res = "OK is pressed!"; } else { res = "Cancel is pressed!"; } document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The following is the output. The button is visible. You need to click it:
On clicking the above button, a confirm box generates that wants users’ consent on clicking the button:
On pressing OK, the following is visible:
To handle exceptions in JavaScript, use the try, catch, throw and finally statements.
The try statement defines a block of code to be tested for errors, whereas the catch statement allows defining a block of code to be executed if an error occurs in the try.
The try block must be followed by either exactly one catch block or one finally block.
Let us see an example of try, catch and finally:
<html> <head> <script> <!-- function show() { var val = 5; try { alert("Value = " + val ); } catch ( e ) { alert("Error = " + e.description ); } finally { alert("Finally block executes!" ); } } //--> </script> </head> <body> <p>Click below:</p> <form> <input type="button" value="Display" onclick="show();" /> </form> </body> </html>
The output on running displays the following button:
On clicking the above button, an alert box is visible:
No error is there. On clicking “OK”, the “finally” statement executes. The alert box in the “finally” generates the following alert:
To return the division remainder, use the Modulus operator in JavaScript.
Let’s say the following are our two variables for which we want the modulus:
var val1 = 20; var val2 = 8;
Now, let us use the % operator to find the remainder:
var res = val1 % val2;
The example finds the division remainder using the Modulus operator:
<!DOCTYPE html> <html> <body> <h2>Remainder</h2> <p id="demo"></p> <script> var val1 = 20; var val2 = 8; var res = val1 % val2; document.getElementById("demo").innerHTML = res; </script> </body> </html>
The output displays the remainder:
The eval() function is used in JavaScript to evaluate or execute an argument. The method evaluates the expression, if the argument is an expression, else for arguments as statements, it executes the statements.
The parameter in the eval(string) function is a string, which can be an expression, variable, statement, or sequence of statements:
eval(string)
Note: Do not call eval() method to evaluate an arithmetic expression
Let’s say we have the following two variables:
var val1 = 20; var val2 = 7;
Now, with a new variable we will perform some calculations with the eval() method:
var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>";
The example demonstrates the role of eval() in JavaScript:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var val1 = 20; var val2 = 7; var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>"; var res = calc1 + calc2; document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays a button, which on pressing generates the following result:
140 119
Let us see another example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var val1 = 15; var val2 = 10; var calc1 = eval("30 * 3") + "<br>"; var calc2 = eval("val1 + val2") + "<br>"; var calc3 = eval("5 * val1") + "<br>"; var calc4 = eval("10 + val2") + "<br>"; var res = calc1 + calc2 + calc3 + calc4; document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays a button, which on pressing generates the following result:
90 25 75 20
To increase the size of the text, you need to use the JavaScript big() method. Using it, you can easily display a string in a font size bigger than the normal font.
The following is an example to create a text with big font:
<html> <head> <title>JavaScript big()</title> </head> <body> <script> var myStr = "Demo Text"; document.write("Normal font: "+myStr) document.write("<br>Bigger font: "+myStr.big()); </script> </body> </html>
The output displays normal as well as bigger font using the <big> element:
Cookies has a plain text record of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It is store information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.
Let us see how we can create a cookie in JavaScript:
The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.
Create a cookie:
document.cookie = "username=Knowledge Hut";
Add an expiry date to the cookie create above:
document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";
To read a cookie in JavaScript:
var a = document.cookie;
The above displays the cookies in name-value form i.e.:
cookie1=value; cookie2=value;
To delete a cookie, you need to just set the cookie to the past date. The date is included using the expires parameter:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Let us see an example that creates and set a cookie:
<html> <head> <script> <!-- function displayCookie() { if( document.one.dept.value == "" ){ alert("Enter some value!"); return; } val = escape(document.one.dept.value) + ";"; document.cookie="name=" + val; document.write ("Setting Cookie <br> " + "name=" + val ); } //--> </script> </head> <body> <form name="one" action=""> Enter Department: <input type="text" name="dept"/> <input type="button" value="Input Cookie" onclick="displayCookie();"/> </form> </body> </html>
The output displays an input, wherein we add a value to set as cookie:
On clicking “Input Cookie” above, you can see that we have set the cookie successfully:
The onclick event gets triggered in JavaScript when a user clicks on any of the HTML element such as on click of a button.
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output displays a button:
Event gets triggered when you click on the button to generate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
To join two or more strings, use the JavaScript concat() method. A new string is returned with the joined strings.
The syntax:
string.concat(str1, str2, str3..., strn)
Here, str1, str2, and str3 are the strings you want to join.
Let’s say the following are our two strings to be joined:
var myStr1 = "One"; var myStr2 = "Time!";
Now, use the concat() method to join both the strings:
var res = myStr1.concat(myStr2);
The example demonstrates how to join two strings:
<!DOCTYPE html> <html> <body> <button onclick="show()">Joined Strings</button> <p id="myid"></p> <script> function show() {a var myStr1 = "One"; var myStr2 = "Time!"; var res = myStr1.concat(myStr2); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output:
Let us now see another example wherein we will join three strings. Now we have three strings:
var myStr1 = "Only"; var myStr2 = " One"; var myStr3 = " Time!";
Join three strings with the concat() method but with an extra parameter for the 3rd string:
myStr1.concat(myStr2, myStr3);
The example that joins three strings:
<!DOCTYPE html> <html> <body> <button onclick="show()">Joined Strings</button> <p id="myid"></p> <script> function show() { var myStr1 = "Only"; var myStr2 = " One"; var myStr3 = " Time!"; var res = myStr1.concat(myStr2, myStr3); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays the result of three strings in a new string on the click of a button:
Let’s say the following is our string with numbers and special characters:
var strNum = "DEMO989#@#@";
The following RegExp is used to get a non-digits:
\D/g
Above we have set the g flag to perform global match.
The following is the code:
<html> <head> <title>Regular Expression in JavaScript</title> </head> <body> <script> var strNum = "DEMO989#@#@"; var regExp = /\D/g; document.write("String with numbers and characters = "+strNum) var res = strNum.match(regExp); document.write("<br>Getting Non-Digits = "+res); </script> </body> </html>
The output displays non-digits:
String with numbers and characters = DEMO989#@#@ Getting Non-Digits = D,E,M,O,#,@,#,@
The trim() method is used to remove whitespace from both sides of a string.
Let’s say we have the following string with leading and trailing whitespace:
var myStr = " Cup of tea! ";
To remove whitespaces, use the trim() method:
myStr.trim( )
The example demonstrates how to remove whitespaces from both the sides of a string in JavaScript:
<!DOCTYPE html> <html> <body> <script> var myStr = " Cup of tea! "; document.writeln("String (after removing leading and trailing whitespace): "+myStr.trim()); </script> </body> </html>
The output displays the same string after removing the leading and trailing whitespace:
String (after removing leading and trailing whitespace): Cup of tea!
Events handlers assist in JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a window also comes under event.
The following are the event handlers in JavaScript:
Event Handers | Triggers |
---|---|
onblur | When the window loses focus |
onchange | When an element change. |
onclick | On a mouse click |
ondblclick | On a mouse double-click |
ondrag | When an element is dragged |
ondragend | At the end of a drag operation |
ondragenter | When an element has been dragged to a valid drop target |
ondragleave | When an element is being dragged over a valid drop target |
ondragover | At the start of a drag operation |
ondragstart | At the start of a drag operation |
ondrop | Dragged element is being dropped |
ondurationchange | When the length of the media is changed |
onerror | When an error occur |
oninput | When an element gets user input |
oninvalid | When an element is invalid |
onkeydown | When a key is pressed |
onkeypress | When a key is pressed and released |
onkeyup | When a key is released |
onmousedown | Triggers when a mouse button is pressed |
onmousemove | Triggers when the mouse pointer moves |
onmouseout | Triggers when the mouse pointer moves out of an element |
onmouseover | Triggers when the mouse pointer moves over an element |
onmouseup | Triggers when a mouse button is released |
onmousewheel | Triggers when the mouse wheel is being rotated |
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output: Event gets triggered when you click on the button to generate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
The “use strict” is a literal expression introduced in ECMAScript version 5. It indicates that the code should be executed in "strict mode", which in turn considered a good practice.
The key use of this mode is if you won’t declare a variable and use it, then an error would be visible. Let us see what we discussed using the following example:
<script> "use strict"; // a is not defined a = 10; </script>
Since, variable “a” is not defined above, the following error would be visible if you will Press F12 for debugging:
a is not defined
The following is not allowed in strict mode with “use strict”:
Case1: It is not allowed to delete a variable in strict mode
"use strict"; // error var a = 10; delete a;
Above generates the following error in strict mode, when you will enable debugging with F12 on web browser:
Error: Deletion of an unqualified identifier in strict mode
Case 2: Using Octal numeric literals are not allowed
<script> "use strict"; // error var a = 012; </script>
Above generates the following error in strict mode, when you will enable debugging with F12 on web browser:
Error: Octal literals are not allowed in strict mode
When data is sent to a web server, it has to be in the form of string. The JSON.stringify() method is used in JavaScript to convert an object to string.
Let’s say we have the following object in JavaScript:
var ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 };
Now use the JSON.stringify() method to convert the above object into string:
var res = JSON.stringify(ob);
Now, display it with innerHTML. Let us see the example:
<!DOCTYPE html> <html> <body> <h2>JSON String</h2> <p id="myid"></p> <script> var ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 }; var res = JSON.stringify(ob); document.getElementById("myid").innerHTML = res; </script> </body> </html>
The output generates the string:
The Math.abs() method is used in JavaScript to find the absolute value of a number.
The following is the parameter of abs(val) method:
The method returns:
Let us see an example to get the absolute value of a negative number:
var val = -9.50;
To get the absolute value:
Math.abs(val);
The entire example:
<!DOCTYPE html> <html> <body> <script> var val = -9.50; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output returns the negative value:
Number: -9.5 Absolute Value: 9.5
Let us see another example for “null” as input:
<!DOCTYPE html> <html> <body> <script> var val = null; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output:
Number: null Absolute Value: 0
Let us see another example to get the absolute value:
<!DOCTYPE html> <html> <body> <script> var val = 15+30+55; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output:
Number: 100 Absolute Value: 100
The NEGATIVE_INFINITE property is a property of the Number Object in JavaScript, which is negative infinity.
The following is the syntax:
Number.NEGATIVE_INFINITY;
The return value is -Infinity. Let us now see an example:
<!DOCTYPE html> <html> <body> <script> var val = 5; document.write(val.NEGATIVE_INFINITY); </script> </body> </html>
The output:
Undefined
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
To display a blink text, use the blink () method in JavaScript. The string blinks using this method.
Note: The blank() method is not part of the standard now and the <blank> element is obsolete. Therefore, it may not work on modern web browsers.
Let us see an example:
<html> <body> <script> var myStr = "Learn!"; var res = myStr.blink(); document.write(res) </script> </body> </html>
The output displays the text and it may or may not blink, since the method is not part of the standard now:
Learn!
To reference an object's properties or methods, use the with keyword.
The syntax:
with (obj){ properties used without the object name and dot }
The “obj” becomes the default object for the duration of the block that follows. Now the object’s properties and methods can be used without even naming the object.
The example demonstrates the usage of with keyword:
<html> <head> <title>JavaScipt with keyword</title> <script> function stock(count){ with(this){ inventory = count; } } function product(pname, category, id){ this.pname = pname; this.category = category; this.id = id; this.inventory = 0; this.stock = stock; } </script> </head> <body> <script> var p = new product("Shirt", "Clothing", 17); p.stock(100); document.write("Product Name : " + p.pname + "<br>"); document.write("Product Category : " + p.category + "<br>"); document.write("Product ID : " + p.id + "<br>"); document.write("Product Inventory : " + p.inventory + "<br>"); </script> </body> </html>
The output:
Product Name : Shirt Product Category : Clothing Product ID : 17 Product Inventory : 100
It is said in JavaScript that almost everything is an object. JavaScript has many native or built-in objects.
Let us see some of them:
Example: Create an object
Let us now see how to create an object in JavaScript. To create an object in JavaScript, use “new” as shown below. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create an object using Object() constructor:
<html> <head> <title>Objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
The output:
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance"; department.id = 005; department.location = "North";
Example: Create a Boolean Object
The Boolean object represents two values, i.e. "true" or "false". Let us now see an example wherein we will create a Boolean object and return the value. We are using Boolean valueOf() method:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>
The output:
Value = true
Here is another example wherein we are returning the string representation of a Boolean value. We are creating a Boolean object first:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>
The output:
String = false
Example: Create a Number Object
The Number object represents numerical date, i.e. integers or floating-point numbers.
Let us now see how to create a Number object:
var val = new Number(25);
Let us now create an object with floating-point value:
var val = new Number(35.90)
An example here is to get the value of the specified Number object. We are creating a Number object:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(35.70); document.write("Value = " + val.valueOf()); </script> </body> </html>
The output:
Value = 35.7
Let us now create another Number object and represent it in String:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(90); document.write("String: " + val.toString()); </script> </body> </html>
The output:
String: 90
Yes, <noscript> element do exist in JavaScript. Use this element to set a message for users if the web browser they are using do not support JavaScript. This is also useful if the scripts have been disabled in the web browser.
The following is an example:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
The JavaScript engine adds a prototype property to the function when a function is created. This prototype property is an object. The objects inherit the properties and methods from their prototype.
Access the function’s prototype property using the following syntax:
functionName.prototype
Here’s an example: <!DOCTYPE html> <html> <body> <h2>Player</h2> <p id="details"></p> <script> function Team(rank, name) { this.rank = rank; this.name = name; } var res = new Team("3", "Jacob"); document.getElementById("details").innerHTML = "The name of the Player is " + res.name; </script> </body> </html>
The output:
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one.
JavaScript Closures
A closure is a function in JavaScript which have access to the parent scope, even after closing the parent function.
Let us see an example:
<!DOCTYPE html> <html> <body> <p>Increment by 5</p> <button type="button" onclick="show()">Count!</button> <p id="myid">0</p> <script> var sum = (function () { var count = 0; return function () {count += 5; return count;} })(); function show(){ document.getElementById("myid").innerHTML = sum(); } </script> </body> </html>
The output:
After clicking “Count” above, the value increments by 5:
In the above example, the following variable is assigned the return value of a function which is self-invoking:
var sum = (function () {
The self-invoking function sets the count to zero:
var count = 0; return function () {count += 5; return count;}
It returns a function expression as you can see above. This makes it a function and can access the count in the parent scope as well. This is what we can call closure in JavaScript.
Anonymous functions
Creating a function without a name is what we call Anonymous functions. Let us see an example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>
The output:
750
Above, we have function without a name:
var res = function (val1, val2, val3) {return val1 * val2 * val3};
To enable JavaScript in Windows, you need to work on “Internet Options” in Windows.
Here are the steps:
Go to “START” on Windows, type “Internet Options” and click on it:
On clicking, the following dialog box would be visible:
Go to “Security” tab now and click “Custom Level”. Now you will reach the “Security Settings” dialog box:
Now under “Active Scripting”, enable “JavaScript” as shown in the following screenshot:
Click “Ok”, then “Apply” one by one on both the dialog boxes to successfully enable JavaScript on Windows.
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one.
The object properties are variables used internally in the object's methods. These variables can also be globally visible throughout the page. The properties are the values associated with a JavaScript object.
Let us see how to create and access object properties:
<!DOCTYPE html> <html> <body> <h2>Department</h2> <p id="myid"></p> <script> var department = { id: 5, name : "Finance", Location : "North" }; document.getElementById("myid").innerHTML = department.id + " is " + department.name + " department's id."; </script> </body> </html>
The following is the output:
Above we access the object properties as:
objectName.property
As shown above, we used to access object properties. Here, “Department” is our object whereas “name” is our property:
department.name
Global variables are widely used and do not create any security concern.
But Global variables should be avoided in JavaScript because these kinds of variables can be easily overwritten by others scripts. On adding a new variable with the same name can create errors if we are not cautious about its placement. To avoid such confusions, it is a good practice to avoid global variables.
Use closures and avoid the usage of global variables. The process is to work with local variables and wrap the code in closures as shown below:
<!DOCTYPE html> <html> <body> <h2>Department</h2> <p id="myid"></p> <script> var department = { id: 5, name : "Finance", Location : "North" }; document.getElementById("myid").innerHTML = department.id + " is " + department.name + " department's id."; </script> </body> </html>
To find whether the web browser supports JavaScript or not, you can test it on your local system.
Create an HTML file and use the <noscript> tag. Run the file in your browser and if it does not support JavaScript, then the message set under the <noscript> would be visible.
The <noscript> tag is used in JavaScript to allow adding an alternate message if JavaScript is disabled in the web browser. In this way a user can know whether the web browser has JavaScript or not. If it’s not there, then the message added using the <noscript> is visible.
The following is an example:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
Place the JavaScript anywhere within your web page, but it is recommended to include it within the <head> or <body> tag.
The following are the different ways in which we can include JavaScript code in an HTML
In head section
If you want the script to run on some event, then add the JavaScript code in the head section of the HTML file.
Let us see an example:
<html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input type="button" onclick="show()" value="Click" /> </body> </html>
In body section
If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example:
<html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html>
The best way to check if a variable exist in JavaScript is to verify it with null.
Let us see an example:
<html> <body> <script> var a = 4; if(a != null) { document.write("Variable do exist!"); } </script> </body> </html>
The output:
Variable do exist!
Above, we worked on the condition that a variable exist if it is not null. Therefore we checked the value if variable a like this:
if(a != null) { document.write("Variable do exist!"); }
Use CSS and jQuery to replace the default JavaScript alert pop up. Let us first see how to create an alert in JavaScript and how the default looks:
<!DOCTYPE html> <html> <body> <h1>Alerts in JavaScript</h1> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output displays a button, which is to be clicked to generate an alert:
On clicking the above button, the following alert generates:
Let us now see how we can create a fancy alert box using JavaScript library jQuery and CSS:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> function myAlertBox(msg, myYes) { var box = $("#test"); box.find(".msg").text(msg); box.find(".yes").unbind().click(function() { box.hide(); }); box.find(".yes").click(myYes); box.show(); } </script> <style> #test { display: none; background-color: blue; border: 2px solid #aaa; color: white; position: fixed; width: 250px; height: 80px; left: 50%; margin-left: -80px; margin-top: 50px; padding: 10px 10px 10px; box-sizing: border-box; text-align: center; } #test button { background-color: white; display: inline-block; border-radius: 5px; border: 1px solid #aaa; padding: 5px; text-align: center; width: 80px; cursor: pointer; } #confirm .msg { text-align: left; } </style> </head> <body> <div id = "test"> <div class = "message">Welcome to the website!</div> <button class ="yes">OK</button> </div> <h2>Fancy Alert Box</h2> <input type = "button" value = "Display" onclick = "myAlertBox();" /> </body> </html>
Under <style> above, we added the CSS code.
The output displays a button which is to be clicked to generate an alert:
On clicking the above “Display” button, the following alert is visible which we styled. The background color is not blue. The button color and style is also changed:
The <noscript> tag is used in JavaScript to allow adding an alternate message if you disable JavaScript in the web browser. In this way a user can know whether the web browser has JavaScript or not. If it’s not there, then the message added using the <noscript> is visible.
The following is an example that ells itself whether JavaScript is disabled in the web browser or not:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
An inline function is assigned to a variable created at runtime. It is assigned to a variable and can be easily reused.
The following code snippet display that inline functions are assigned:
var show = function() { alert ('This is inline!') };
Creating a function without any name is what we call Anonymous functions.
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>
The output:
750
The javascript:void(0) evaluates an expression even if its addition to a web page brings unwanted output.
Use the void(0) to get the undefined primitive value. Here, we are preventing the page from loading on clicking the hyperlink:
<html> <head> <script> <!-- //--> </script> </head> <body> <p>On clicking the below link, nothing will happen...</p> <a href="javascript:void(0)">Try to click me!</a> </body> </html>
The output is displayed below. Nothing happens when the link is clicked:
Get the pixels of the current document scrolled to from the upper left corner of the window, vertically using the pageYOffset property. An example displays the same and returns the pixels:
<!DOCTYPE html> <html> <head> <style> div { height: 1300px; width: 1300px; } </style> </head> <body> <script> function display() { window.scrollBy(200, 200); alert("pageYOffset pixels = " + window.pageYOffset); } </script> <button onclick="display()" style="position:fixed;">Display</button> <br><br><br> <div> </div> </body> </html>
Let’s say the following is your array:
var a = [99, 150, 299, 340, 390, 450, 590, 600];
Now, get the length of the array:
var len = a.length;
Loop until the length of the array is more than 0. Use Math.random() to randomize the elements. Decrement the value of len (length) after every iteration for each element:
while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; }
The following is an example that shuffles an array:
<html> <body> <script> function show(a) { var len = a.length; var t, index; while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; } return a; } var a = [99, 150, 299, 340, 390, 450, 590, 600]; document.write("Array = "+a); document.write("<br>Shuffling the array = "+show(a)); </script> </body> </html>
The output:
Array = 99,150,299,340,390,450,590,600 Shuffling the array = 390,340,150,590,99,450,299,600
JavaScript provides a join() method to join the elements of an array. While joining, you can set the separator as well:
array.join(separator)
Here, separator is the resultant array would be specified by this separator. Comma is the default separator.
The return value is the strings as array elements separated by the separator.
Let us see an example wherein we have the following array:
var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"];
The example to convert array into comma-separated list:
<!DOCTYPE html> <html> <body> <script> var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"]; document.write(products.join()); </script> </body> </html>
The following is the output:
Shoes,Cap,TShirt,Shirt,Trousers
The var and let are used to declare a variable in JavaScript. The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can also be declared with var, but the usage of var are scoped to the function block level.
Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block.
Example of let
Let us see an example of let. The variable declared in the loop does not redeclare the variable outside the loop:
<!DOCTYPE html> <html> <body> <h3>JavaScript let</h3> <p id="myid"></p> <script> let i = 2; for (let i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays the value if i variable as 2:
Example of var
Let us see the same example and place var in place of let to work with variables:
<!DOCTYPE html> <html> <body> <h3>JavaScript var</h3> <p id="myid"></p> <script> var i = 2; for (var i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays the value of i variable as 10:
The Number object is for integers, floating-point numbers, etc. Let us now see how to create a Number object:
var val = new Number(10);
Let us now create an object with floating-point value:
var val = new Number(25.90);
An example here is to get the value of the specified Number object. We are creating a Number object:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(25.90); document.write("Value = " + val.valueOf()); </script> </body> </html>
The output:
Value = 25.9
Let us now create another Number object and represent it in String:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(40); document.write("String: " + val.toString()); </script> </body> </html>
The output:
String: 40
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
The length property is used in JavaScript to get the length of a string:
The syntax:
string.length
Let’s say the following is our string:
var myStr = "This is an example!";
Now get the length of the string in a new variable:
var res = myStr.length;
The following is an example that displays the string length:
<html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = "This is an example!"; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>
The output:
Length = 19
Let us now see what we will get when we will try to find the length of an empty string:
<html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = ""; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>
The output displays 0 since it is an empty string:
Length = 0
The document.write() method writes JavaScript code to a document. It also writes HTML expressions.
The syntax:
document.write(expression1, expression2, expression3, ...)
Here, expression1, expression2, expression3 are the expressions to be written to the output stream.
Let us now see an example to write HTML elements with document.write():
<!DOCTYPE html> <html> <body> <script> document.write("<p>John Cena</p>"); </script> </body> </html>
The output:
John Cena
Let us see another example to write text to stream with document.write():
<!DOCTYPE html> <html> <body> <script> document.open(); document.write("<p>Travis Head</p>"); document.close(); </script> </body> </html>
The output:
Travis Head
To display an alert box in JavaScript, use the alert() method. The alert box would have an OK button.
The syntax:
alert(msg)
Here, msg is the text which is to be displayed in the alert box. Shown below under alert():
function show() { alert("This is an alert box!"); }
The following is an example:
<!DOCTYPE html> <html> <body> <p>Below button displays an alert...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output:
On clicking the above button, the following alert generates and the message we added as parameter is visible:
You may be wondering how we can add a multi-line message in an alert box in JavaScript. For that, just use \n as shown below:
<!DOCTYPE html> <html> <body> <p>Below button displays an alert with multi-line content...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is first line!\nThis is next line!"); } </script> </body> </html>
The output:
On clicking the above button, the following alert generates and the multi-line message we added as parameter is visible:
Unfortunately, Boolean Typed array do not exist in JavaScript. The following typed arrays exist in JavaScript: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, etc.
Let us see an example of Int8Array typed array. The Int8Array typed array represents an array of twos-complement 8-bit signed integers.
The following is the syntax:
new Int8Array(); new Int8Array(length); new Int8Array(typedArray);
The following is an example:
<!DOCTYPE html> <html> <body> <script> var val = new Int8Array(5); val[3] = 9; // length of array document.write("Array Length = "+val.length); // displaying array elements document.write("<br>Array elements..."); document.write("<br>"+val[0]); document.write("<br>"+val[1]); document.write("<br>"+val[2]); document.write("<br>"+val[3]); </script> </body> </html>
The output:
Array Length = 5 Array elements... 0 0 0 9
“True” and “False” are the two values in a Boolean object. Let us now see how to create a Boolean object:
var val = new Boolean(false);
Let us now see an example wherein we will create a Boolean object and return the value. We are using Boolean valueOf() method:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>
The output:
Value = true
Here is another example wherein we are returning the string representation of a Boolean value:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>
The output:
String = false
To display the unicode of the character at a specified index in a string with JavaScript, use the charCodeAt() method.
Let us now see the syntax:
string.charCodeAt(index)
Here, “index” is the index of the character we are willing to return.
The method returns the Unicode of the character. However, "NaN" is returned if no character is found at the index we added as the parameter.
The following is an example:
<!DOCTYPE html> <html> <body> <script> var myStr = "Chatting!"; var res = myStr.charCodeAt(0); document.write( "Unicode = " + res.toString() ); </script> </body> </html>
The output displays the returned Unicode of the 1st character, since we added parameter as 0:
Unicode = 67
The following is another example wherein we will find out the Unicode for character at index 2:
<!DOCTYPE html> <html> <body> <script> var myStr = "Hit Wicket!!"; var res = myStr.charCodeAt(2); document.write( "Unicode = " + res.toString() ); </script> </body> </html>
The output displays the returned Unicode of the 3rd character, since we added parameter index as 2:
Unicode = 116
Let us see a condition in which we are finding the character at a position where there is no character:
<!DOCTYPE html> <html> <body> <script> var myStr = "abc"; // 5th character does not exist var res = myStr.charCodeAt(5); // NaN is returned document.write( "Unicode = " + res.toString() ); </script> </body> </html>
Above, “NaN” is returned since there is no character at position 5th:
Unicode = NaN
The Date() method is to be used in JavaScript to get today’s date and time.
The following is the syntax:
Date()
Let us see the example to display the current date and time:
<!DOCTYPE html> <html> <body> <script> var date = Date(); document.write("Date and Time = " + date ); </script> </body> </html>
The output displays today’s date and time:
Date and Time = Fri Dec 14 2018 20:16:22 GMT+0530 (India Standard Time)
Let’s say you need to only fetch the time portion of the date. For that, use the toTimeString() method:
<!DOCTYPE html> <html> <body> <script> var date = new Date(2018, 12, 14, 10, 11, 30); document.write( date.toTimeString() ); </script> </body> </html>
The output displays only the current time:
10:11:30 GMT+0530 (India Standard Time)
The Date.parse() method is used in JavaScript to parse a string representation of date and time.
Let us first see the syntax:
Date.parse(str)
Here, str is the date string.
The method parses the date and returns the number of milliseconds since midnight of January 1, 1970.
Let us see an example now:
<!DOCTYPE html> <html> <body> <script> var res = Date.parse( "Dec 14, 2018 16:45:00" ); document.write( "Number of milliseconds between the date mentioned above and 1970 = " + res ); </script> </body> </html>
The output:
Number of milliseconds between the date mentioned above and 1970 = 1544786100000
To convert a date object to string in JavaScript, use the toLocaleString() method.
The following is the syntax:
Date.toLocaleString();
Create a Date object:
var date = new Date();
Now convert the above date object to string:
date.toLocaleString();
The example demonstrates how to convert Date object to string:
<!DOCTYPE html> <html> <body> <script> var date = new Date(); var res = date.toLocaleString(); document.write(res); </script> </body> </html>
The output:
12/14/2018, 8:25:52 PM
The Math.random() method displays a floating-point pseudo-random number between 0 and 1.
Note: The value is inclusive of 0 and exclusive of 1
The following is an example:
<!DOCTYPE html> <html> <body> <script> var num = Math.random( ); document.write("Random number = " + num ); </script> </body> </html>
The output displays any random number between 0 and 1:
Random number = 0.8085646074894297
When we will run the above program again, a new random value between 0 and 1 will get generated as shown below:
Random number = 0.1117848013962992
To remove the last element from an array in JavaScript, use the pop() method.
The following is the syntax:
array.pop()
Let’s say we have the following array:
var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];
To remove an element, use the pop() method:
var element = arr.pop();
Let us see an example wherein we are removing 5 elements:
The method returns the removed element from the array. In the below example, we have an array and we have removed the last element from the array. With that we have removed 4 more elements from the end one by one using the pop() method:
<!DOCTYPE html> <html> <body> <script> var arr = [20, 11, 44, 39, 88, 48, 89, 47 ]; document.write("Array = "+arr); document.write("<br><br>Removing 5 elements...<br>"); var element = arr.pop(); document.write("Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); </script> </body> </html>
The output:
Array = 20,11,44,39,88,48,89,47 Removing 5 elements... Popped Element = 47 Popped Element = 89 Popped Element = 48 Popped Element = 88 Popped Element = 39
Yes, we can add one or more element to the front of an array using the unshift() method.
Let us first see the syntax of the unshift() method to understand it further:
array.unshift( e1, e2, e3, ..., eN );
Here, e1, e2, e3, … , en are the elements to be added in the front of the array.
We added the following elements to the array:
var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];
Let’s say we need to add a new element in the front of the above array. For that set the element value as a parameter in the unshift method as shown below:
var len = arr.unshift("5");
The following is an example wherein we are adding an element in the beginning of an array:
<!DOCTYPE html> <html> <body> <script> var arr = [20, 11, 44, 39, 88, 48, 89, 47 ]; document.write("Array = "+arr); // adding element 5 in the front var len = arr.unshift("5"); // displaying the new array document.write("<br>New array = " + arr ); document.write("<br /> Length of the array = " + len ); </script> </body> </html>
The output:
Array = 20,11,44,39,88,48,89,47 New array = 5,20,11,44,39,88,48,89,47 Length of the array = 9
The !! operator is the not operator twice. It is useful in working through the truth value and returns a Boolean value.
Let us see an example:
<!DOCTYPE html> <html> <body> <script> var val1 = "This is an example"; var val2 = !!val1; document.write(val2); </script> </body> </html>
The output:
True
Let us see another example for integer and apply double not to it:
<!DOCTYPE html> <html> <body> <script> var val1 = 10; var val2 = !!val1; document.write(val2); </script> </body> </html>
The output:
True
NaN suggests that the entered value is not a legal number. It is a JavaScript property, which can also be considered as a "Not-a-Number" value.
To determine the entered value is a number or not, you can use the Number.isNaN() method. If the result is “True”, then it would that the given value is not a number, whereas “False” would mean the value is a legal Number.
Let us see an example:
<!DOCTYPE html> <html> <body> <script> var a = "Grill"; document.write(isNaN(a)); </script> </body> </html>
The output displays True since the above value is not a legal number:
True
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 10; document.write(isNaN(a)); </script> </body> </html>
The output since the above value is a legal number:
False
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 0/0; document.write(isNaN(a)); </script> </body> </html>
The output generates True since 0/0 is not a legal number:
True
The “undefined” is used to unset a variable in JavaScript.
Declare and initialize a variable:
]var a = 50;
Now reassign the variable with undefined since we wish to unset it:
a = undefined;
The following is an example:
<!DOCTYPE html> <html> <body> <script> var a = 50; a = undefined; document.write(a); </script> </body> </html>
The output displays undefined:
Undefined
If you are implicitly declaring the variable without var keyword, then use the delete to unset a variable:
<!DOCTYPE html> <html> <body> <script> a = 10; delete a; </script> </body> </html>
The double NOT Bitwise operator is a “double tilde” (~~) operator in JavaScript.
Let’s say we have the following variable:
var val1 = 3.7; var val2;
Now, use the double tilde operator and assign it to another variable:
val2 = ~~val1;
The example to work with double tilde operator:
<!DOCTYPE html> <html> <body> <script> var val1 = 3.7; var val2; val2 = ~~val1; document.write(val2); </script> </body> </html>
The output:
3
You can achieve the same result from Math.floor() in JavaScript, but double tilde is considered faster:
<!DOCTYPE html> <html> <body> <script> var val1 = 3.7; document.write(Math.floor(val1)); </script> </body> </html>
The same output is visible:
3
Generally, in JavaScript we create functions using the function keyword:
var points = [98, 45, 78, 65, 99]; var demo = points.map(function(val) { return val + val; })
Using the Fat arrow function reduces line of code and even avoids you to write the keyword “function” again and again.
The syntax of fat arrow function includes =>, wherein it shows fat arrow:
arg => exp
For multiple arguments:
(arg1 [, arg2]) => exp
Let’s see what you need to do with fat arrow function while implementing the code snippet we saw above:
var points = [98, 45, 78, 65, 99]; var demo = points.map((val) => val+val);
The substr() and substring() methods are simpler, yet they have some differences. The 2nd argument of the substring() method is the index to halt the search, whereas the 2nd parameter of substr() is the maximum length.
Note: We will be taking the same string and the same parameter value for both the functions to make it easier to understand
substr() method
The substr() method returns the characters in a string beginning at the specified location. It goes through the number of characters which is specified by the user.
The parameters of substr(start, len):
Let us see an example.
We have the following string:
var myStr = "Knowledge Hut!";
Now, we will use substr() as discusses above with the parameters to get 5 elements beginning from 3rd index:
myStr.substr(3,5)
The example:
<html> <head> <title>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substr(3,5)); </script> </body> </html>
The output from 3rd index.
5 is the length of elements after beginning with 3rd index:
(3,5): wledg
substring() method
The substring() method returns subset of a string.
The parameters of substring(i1, i2):
Let us see an example.
We have the following string:
var myStr = "Knowledge Hut!";
Now, we will use substring() as discussed above with the parameters to get substring from 3 to 5, since we set the parameter as 3 and 5:
myStr.substring(3,5)
The example:
<html> <head> <title>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substring(3,5)); </script> </body> </html>
The output from substring 3 to 5:
(3,5): wl
A staple in JavaScript technical interview questions and answers, be prepared to answer this using your hands-on experience.
Prototypal inheritance is to add new capabilities to a constructor function using Prototype.
Let’s first understand what are Constructor functions. They are basically JavaScript way to implement the concept of Classes.
Let’s consider the example below, where we have a “Car” constructor function. In it we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel().
let Car = function(model) { this.model = model; this.getModel = function() { return this.model; } } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan');
console.log(maryCar.getModel()); //nissan
Now, the problem is that every time we create a new instance we get a new copy of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing.
We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps.
In JavaScript as you know everything is an Object. Whenever a function is created there are two object one is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.
Every instance created from the function have access to the Prototype object. Now, let’s move our getModel() outside our Constructor function using prototype.
let Car = function(model) { this.model = model; } Car.prototype.getModel = function() { return this.model; } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan'); console.log(maryCar.getModel()); //nissan
We get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log.
JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
Many people think JavaScript is asynchronous because we can do async tasks like setTimeout, callbacks, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs.
The browser have a Call Stack, Browser API and Message Queue and the order of their processing is called event loop.
We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works.
function main() { console.log('A'); setTimeout(function(){ console.log('B'); },0); console.log('C'); } main();
//Output
//A //C //B
The output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution.
The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.
This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from.
Every function in JavaScript have call, apply and bind methods. These methods can be used to set the custom value of “this” to the execution context of the function.
call
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers.
Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; console.log(addNumbers.call(obj, 1, 4, 6)); //14
apply
It is totally similar to call, but the only difference is that we can pass array as the second argument. We will use the same code for apply also. But now we have an arr, to be passed as second argument.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; let arr = [7, 3, 8]; console.log(addNumbers.apply(obj, arr)); //21
bind
Bind works in a bit different way then call and apply. It works by returning a copy of the function. We will take the returned function in bindFunc and then execute it in the next line.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; let bindFunc = addNumbers.bind(obj); console.log(bindFunc(7, 3, 8)); //21
There are four solutions to access “this” inside the innerFunc().
Solution 1
Use a “that” variable in cleanRoom() for accessing “this” inside innerFunc(). Basically “that” is nothing but the outer “this”.
const cleanRoom = function(soap) { let that = this; const innerFunc = function(_soap) { console.log(`Cleaning ${that.room} with ${_soap}`) } innerFunc(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 2
Use call method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) { const innerFunc = function(_soap) { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc.call(this, soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 3
Use bind method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) { const innerFunc = function(_soap) { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc.bind(this)(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 4
Use arrow function in the innerFunc(). Arrow functions have special meaning for “this” and it is that, it takes the value of “this” from the enclosing scope and is very useful in this case.
const cleanRoom = function(soap) { const innerFunc = (_soap)=> { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
One of the main use of “call” is to change an array like object to array.
There is an array like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into array, because arrays have a lots of functionality.
Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities.
let sumNumbers = function() { console.log(arguments); } sumNumbers(1, 2, 3, 4);
Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is converted into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the sum of the number of arguments passed to it.
let sumNumbers = function() { const argsToArray = [].slice.call(arguments); console.log(argsToArray); return argsToArray.reduce((acc, curr) => acc + curr); } console.log(sumNumbers(1, 2, 3, 4)); //10 console.log(sumNumbers(1, 2, 3)); //6
The second application of call is in inheritance , using constructor functions.
Consider the below example. Here in the Cat function, we called its parent Mammal using call method with “this” of Cat.
let Mammal = function(legs) { this.legs = legs; } let Cat = function(legs, isDomesticated) { Mammal.call(this, legs); this.isDomesticated = isDomesticated; } let tiger = new Cat(4, false); let homeCat = new Cat(4, true); console.log(tiger); // { legs: 4, isDomesticated: false } console.log(homeCat); // { legs: 4, isDomesticated: true }
One of the practical use of apply is to pass an array to a function, which expects arguments only.
Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding.
let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29
One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor.
Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.
class Foo extends React.Component{ constructor( props ){ super( props ); this.state = { text: '' }
this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.setState({ text: event.target.value }) } render(){ return ( <input type="text" value={this.state.text} onChange={this.handleChange} /> ); } } ReactDOM.render( <Foo />, document.getElementById("app") );
This is one of the most frequently asked JavaScript interview questions and answers for freshers in recent times.
The output logged will be:
undefined Johnny Deep
The first console.log prints undefined because heroIdentity()is been invoked in the global context (i.e., the window object) where the _name property doesn’t exists.
The way to fix it is by binding, it to hero object by using bind.
var heroIdentity = hero.getIdentity.bind(hero);
The output logged will be:
10 2
When inside the method, fn() is called the “this” of the function fn is at window level. So, “this.length” will produce 10.
Now, when arguments[0]() is called, then argument[0] is equivalent to “fn” and function fn is called. But “this” now is the arguments array, which is of length 2 because it contains two arguments (fn, 1). So, “this.length” will produce 2.
The output logged will be: null
The reason is for prototype chaining. The __proto__ of ‘hello’ is the global String.
console.log(('hello').__proto__);
Then the __proto__ of it is the global Object.
console.log(('hello').__proto__.__proto__);
Now, the Object is the final thing from which everything in JavaScript is created and it points to null.
This is one of the most frequently asked JavaScript interview questions and answers for freshers in recent times.
Nested promises are set of promises in which , the result of one promise we call another in the .then statement. It is very useful in practical applications, where the result of fetch from an API endpoint will result in sending the data to another endpoint. Nested promises can also be done with callback functions, but the code get complicated soon.
Let’s look at an example of nested promises. Here we have three functions which return promises- movieTicketQueue, buyPopcorn and happyPartner. Now only the movieTicketQueue is returning resolve() or reject() depending on random number. The other two functions are returning only resolve() for simplicity sake.
Now, when the movieTicketQueue function is run and return a resolve(), then the immediate .then block will be run or else we will go to the .catch block. In the .then we are returning the next buyPopcorn and in its .then we are returning the happyPartner. We are passing the message from one function to other, so it will be appended.
On running the code and getting a resolve, because we random number greater than 0.5, we get below output.
On running the code and getting a reject, because we random number less than 0.5, we get below output.
We can implement the Array.prototype methods by using callbacks and actually this is the way it is implemented in JavaScript internally.
forEach
We are implementing our version of forEach as myEach by having the callback attached to the prototype, which is available to every JS function. Here “this” is equal to the array. So, we are iteration over it using traditional for loop and calling the callback function on each iteration.
map
We are implementing our version of map as myMap, by creating an empty array in our function and then pushing it in the iteration. From inside the push we are calling our callback, so when we are calling it we can use something like Math.round(line 17) to change an individual item or just return it like in line 13.
filter
We are implementing our version of filter as myFilter. The process is quite similar to map, where we create an empty array ad push to it. But as we know that filter goes through the array and gives an subset of elements depending on boolean expression.
Here when we iterate through the array and call the callback in an if statement, and if it’s true we are pushing the item into the array.
Implement your version of Array.prototype methods some, every and reduce in vanilla JavaScript ?
We will be implementing some, every and reduce by using of callbacks, in the same way, we used to implement forEach, map and filter in the previous question.
some
The Array prototype method some returns true if any element of the array fulfils the condition we are testing. Here also like filter, we will have the callback been checked in an if statement in every iteration. This will test our condition and even if one of it pass we return a true and get out of loop. If the iteration is complete, it means not a single element satisfy condition and we return false.
every
It is the opposite of some. The method “every” will return true only if every element passes the test. Here we do a trick in the if statement. We check the opposite of the test, so say if element should be greater than 10, we are checking for less than 10. So, if even one is less than 10 we return false. And if we iterate through whole loop, means all element satisfy the condition so we return true.
reduce
The method reduce is considered the hardest in the Array prototype methods to master. It is because it’s concept is quite different. It takes the whole array and iterate through it and returns a single value. It is useful to do sum/multiply/subtract of all the elements of an array, but is more powerful than that. To do this it have an accumulator, which is used to hold the number in each run. This accumulator will be operated with the current value of the iteration.
Now in our implementation, we first check whether an accumulator was supplied or else make it to undefined. Now inside the loop we update the accumulator variable by using the callback.
Named after Haskell Brooks Curry, currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.
In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.
Here is a simple example to write a simple multiply function and then the function asked in the question with currying.
Currying works because of JavaScript concept of closures. The closure created by the nested functions to retain access to each of the arguments. So inner function which do “return a * b * c * d” have access to all arguments.
Expect to come across this, one of the top JavaScript interview questions for experienced professionals in web development, in your next interviews.
Map and WeakMap are data structures that were introduced in ES6.
Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted.
Let’s find out the reason for Map by analysing a problem with Objects. In the below example, we have an object “x” and another object “a”. Now we are using “a” as a key and push a value to “x”. Now, if we console log “x” the key is shown as [object object], but then also we can extract it’s value by x[a].
But the real problem occurs when we add another object to “x” for key. It over-writes the earlier object. This occurs because in JavaScript we can have only 1 key as an object.
Now we will look at how Maps help. We create Map by the new keyword. And also to add to Map we need use one of its method set.
In the below example the objects “a” and “b” are been added as key successfully.
Notice that the __proto__ object contains Symbol.iterator, so the for..of loop can be used to iterate over it like arrays. The same is not true for Objects.
We iterate over Map using the for..of loop. We get an array of [key, value] for each element in Map. So, we de-structure it into [key, value] pair.
If we add the same object as key as in line 9 for “a”, the Map will over-write the old value of the key.
Also, we can delete an entry by passing it’s key in delete method.
There is one problem with Map and it is that it holds the Map’s key, even if the original key is deleted. That is the reason we use WeakMap. So, WeakMap allows garbage collector to work as it holds a weak reference to its key but Maps doesn’t allow garbage collector to work.
Another difference is that keys of WeakMaps are of type Object only. Primitive data types(Number, String, Boolean, Symbol) can only be used in Maps.
Set and WeakSet are also new data structures introduced in ES6 along with Map and WeakMap. Set are data-types like arrays, but the key feature is that we cannot keep duplicate data. In a nutshell Sets are nothing but unique arrays.
Let consider below example. The way to create a Set is through the constructor function using “new” keyword. We add value to Set by using add method and delete value from Set using delete method.
Notice that it’s __proto__ object have Symbol.iterator like array, which means it is iterable.
There is another method to create a Set. We can pass an iterable like array to the constructor function.
Also, we cannot add duplicates value in a Set. Also we can add values to Set using add in method chaining format. All are shown in below example.
We can use this feature to get unique items from an array containing duplicate items. Notice at Line 3, we are using spread operator inside an array. It is because Set is not exactly array and we are converting it to array.
WeakSets are like WeakMaps and one of key feature is that we cannot have Primitive data-types(Number, String, Boolean, Symbol) as it’s items. So, the below will throw and error.
So, we will add Objects to WeakSet. Also, notice that it’s __proto__ doesn’t have many methods and it is not an iterable.
Symbols are the new primitive data-type introduced in ES6. Symbols is unique and immutable data-type. They are tokens that can be used as unique ids.
Two Symbols are never the same, even if they are declared as same. Consider the below example.
We can also put some value inside the constructor in Symbol, which helps in identifying it. Also, it’s typeof is symbol
We cannot directly concatenate it to a Sting as it will throw an error.
So, we convert a Symbol into a String by using string in-built function toString().
One of the use case of Symbol is to be used as unique keys. We can use them very efficiently in Objects and Maps, where only unique keys are allowed.
A must-know for anyone looking for top JavaScript coding interview questions. This is one of the frequently asked JavaScript questions today.
The concept of Sub-classes and inheritance is like that in other languages like Java and C++. The sub-class can inherit properties from its parent class and can also override or update an existing method.
Let’s consider the below example. We have a Parent class “Mammal” and a Sub-class “Bat” which is inheriting from it. Notice, that we have use the “extends” keyword.
To use the “legs” and “name” variable in “Bat”, we use the “super()” method. Also, notice that we can use update “walk()”, and add additional functionalities.
To understand iterators, we will first look into recently introduced [Symbol.iterator] property in data types.
This indicates whether a data structure is iterable or not. This includes array, strings, Map, Sets and NodeList. Objects doesn’t have a [Symbol.iterator] property.
If we check the __proto__ of an array, we can find the [Symbol.iterator] property.
But it is not the case with Objects as it is not iterable.
Now, iterator are created using the “Symbol.iterator” and can be used to iterate over all data structures which have [Symbol.iterator] property.
Let consider the below example. Here we create an iterator by the syntax at line 3. Now we can iterate over the array using “iterator.next()”. Each run gives and Object which have the “value” and “done”, which specifies whether there is an element. Notice, after the fifth run we get the “value” as undefined and “done” as true.
ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped.
Let’s look at the below example. The generator function have a special syntax with “*”. Also, inside the generator we have “yield” statements. Each “next()”, goes to the next yield statement.
The above example doesn’t shows any advantages of generator and it is same as iterating through an array. But let’s look at next example, where we have an infinite while loop inside an generator.
First look at this normal function. If we run it, it will cause an infinite loop and crash your browser.
But the same type of function with generator doesn’t produce an infinite loop. It pauses every time yield is called and will generator the next value of “i” every-time “next()” is called. So, this function can be used to generate any time “i” and not like in array where we have to give the size of array in advance.
In JavaScript every object is created from a global “Object”(Notice the capital ‘O’). If we look at it in console, it have many properties and create been one of it.
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Consider the below example, where we can create a new object from the existing object and can also add new properties to it or modify an existing property.
Now, let see a practical use of Object.create in Inheritance. In below example we have an Employee function, which have two functions in its Prototype. Then we have another function SalesEmployee and then set it’s Prototype to Employee’s Prototype. We also have a function in the prototype of SalesEmployee
SalesEmployee.prototype = Object.create(Employee.prototype);
We then create an instance of the SalesEmployee as emp1 variable. It have all functions of Employee function and can also use it.
Prototype chain can be explained through below example. Here we have three functions Mammal, Whale and BlueWhale. Each have their own version of print().
We are inheriting from Mammal to Whale by setting Whale’s prototype to be Mammal’s prototype.
Then inhering from Whale to BlueWhale by setting BlueWhale’s prototype to be Whale’s prototype.
Then we have three instances of Mammal, Whale and BlueWhale. On calling the print(), we get the respective console log.
Now, let remove BlueWhale’s print() method and then if we call print() on its instance blueWhale, we get result from Whale’s print().
If we further remove Whale’s print() method and then if we call print() on its instance blueWhale, we get result from Mammal’s print().
So, if you call an method on a Child and the method is not there, it will check in its Parent and if not there then will check in Parent’s parent.
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
To understand inheritance using constructor function, we will see an example containing a Mammal parent function and Human child function. Also, make the Human’s Prototype have a reference of Mammal’s Prototype using Object.create. Human’s Prototype will have all methods of Mammal’s Prototype.
Now, let’s look into “Human” in the console. As you can see it contains “Mammal” sleep and walk function in it’s __proto__.
But we have a major problem because the statement Human.prototype = Object.create(Mammal.prototype) wipes out any Human’s Prototype function and also it’s constructor.
We didn’t declared any Human’s Prototype function, but the constructor was wiped.
So, we solve it by below code. It is using Human.prototype.constructor = Human to set the constructor back in “Human”.
Also, we are declaring Human’s Prototype function after Human.prototype = Object.create(Mammal.prototype)
... ... Human.prototype = Object.create(Mammal.prototype); Human.prototype.constructor = Human; Human.prototype.fly = function() { return 'Flying with Gliders'; }
Let’s now complete the code and create two instances of “Human” as hari and harry. Both can access functions walk, sleep and fly.
Interview Tips for Freshers
The industry is looking for candidates who can start with their work immediately and not the ones who are looking for a training. As a newbie in the IT Industry for a career as UI Developer, it’s good to learn the various UI frameworks like Vue.JS, React.JS, and Angular.js which are Javascript frameworks. To be shortlisted you can also take up some courses on these front-end technologies.
These javascript interview questions for beginners will help you to crack your javascript interview. Be prepared with the best interview questions for javascript and you will be able to pass the Javascript interview easily. All the best!
null (var null)
In JavaScript, null is a reserved identifier, therefore we cannot use it as an identifier in JavaScript. An error can be seen if we will write:
<html> <body> <script> var null; </script> </body> </html>
The following is the error visible when you will press F12 on browser:
SyntaxError: Unexpected token null
The web browser throws an error for “var null” since it is a reserved identifier.
undefined (var undefined)
The undefined is not a reserved identifier, therefore if you will write the following, then no error would be thrown:
<html> <body> <script> var undefined; document.write(undefined); </script> </body> </html>
Even if it is undefined, let us see what would be the output:
Undefined
In JavaScript, you may have seen the function name with a leading plus sign:
+function() { }();
The + is used for forcing the parse to consider whatever follows the leading plus as expression
This is how you can use + perfectly in a function invoked immediately, for example,
+function() { alert("Demo!"); }();
You can also display it as:
(function() { alert("Demo!"); })();
You can also use it like this (Closing parentheses at the end):
(function() { alert("Demo!"); }());
A staple in JavaScript technical interview questions and answers, be prepared to answer this one using your hands-on experience.
The number formatter would allow you to format numbers as the currency you want it to work.
The following is an example for US$ currency. Here we have set the currency as ‘USD’:
<!DOCTYPE html> <html> <body> <p>Average cost of a laptop (US$) </p> <script> var f = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, }); document.write(f.format(500)); </script> </body> </html>
The output:
Let us see another example in Euro. Here we have set the currency as ‘EUR’:
<!DOCTYPE html> <html> <body> <p>Average cost of a laptop (US$) </p> <script> var f = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', minimumFractionDigits: 2, }); document.write(f.format(300)); </script> </body> </html>
The output:
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The leading bang! Is used in anonymous functions:
!function(){ // }();
With that, you can also write it as:
+function(){ // }()
Generally, the leading bang (semi-colon) is used in functions in libraries. Let us see the different uses of including a leading semicolon:
Appending
The leading semicolon in immediately-invoked function expressions prevent errors when appending the file during concatenation. This concat is to a file containing an expression improperly concluded with a semicolon.
Concatenate
The purpose to include semicolon is to safely concatenate several JS files into one.
Preceding Code
A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.
Let’s see an example. Let’s say we are concatenating two files with self-invoking functions:
Function ONE
(function(){...ONE...})()
Function TWO
(function(){...TWO...})()
Now concatenating it will give the following result:
(function(){...ONE...})() (function(){...TWO...})()
Function TWO can have a leading semicolon:
!(function(){...TWO...})()
Now after concatenation:
(function(){...ONE...})();(function(){...TWO...})()
Yes, it is possible to create a custom alert box with CSS and JavaScript library jQuery.
Let us see an example wherein we have styled the alert box, it’s button, background color, border, position, etc.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> function myAlertBox(msg, myYes) { var box = $("#test"); box.find(".msg").text(msg); box.find(".yes").unbind().click(function() { box.hide(); }); box.find(".yes").click(myYes); box.show(); } </script> <style> #test { display: none; background-color: blue; border: 2px solid #aaa; color: white; position: fixed; width: 250px; height: 80px; left: 50%; margin-left: -80px; margin-top: 50px; padding: 10px 10px 10px; box-sizing: border-box; text-align: center; } #test button { background-color: white; display: inline-block; border-radius: 5px; border: 1px solid #aaa; padding: 5px; text-align: center; width: 80px; cursor: pointer; } #confirm .msg { text-align: left; } </style> </head> <body> <div id = "test"> <div class = "message">Welcome to the website!</div> <button class ="yes">OK</button> </div> <h2>Fancy Alert Box</h2> <input type = "button" value = "Display" onclick = "myAlertBox();" /> </body> </html>
The output displays the button which is to be clicked to generate the new custom alert box;
On clicking the above “Display” button, the following alert is visible which we styled:
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The setTimeout() function is used in JavaScript to delay a function call.
For example, if you want to delay the function call by 5 seconds, then you can easily achieve this using the setTimeout() function.
The following is the syntax:
setTimeout(func_name, milliseconds, arg1, arg2, ...)
Here,
The following is an example:
Let’s say we want the function cal to delay by 3 seconds, therefore we will implement the setTimeout( with a parameter as 3000 milliseconds (i.e. 3 seconds):
function display() { setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); }
The example:
<!DOCTYPE html> <html> <body> <button onclick="display()">Click</button> <script> function display() { setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); } </script> <p>Wait for 3 seconds after clicking the button</p> </body> </html>
The output displays a button:
After 3 seconds, the following would be visible since we delayed the execution:
Create a custom object in JavaScript, using the “new”. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create a custom object in JavaScript:
<html> <head> <title>Custom objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
The output:
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance";
department.id = 005;
department.location = "North";
The Array.from() method is used in JavaScript to convert the arguments object to an array.
Let us first see what Array.from() method provides us:
Array.from(obj, mapFunction, thisValue)
Here,
Here, we have a function, which we are calling with some values:
display('q', 'w', 'h', 'm', '20', '66', '35')
The display() function consider arguments and sets using the Array.from() method. With that the sort() method is used to sort the array for our example:
function display(){ var myArgs = Array.from(arguments); return myArgs.sort(); }
The following is an example to convert the arguments object to an array:
<!DOCTYPE html> <html> <body> <script> function display(){ var myArgs = Array.from(arguments); return myArgs.sort(); } document.write(display('q', 'w', 'h', 'm', '20', '66', '35')); </script> </body> </html>
The output:
20,35,66,h,m,q,w
To round a number to specified decimal place in JavaScript, the toFixed() method is to be used.
Let us first see the syntax;
number.toFixed( [digits])
Here, digits is the decimal places to be set. For example, for 1 decimal place:
variable.toFixed(1))
The following is an example to round a number to 2 decimal places in JavaScript:
<html> <head> <title>JavaScript toFixed()</title> </head> <body> <script> var a = 291.78687; document.write("Number = " + a); document.write("<br>Result (2 decimal places) = " + a.toFixed(2)); </script> </body> </html>
The output:
Number = 291.78687 Result (2 decimal places) = 291.79
Let us see another example wherein we will round a number to 3 decimal places in JavaScript:
<html> <head> <title>JavaScript toFixed()</title> </head> <body> <script> var a = 291.78687; document.write("Number = " + a); document.write("<br>Result (3 decimal places) = " + a.toFixed(3)); </script> </body> </html>
The output:
Number = 291.78687 Result (3 decimal places) = 291.787
The parseInt() method parses up to the first non-digit and returns the parsed value, whereas Number() converts the string into a number, which can also be a float.
To learn about the difference between parseInt(string) and Number(string) in JavaScript, let us see an example:
Let’s say we have the following value:
20demo
Using parseInt(string), 20 is returned:
<!DOCTYPE html> <html> <body> <script> document.write(parseInt("20demo")); </script> </body> </html>
The output:
20
Using the Number(string), the same value returns NaN:
<!DOCTYPE html> <html> <body> <script> document.write(Number("20demo")); </script> </body> </html>
The output:
NaN
Let us now workaround for a float value with both Number(string) and parseInt(string):
<!DOCTYPE html> <html> <body> <script> document.write(Number("12.99demo")); document.write("<br>"+parseInt("12.99demo")); </script> </body> </html>
The output:
NaN 12
Let’s say the following are our arrays:
[20, 40, 60] [80, 100, 120]
To merge them, JavaScript provides the Array.concat() method. The return value of this method is a new array with the result of concatenated arrays:
var res = arr1.concat(arr2);
Let us now merge the above two arrays:
<html> <head> <title>Merge JavaScript Arrays</title> </head> <body> <script> var arr1 = [20, 40, 60]; var arr2 = [80, 100, 120]; document.write("Array 1 = " + arr1); document.write("<br>Array 2 = " + arr2 ); var res = arr1.concat(arr2); document.write("<br>Merged Arrays = " + res ); </script> </body> </html>
The output displays the merged arrays:
Array 1 = 20,40,60 Array 2 = 80,100,120 Merged Arrays = 20,40,60,80,100,120
The getMinutes() method is provided by JavaScript to get the current minutes in JavaScript. The minutes are according to local time. We will add minutes to it using the setMinutes() method.
Create a Date object:
var date = new Date();
Now get the current date and time:
// current date and time document.write("Current Date and Time = "+date);
Now, under setMinutes(), get the current minutes using getMinutes() and add the minutes as shown below. We added 10 minutes here:
date.setMinutes(date.getMinutes() + 10 );
The following is an example to add 15 minutes to a date in JavaScript:
<html> <head> <title>JavaScript setMinutes() Method</title> </head> <body> <script> var date = new Date(); // current date and time document.write("Current Date and Time = "+date); date.setMinutes(date.getMinutes() + 15 ); document.write("<br>New Date = "+date); </script> </body> </html>
The output:
Current Date and Time = Sat Dec 15 2018 20:11:14 GMT+0530 (India Standard Time) New Date = Sat Dec 15 2018 20:26:14 GMT+0530 (India Standard Time)
To check whether a value entered is a NaN or not, use the Number.isNaN() method. This method returns true if the value is not a number, else false is returned.
Let’s say the following is our value:
var a = 'z';
To check whether it is a number or not, use isNaN() method:
isNaN(a);
The following is an example that returns true i.e. not a number:
<!DOCTYPE html> <html> <body> <script> var a = 'z'; document.write(isNaN(a)); </script> </body> </html>
The output:
true
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 0/0; document.write(isNaN(a)); </script> </body> </html>
The output generates True since 0/0 is not a legal number:
True
Let us see another example that is a number. Therefore, false is returned:
<!DOCTYPE html> <html> <body> <script> var a = 50; document.write(isNaN(a)); </script> </body> </html>
The output:
false
Advanced Encryption Standard (AES) encrypts the data in the application. To perform AES, the JavaScript library Forge is used.
An example for encryption can be string encrypted to store in the database.
Yes, we can preserve the readability of text using the fontSizeAdjust property. This sets the difference between lowercase and uppercase letters size.
Use the document.forms length property of forms to count the number of forms in a document. Here’s an example for the same:
<!DOCTYPE html> <html> <body> <form> Name: <input type="text" name="my_name" value="demo"> Password: <input type="password" name="pwd" value=""> <input type="submit" value="Submit"> </form> <script> var res = document.forms.length; document.write("<br>Count of forms = "+res); </script> </body> </html>
The output displays the count:
To interact with the browser, the Browser Object Model has some properties and methods. Some examples include, the height and width of the window/ screen.
Some of its methods include:
To find the coordinates of cursor in JavaScript, use event.screenX and event.screenY. In this example, we are display the cursor coordinates relative to the screen:
<!DOCTYPE html> <html> <head> <script> function display(event) { document.write("Coordinate : X = " + event.screenX + "<br>Coordinate : Y = " + event.screenY); } </script> </head> <body> <div onmousedown="display(event)">Display coordinates of cursor...</div> </body> </html>
The columnFill property is used in JavaScript to fill columns. It means you can divide your content in columns like 2 3, 4, columns on a web page. An example is shown below:
<!DOCTYPE html> <html> <body> <p>Create columns...</p> <button onclick="display()">Columns</button> <div id="demo"> Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! </div> <script> function display() { document.getElementById("demo").style.columnCount = "2"; document.getElementById("demo").style.columnFill = "balance"; } </script> </body> </html>
The above text is divided into two columns since we have set columnCount as 2:
To detect a mobile device, let’s say Android device, use the navigator.userAgent.match. Here, we have set it in a function:
Android: function() { return navigator.userAgent.match(/Android/i); },
For iOS:
iOS: function() { return navigator.userAgent.match(/iPhone|iPad/i); },
A staple in advanced JS interview questions with answers, be prepared to answer this using your hands-on experience. This is also one of the top interview questions to ask a JavaScript developer.
The pageBreakAfter property in JavaScript is used set the page-break behavior after an element. Let’s say you need to set if got footer:
function myfunc() { document.getElementById("idFooter").style.pageBreakAfter = "always"; }
The some() method checks if an array element satisfies a test. An example:
<!DOCTYPE html> <html> <body> <script> var val = [20, 28, 45]; function display(a) { return a > 21; } document.write("Are their values greater than 21 in the array = "+val.some(display)); </script> </body> </html>
The output is true i.e. we have tested the array element and checked a condition: elements greater than 21.
JavaScript array every method checks whether the array elements (all) passes the test. A condition is checked for the test. An example here checks for every elements in the array for a condition passed in the function:
<!DOCTYPE html> <html> <body> <script> var val = [128, 29, 28, 45]; function display(a) { return a > 21; } document.write("Are all the values greater than 21 in the array = "+val.every(display)); </script> </body> </html>
The output displays true since the condition is satisfied for all the elements of the array.
The onresize event is executed a JavaScript when the browser window is resized. An example here displays the same:
<!DOCTYPE html> <html> <head> <script> function display() { var a = "Window Width=" + window.outerWidth + ", Window Height=" + window.outerHeight; document.getElementById("myid").innerHTML = a; } </script> </head> <body onresize="display()"> <p>Resize browser window!</p> <p id="myid"> </p> </body> </html>
The above displays the following output when the window is resized:
Resize browser window! Window Width=1366, Window Height=728
The onabort event is executed when the loading of an image is aborted. Use it in an image tag like this:
<img src="demo_image.jpg" onabort="display()">
Here, you can display an alert when the loading of image aborts:
function abortFunc() { alert('Image isn’t loading!'); }
A staple in advanced JS interview questions with answers, be prepared to answer this one using your hands-on experience. This is also one of the top interview questions to ask a JavaScript developer.
You can fill static values in an array using the fill() method in JavaScript. An example is here:
<!DOCTYPE html> <html> <body> <script> var arr = ["abc", "def", "ghi", "jkl"]; document.write("Initial array = "+arr); document.write("<br>Updated array = "+arr.fill("pqr",1,2)); </script> </body> </html>
The output displays that the array is set with static value:
Initial array = abc,def,ghi,jkl Updated array = abc,pqr,ghi,jkl
Use the join() method to join the elements of an array into string with a separator. An example here:
<!DOCTYPE html> <html> <body> <script> var arr = ["abc", "def", "ghi", "jkl"]; document.write("Initial array = "+arr); document.write("<br>Updated array = "+arr.join(" demo ")); </script> </body> </html>
Above, we have joined the elements into a string with a separator.
The output is:
Initial array = abc,def,ghi,jkl Updated array = abc demo def demo ghi demo jkl
This, along with other JavaScript basic interview questions for freshers, is a regular feature in web developer interviews, be ready to tackle it with the approach mentioned below.
Logic errors occur when there is a mistake in the logic. This can lead your script to work inappropriately to give unexpected results.
The blur event triggers when object loses focus. An example here displays that we write a name in the textbox and then when the object loses focus, the text color is changed. This happens since the blur event triggers when the focus ends:
<!DOCTYPE html> <html> <body> <h2>Type your name</h2> <input type="text" onblur="display(this)"> <script> function display(z) { z.style.color = "green"; } </script> </body> </html>
In JavaScript, an onfocus event is triggered when element gets focus. An example here displays that a user types in the textbox and the onfocus event is triggered, allowing the color of the text to change to yellow:
<!DOCTYPE html> <html> <body> <h2>Type your name</h2> <input type="text" onfocus="display(this)"> <script> function display(z) { z.style.color = "yellow"; } </script> </body> </html
When a visitor leaves the web page, then the onpagehide event triggers. The visitor can move to another page or click a link after leaving the current web page. An example here displays an alert box when the user tries to leave the page. This happens since onpagehide event fires when the page is left:
<!DOCTYPE html> <html> <body onpagehide="display()"> <p>Close the page</p> <script> function display() { alert("It was nice having you here!"); } </script> </body> </html>
The oninput event occurs when a value is included in the input box. This is how we can set the oninput event:
<input type="text" id="display" oninput="display()">
Above, the function display() is called when a user begins adding value in the textbox: function display() { var a = document.getElementById("display").value; document.write("Typed: " + a); }
This, along with other JavaScript basic interview questions for freshers, is a regular feature in web developer interviews, be ready to tackle it with the approach mentioned below.
Let’s first understand what is an compiled language and interpreted language.
gcc hello.c -o hello
If no error it will generate an executable “hello” and we will run it by:
./hello
python hello.py
The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.
However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.
Let consider the below example. The compilation steps mainly looks at the var keyword. It is not bothered with what is assigned in these variables.
var a = 10; var b = 20; console.log(a+b)
When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.
For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it. Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”.
Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.
The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser.
The variables "let” and “const” were introduced recently in ES6(In 2015). There were some design mistakes made with “var” and these were rectified with “let” and “const”.
The problem is that “var” is function scoped and it causes a lot of problems.
Consider the below example where we are using “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.
for(var i=0; i<5; i++) { console.log(i); //Output- 0 1 2 3 4 } i = i + 2; console.log(i); //Output- 7
Since, “var” is function scope so we can put our “for” loop inside a function and then “i” won’t be accessible outside.
function incrementI() { for(var i=0; i<5; i++) { console.log(i); } } incrementI(); //Output- 0 1 2 3 4
i = i + 2; console.log(i);
//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:9:1 */
Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.
The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.
for(let i=0; i<5; i++) { console.log(i); //Output- 0 1 2 3 4 } i = i + 2; console.log(i);
//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:6:1 */
We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like integers and strings.
const c = 12; c = 14; console.log('c is ', c);
/*
Exception: TypeError: invalid assignment to const `c'
@Scratchpad/6:2:1
*/
But can add or update values for non-primitive like arrays and objects.
const arr = [1, 2, 3]; arr.push(4); console.log('arr is ', arr); // [ 1, 2, 3, 4 ] const obj = { name: 'Robin', skill: 'JS' }; obj.skill = 'React'; obj.profession = 'Developer'; console.log('obj is ', obj); // { name: "Robin", skill: "React", profession: "Developer" }
This is one of the most frequently asked JavaScript interview questions for freshers in recent times.
JavaScript has both strict and type-converting equality comparison. For strict comparison we use === and for type-converting comparison we use == . Let’s look at each of it in details :
Strict Comparison(===)
For strict comparison the items been compared must be the same type.
console.log("Coder" === "Coder"); //true console.log("Coder" === "coder"); //false
console.log(23 === 23); //true console.log(NaN === NaN); //false console.log(0 === -0); //true
console.log(true === true); //true console.log(false === false); //true
var obj = {}; var newObj = obj; console.log(newObj === obj); //true
console.log(null === undefined); //false console.log(null == undefined); //true
Type-converting comparison
The == does a type conversion before comparing, if both items are of different types.
As you can see in the below example. String 1 is equal to numeric 1, when using ==. It is because the type of String 1 is converted to Number before comparison.
It is the similar case with “1 == true”. The 1 is converted into Boolean, which is true before comparison.
Same expressions are not true while using ===, as we know it doesn’t do any type conversion.
console.log('1' == 1); //true console.log(1 == true); //true console.log(1 === true); //false console.log('1' === 1); //false
Both null and undefined represents empty values. Let’s understand them first and then we will see what is the difference.
undefined
To understand “undefined” we have to understand what is declaration and definition of variables. When we declare a variable as in below diagram by “var value”, the compiler makes space for a variable “value”. The definition means that we assign a value to the variable and it’s allocated in that space. You can also do these two together by
var value = 42;
So, every language have a way of handling the value of a variable between function declaration and definition.
In JavaScript that is handled by type “undefined”. The type undefined is a primitive type which have only one value possible i.e. undefined.
null
It is also similar to “undefined” and is a primitive type. It also have only one possible value i.e. null. It is also used to represent empty values, but is generally assigned by the users.
var a; console.log(a); //undefined a = null; console.log(a); //null
Function declaration is like most other traditional languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we pass function as arguments to other function or return an function.
function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); } console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //Function expression
One of the key difference is that, we can call a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top.
console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //ReferenceError function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); }
/*
Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization
@Scratchpad/7:2:1
*/
But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.
This is one of the most frequently asked JavaScript interview questions for freshers in recent times. Be careful with the expression this one.
Closures are one of the most complex topic in JavaScript, but they are everywhere in JavaScript.
Closures are basically, the inner function having access to the variables in the outer function scope, even after the outer function has returned. To use a closure, simply define a function inside another function and expose it. To expose a function, return it.
Consider the below code. The variable b have an scope in outer function i.e. from line 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.
So, how does the innerFn() access the value of b. This is where the JS feature of Closures comes into play.
When the “var inner” is created at line 6, the JS engine not only stores the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.
Now it doesn’t matter where you call inner, whether in this file or some third party file. It will always remember the value of a and b, as if a snapshot is been taken.
var a = 10; function outer() { var b = 20; var inner = function() { console.log(a); console.log(b); }; return inner; } var innerFn = outer(); innerFn();
Output
//10 //20
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one. Here is how to answer this -
JavaScript “this” keyword simply means that whatever scope you are inside, it belongs to that. Now the scope can be a function or and Object. Although, there are some exception to this rule. We can have “this” in various context. Let’s go through them.
“this” in simple function
In a normal JS function like below, the “this” refers to global window object.
function foo() { console.log(this); console.log(this === window); } foo();
Running the above code will give.
There is a special case with strict mode.
In strict mode “this” to be undefined , as global object refers to undefined instead of window object.
function foo() { 'use strict'; console.log(this); console.log(this === window); } foo();
“this” in an object property
In an object which have a property as a function, the value of “this” is the Object itself.
var obj = {}; obj.foo = function() { console.log("Inside obj foo"); console.log(this); } obj.foo();
this is Object itself
“this” with constructor function
When a function is called with “new” keyword, it is known as constructor function. And the value of “this” refers to the newly created instance.
function Person(fn, ln) { this.first_name = fn; this.last_name = ln; this.displayName = function() { console.log(`Name: ${this.first_name} ${this.last_name}`); console.log(this); } } let person = new Person("Tim", "Horton"); person.displayName(); let person2 = new Person("Mary", " Poppins"); person2.displayName();
The newly created instance is nothing but an object, because everything in JS is an object.
One The for..in loop is mainly used to iterate over properties of an Objects.
In JavaScript Arrays are also Objects and each characters in an string have an index. So, we can use them also to iterate over Arrays and Strings also.
//Object example
const obj = { 'frontend developer': 'Thomas', 'designer': 'Mary', 'backend developer': 'Harry', 'engineering manager': 'Vikas' } for(const key in obj) { console.log(`${key}: ${obj[key]}`) }
//Array example
const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager']; for(const index in array){ console.log(array[index]); }
//String example
const string = 'frontend developer'; for(const index in string){ console.log(string[index]); }
The for..of loop was introduced in ES6 and is used to iterate over Objects that have [Symbol.iterator] property. This includes array, strings, Map, Set and NodeList. They cannot be used to iterate over Objects are not iterable.
If we check the __proto__ of an array, we can find the [Symbol.iterator] property.
But it is not the case with Objects as it is not iterable.
Some use of for..of loop are below:
//Array example
const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];
for(const item of array){ console.log(item); }
//String example
const string = 'developer'; for(const char of string){ console.log(char); }
//Map example
const map = new Map(); const emp1 = {name: 'Vikas', Degree: 'MS'}; const emp2 = {name: 'Thomas', Degree: 'MBA'}; map.set(emp1, 'frontend developer'); map.set(emp2, 'engineering manager'); for(const [key, item] of map) { console.log(key, '-', item); }
Hosting means we can use a variable even before declaring it. When the compiler runs(details in Question 1) and finds all the var declaration, it move them to the top of the file.
Let’s consider this below example. Here we are assigning values to on name , age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throws a runtime error. It is because it doesn’t matter where the variables are declared. They are always hoisted to the top by when the compiler makes the first pass.
name = "Thomas"; age = 45; profession = "Engineering Manager"; console.log(`${name} aged ${age} is ${profession}`); //Thomas aged 45 is Engineering Manager var name; var age; var profession;
This is also true for function declaration, as the compiler also treats function declaration as variable declaration as in JS all function declaration are object declaration. But same is not true for function expression and it will give reference error.
console.log(funcDeclaration()); //Function declaration console.log(funcExpression()); //ReferenceError function funcDeclaration() { console.log('Function declaration'); } let funcExpression = function() { console.log('Function expression'); } /*
Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization
@Scratchpad/7:2:1
*/
But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.
The output right now will be as below, as the method chaining is not understood by the compiler.
/* Exception: TypeError: A.x(...) is undefined @Scratchpad/1:14:1 */
We can get the desired output by “return this” in each function.
Now “this” is the object “A”. So, A.x() will result in console logging ‘x’ followed by returning the object “A” to y().
After that the function A.y() will print ‘y’ followed by returning the object “A” to z().
Finally, ‘z’ is printed on console.
var A = { x: function() { console.log('x'); return this; }, y: function() { console.log('y'); return this; }, z: function() { console.log('z'); return this; } } A.x().y().z(); //Output x y z
The sort() method is used to sort the elements of an array. But the output of the above is not what expected out of sort() function. The output will be [ 1, 15, 2, 30, 4, 45, 7 ] and it is far from desired.
This is because the default sort is according to tring Unicode points. The fix to it is by adding an anonymous function and tell to sort according to ascending or descending order.
Ascending order is as below:
const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> a-b)); //[ 1, 2, 4, 7, 15, 30, 45 ]
Descending order is as below:
const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> b-a)); //[ 45, 30, 15, 7, 4, 2, 1 ]
The most obvious answer to think is the value of “i” will be 0. So, let’s put i = 0 and see what happens.
let i = 0; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives NaN
Everything is ok, but the last one produce NaN(Not a Number) because “0 divide by 0 will produce infinity”
So, we need a number which is like zero but gives 1 if we divide it by itself. Fortunately there is such a number in JavaScript. The number is the minimum value that is allowed in JavaScript and is represented by Number.MIN_VALUE
let i = Number.MIN_VALUE; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives 1
Now, what is this MIN_VALUE and why it produces the above correct desired result. If we console log it we can see it’s a very small number 5e-324.
console.log(Number.MIN_VALUE); //5e-324
Now, this number in most cases behaves like a zero(0). Like when we multiply it by itself(i * i), add it to 1(i + 1) or substract it from 1(i -1).
But when we divide this small number by itself it produces 1.
When an event happens on an element, it first runs on which it was clicked, then on its parent, then all the way up on other ancestors. It is the default behaviour of the browser.
Event capturing is the opposite of bubbling and it means when you click on parent element, it goes till the child.
We will first see Event Bubbling. The HTML contains an parent element containing a child element called Child1. When we click on the “Child1” button, first the console log of child is displayed and then the parent is displayed.
We will now see Event Capturing. The HTML contains an parent element containing a child element called Child1. When we click on the button, first the console log of parent is displayed and then the child is displayed. Notice that in addEventListener we have to pass a value of true.
IIFE means Immediately Invoked Function Expression. Let’s first see a normal way to create function in JavaScript, also known as function as “Function declaration”. This is most similar, to the syntax of declaring functions in most other traditional languages like C++ and Java.
Consider the below example which have a simple function to add two numbers. Notice that these function definitions always start with the function keyword. You can’t omit it as it’s invalid syntax.
In JavaScript functions are first class citizens. So, there is another way to declare them. It is known as “Function Expression”. We will refactor the above addNumbers() code. Here we are treating as if addNumbers is a variable declaration. But then assigning an anonymous function to it.
IIFE(Immediately Invoked Function Expression) is nothing but a function expression, but it is defined and invoked at the same time. Here we had got rid of the addNumbers name itself and calling it also at the same time. Notice, that we are passing 2,3 immediately after the anonymous function is declared.
As JavaScript for most part is function scoped, so IIFEs are great way to create private variables.
Promises in JavaScript are like promises in real life. You promise to do something, and then it is done or not done. A promise may be in one of 3 possible states: resolve, rejected, or pending.
They are mainly used to do asynchronous task like calling a REST api and getting the result back. So, these network calls takes time. When the network call is been made, the promise is in Pending state. Once the network call is successful the promise returns a resolve and if it fails it returns resolve.The resolve is captured by the then() callback function and reject captured by catch() callback function.
Consider the below example. Here inside promiseCleanRoom we generate a random number between 0 and 1. If the number is greater the 0.5, we send a resolve or else we send a reject.
Depending on the case either .then is executed or .catch is executed.
Below is the resolve case
Expect to come across this, one of the top JavaScript interview questions for experienced professionals in web development, in your next interviews.
A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is executed inside the that Function.
Callback function are used everywhere in JavaScript. In JavaScript, functions are first-class citizens. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”.
Let’s look at the example below. Here we call function mainFunc with function “x” as argument and then from inside mainFunc, calling it after some console log.
When we use anonymous function inside our function call for callback like in the below code.
The in-built for Each, map, reduce, filter uses callback functions internally. Check the below example and here we are passing a function, just like above calc code.
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result.
Now, in recursive function there are two parts. One is termination condition and other is the recursion itself. The termination condition is very important or else the recursion never stops and goes into infinite loop.
Let consider the below simple example to add numbers from the current passed number backwards till 1. Say we pass 3, then 3+2+1 = 6. In the below example If(n≤0) is the termination condition and return n + add(n-1); is the recursion.
The recursion works as shown in the diagram below.
It works like loop, so the first call will go to recursion part and give “3 + add(2)”.
Now the add(2) will be called and will be expended into “2 + add(1)”.
After that add(1) will be called and expanded into “1 + add(0)”.
Finally the add(0) will trigger the termination condition If(n≤0) and produce 0.
After this everything will be added 3 + 2 + 1 + 0 to give 6.
A Higher Order Function is a function that takes one or more function as argument. We use them at many places in JavaScript, and are also called callback functions.
Consider, the below JS code which uses filter to filter-out Adult people. Here, we have a callback function isAdult which is called on every item.
These callbacks are usually defined inline as anonymous function. So, the refactored code is below.
We can further refactor it using arrow functions as below.
So, the array methods of map(), filter(), reduce(), forEach() are all Higher Order Functions.
Beside this eventListener like below are also Higher Order Function, as they use a callback function.
Template Strings are also known as Template Literals. They are the new way to write Strings in JavaScript and been introduced in ES6. We can now write Stings using back-ticks(``), which have a special way to interpolate variables.
They are very useful in Expression interpolation and Multi-line strings. Although they don’t add any new feature to JavaScript, but they are a better visual way to write strings.
Expression interpolation
The old JavaScript way is quite cumbersome and we have to use many + operators to concatenate Strings, whereas with back-ticks we interpolate variable name using ${}.
Multi-line strings
The old way to have multiline strings is to have a newline(\n) inserted after where we want the next line.
Template strings provides a new way. You just go to the next line and the text will be displayed in next line.
Default parameters are the parameters, which are used if we don’t pass the value to that argument in a function while calling it.
Earlier to ES6, it was a bit difficult to handle a situation like this. In the below example if user didn’t supplied a value to argument , we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”.
So, now we can handle all three situation successfully like when we pass no arguments, or pass only value of ‘a’ or pass only value of ‘b’.
The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.
Spread operators(…) were introduced in JavaScript in ES6 version. Just like plus(+) and minus(-) are operators, spread(…) is also an operator in JavaScript. Basically Spread operator spreads on demand.
When you pass arguments to a function using Spread operators they are called Rest parameters.
Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function the arr gets converted into and array. This functionality is quite similar to arguments object.
Now see the restFunc, here we are using rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into array.
The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects.
Consider that we want to copy an array to other array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x.
In the first solution, we use the new JavaScript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”.
But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array.
Another use it that if we pass an array to build in functions, which expects normal arguments. Consider the below examples.
We can also use Spread operator in Objects. So, by it we can do both clone and merge as shown in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys.
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. You can also handle nested structure by using nested destructuring syntax.
Object Destructuring
Consider the old way to assign variable to Object properties without destructuring.
Now we will refactor the above using “Object Destructuring”. Basically, you use an object literal on the left-hand-side of an assignment expression for object destructuring.
Nested Object Destructuring
If there is nested object as in below case, we can destructure it by adding it’s value to another object syntax
Array Destructuring
Let’s first see how to do it without destructuring. Here we use the index to assign the variables.
Array destructuring is similar to object destructuring, but here instead of keys you assign any variable.
Skipping Items
It is possible to skip items in array destructuring by omitting items with comma(,).
A must-know for anyone looking for top JavaScript coding interview questions. This is one of the frequently asked JavaScript questions today.
ES6 introduced the keyword class in JavaScript. But class in JavaScript is still different than those used in Object Oriented Programming languages like C++ and Java. The ES6 classes are nothing but synthetic sugar for constructor function and internally behaves exactly the same.
Consider the below example of Constructor function. Here we have a constructor function named “Mammal”. It have two properties of legs and name. It also have a function called walk(), which uses the legs and name property. We are creating an instance called person, which then is calling the walk function.
The same can be written with ES6 classes with constructor, but it is exactly the same.
Async await help in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.
Async await are basically promises under the hood. But they have made the code for promises very easier to implement. If promises had simplified the code for callbacks, then async await have simplified the code for promises.
Let’s first check a nested promise example. Here we have three functions which return promises- cleanRoom, removeGarbage and winPizza. Now, when the cleanRoom function is run and resolve is returned from the promise, then the immediate .then block will be run . In the .then we are returning the next removeGarbage and in its .then we are returning the winPizza. We are passing the message from one function to other, so it will be appended.
We will refactored the code with async await. Here, instead of three functions we have one function cleaningTheRoom, which have a keyword “async” infront of it. It means that the function will have await statement(s). In the “await” we can have the value returned by a Promise stored in a variable. This type of code is much more cleaner then promise.
The Promise.all method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
Let’s refactor the async await code from previous question to use Promise.all. Notice, that we are also using array destructuring at line 6, to receive all the values returned by the promise.
We should use Promise.all in only cases like above, where the result of one Promise is not dependent on other promise.
In Promises we handle any error or reject in the .catch block. Let’s look at the below example, where we are sending reject() from cleanroom(). So, now the error will be caught by the .catch block and then we are displaying the same in console log.
Now, when we refactor the above code using async-await, we don’t have any .catch block. So, we take help from the good old try…catch block available in JavaScript.
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
Constructor functions are the equivalent of classes of traditional programming languages like C++ and Java. Sometimes people will refer to them as reference types, classes, data types, or simply constructors.
If you aren’t familiar with classes, they are a construct that allows you to specify some properties and behaviours (functions), and multiple objects can be created with those properties and behaviours.
A common analogy you’ll often hear is, a class is an architecture’s map and an object is a house created using it. Multiple houses can be created from a single map, as multiple objects can be created from a class.
Let’s start with creating a simple function using object to create employee objects.
Now consider the line var newObj = {} and return newObj. They will be same in every function which we create. So, JavaScript gives us a special type of function known as Constructor function to create them.
We will refactor the above to use Constructor function. Look at the below code.
We are adding the keyword new to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name this.
Note, that we don’t need to put those two line in our code and automatically put by JavaScript engine.
We can also add methods to a Constructor function and then it can be called with any object created with new keyword.
Let us first consider the below code for normal Constructor function. Here we can directly access the variable “name” by person.name.
Now, this might be not desirable at many places and in Traditional languages like C++ and Java, this is solved by the having “private” variables in class and then having “Getters” and “Setters” to access them.
Now, we implement the same in JavaScript using Closures. We have two closure functions setName and getName which are basically “setters” and “getters”. Now, the variable _name is private and cannot be accessed outside the function by person._name and we can access it only by person.getName()
In JavaScript everything is an Object. So whenever we create an function, there is a one object which is created for that function. But actually there is another object which is created which is known as the Prototype object.
Now to access the Prototype object we have a reference on the function object also known as prototype. Notice the small “p”.
When we create an instance of the function with the new keyword interesting things happens. It create something known as __proto__. This is created by the JavaScript engine for every function call using the new keyword.
Now, let’s look how to create an function using prototype and the benefit of it. The below code have two function haveFun and drinkBreak. The function haveFun is an normal function inside the Constructor function. The function drinkBreak is created outside and added to the Prototype Object using it’s reference prototype.
Both the function seems to be doing the same thing, then what’s the benefit.
The benefit of declaring function using prototype is that it’s created once in the Prototype object. So, now whenever we create a new instance of the Constructor function the function is not created again. As in the below screenshot, you can see that emp1 and emp2 both have name and haveFun. But the drinkBreak is inside the __proto__, which is a reference to Prototype object.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
Let us now see why JavaScript is needed:
You can validate input before sending it to the server. This leads to faster loading on the server.
Executing JavaScript code is not a tedious task. Add your code in an HTML document. When user requests this HTML page with JavaScript in it, the script is sent to the web browser.
JavaScript can load content into the document whenever you need it. And while doing that, you don’t need to reload the complete page.
Use JavaScript to show and hide information on click. Move DOM elements around the page based on some pattern using JavaScript.
With JavaScript, you can also animate text.
You can develop games as well if you have advanced knowledge of JavaScript and its practical implementation.
JavaScript validates form data on the client's computer. And this task is accomplished before sending the data to the server.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
Java is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform independent object-oriented language.
The following is the difference between Java and JavaScript:
Basis | Java | JavaScript |
---|---|---|
Definition | Java is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform independent object-oriented language. | JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997. |
OOP | Java is an OOP programming language | JavaScript is an OOP scripting language. |
Running on Browser | Java creates applications that run in a virtual machine or browser | JavaScript code is run on a browser only. |
Compiled vs. Interpreted | Java Program is compiled. | JavaScript scripts are Interpreted. |
Type Checking | Java has static type checking. The type of a variable is checked at compile-time. | JavaScript has dynamic typing. The type safety is verified at runtime. |
Type of Variable | The type of variable should be specified. | It is not required to specify the type of variable. |
JavaScript is a lightweight and interpreted scripted/ programming language introduced in by Brendan Eic. It has a lot of advantages like validation, animation, interactions, etc. However, like any other programming language, it has some limitations too like you cannot write files on server, browser compatibility issues, etc.
Let us see the limitations of JavaScript one by one:
Writing files on server
JavaScript cannot directly write files on server. However, they can do this using server-side script.
Disable JavaScript
Due to security reasons, every web browser provides an option to disable JavaScript.
The screenshot displays how to enable or disable JavaScript:
It cannot be used for Networking applications.
Applications may behave differently in different web browsers. To support all modern browsers, you need to write cross browser codes.
Since the code executes on client’s computer, the chances are high for vulnerability and can be exploited for malicious purposes
JavaScript cannot access databases. You need AJAX and a server-side script for this.
Note: New developments in JavaScript introduced accessing client-side databases.
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The === is a comparison operator in JavaScript. It checks for the value as well type.
Same value and type
Let us see an example wherein we have assigned a numeric value to variable “val1” and checked it with a numeric value for equality (type and value):
<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val1 = 20; document.getElementById("test").innerHTML = (val1 === 20); </script> </body> </html>
The output displays that the variable has the same value and type. Therefore, true is returned as output:
Same Value and Different Type
Let us see an example wherein we have assigned a numeric value to variable “val2” and checked it with a value of another type for equality (type and value):
<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val2 = 5; document.getElementById("test").innerHTML = (val2 === "5"); </script> </body> </html>
The output displays that the variable has same value but different type. Therefore, false is returned as output:
Yes, JavaScript is case-sensitive. Therefore, the following identifiers are different:
Knowledge KNOWLEDGE
The case-sensitivity feature remains the same for variables, function names, and any other identifiers. The consistent capitalization of letters should be considered. For example, “for loop” should be written as “for”, not “FOR” or “For”.
Let us see an example wherein we have three variables with different case. All of these 3 variables are considered different:
<!DOCTYPE html> <html> <body> <h3>Popular Programming Languages</h3> <p id="test"></p> <script> var language, LANGUAGE, Language; language = "C#"; LANGUAGE = "Java"; Language = "Python"; document.getElementById("test").innerHTML = LANGUAGE; </script> </body> </html>
The output:
Let’s see the following two ways with which you can create an object in JavaScript:
Let us understand them one by one:
To create an object in JavaScript, use “new” as shown below. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create an object using Object() constructor:
<html> <head> <title>Objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance"; department.id = 005; department.location = "North";
Object creation with Object Literal
An object can also be created in JavaScript using object literal as shown below:
var department = { id: 11, name : "Finance", Location : "North" };
We can write it as:
var department = { id: 11, name : "Finance", Location : "North"};
Let us see another example:
<!DOCTYPE html> <html> <body> <h2>Department Details</h2> <p id="test"></p> <script> var department = { id: 11, name : "Finance", Location : "North"}; document.getElementById("test").innerHTML = department.name + " Department is in " + department.Location + " location."; </script> </body> </html>
The output:
The array variable is to be set empty if you want to empty an array.
Let’s say we have the following array:
var myArr = ["shirt", "trousers", "watch"];
To empty the above array, just set it to empty:
myArr = [];
Here we converting our array to empty array:
<html> <head> <title>Empty Array in JavaScript</title> <script> var myArr = ["shirt", "trousers", "watch"]; document.write("<br />Array: " + myArr ); // set array to empty myArr = []; document.write("<br />New array (Empty now): " + myArr ); </script> </head> <body> </body> </html>
The output:
Array: shirt,trousers,watch New array (Empty now):
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one. Here is how to answer this -
Using the <scrip>t tag you can store the JavaScript code in an external .js extension file. The tag with the “src” attribute allows you to include this js file in your HTML.
If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time.
Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The ”src” attribute is used to include the external JavaScript file in your HTML:
<script src="myfile.js" ></script>
Let’s say the following is the content of our external JS file “myfile.js”:
function show () { alert("Learning is fun!"); }
The following is our HTML file, wherein we will include the external file “myfile.js”:
<html> <body> <form> <input type="button" value="Click" onclick="show()"/> </form> <script src="show.js"> </script> </body> </html>
On running the above “myfile.js” file, the following is visible. Press the button “Click”:
On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function:
Events handle JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a window also comes under event.
The following are the events. A function in JavaScript gets executed against the event:
Events | Triggers |
---|---|
onblur | When the window loses focus |
onchange | When an element change. |
onclick | On a mouse click |
ondblclick | On a mouse double-click |
ondrag | When an element is dragged |
ondragen | At the end of a drag operation |
ondragenter | When an element has been dragged to a valid drop target |
ondragleave | When an element is being dragged over a valid drop target |
ondragover | At the start of a drag operation |
ondragstart | At the start of a drag operation |
ondrop | Dragged element is being dropped |
ondurationchange | When the length of the media is changed |
onerror | When an error occurs |
oninput | When an element gets user input |
oninvalid | When an element is invalid |
onkeydown | When a key is pressed |
onkeypress | When a key is pressed and released |
onkeyup | When a key is released |
onmousedown | Triggers when a mouse button is pressed |
onmousemove | Triggers when the mouse pointer moves |
onmouseout | Triggers when the mouse pointer moves out of an element |
onmouseover | Triggers when the mouse pointer moves over an element |
onmouseup | Triggers when a mouse button is released |
onmousewheel | Triggers when the mouse wheel is being rotated |
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output:
Event gets triggered when you click on the button “Display” to agenerate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
In JavaScript, you can use the same variable to hold different data types. This is why it is called that JavaScript has dynamic types.
It is not required to specify the type of variable in JavaScript. For example, the following is a variable, which is a number:
var val = 10;
Now, the same variable is a String:
var val = “Bingo”;
Now, you can also set it as a Number with decimal:
var val = 3.6;
Let us see them in an example to understand the dynamic types wherein we are showing the same variable can easily hold different types:
<!DOCTYPE html> <html> <body> <h2>Dynamic Types</h2> <p id="myid"></p> <script> var a; // a is undefined a = "Bingo"; // a is a String a = 10; // a is a Number a = 3.6; // a is a Number with Decimal document.getElementById("myid").innerHTML = a; </script> </body> </html>
The output:
In the above example, we have set different types for the same variable “a”:
var a; // a is undefined a = "Bingo"; // a is a String a = 10; // a is a Number a = 3.6; // a is a Number with Decimal
If you want to check the type of an object at runtime, then use the instanceof operator. The result is a boolean.
Check for Array
Let’s say we are checking if a variable is an array or not using instanceof operator. The syntax:
variable_name instanceof Array
The following is our example and we are checking whether array exists or not:
<html> <body> <script> var department = [ "Finance", "Operations", "Marketing", "HR" ]; if (department instanceof Array) { alert('This is an Array!'); } else { alert('This is not an array!'); } </script> </body> </html>
The output displays that array exists since the if condition is true:
Check for Object using instanceof
To check for an object, use the instanceof operator, the following is the example:
<html> <body> <script> var myObj = {}; if (myObj instanceof Object) { alert('This is an object!'); } else { alert('This is not an object!'); } </script> </body> </html>
The output displays ‘this is an object!’ in an alert box, since the if condition is true:
Remove a Single Element
To remove a single element from an array in JavaScript, the splice() method is used. With that you can also replace, and/or add elements in an array.
Let’s say we have the following array:
var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];
We are using the splice() method to remove a single element by setting the location from where it start, and the number of elements to be removed. Here, we have set 1, therefore only a single element will get removed:
myArr.splice(3, 1);
The following is an example:
<html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing an element = " + myArr ); rem = myArr.splice(3, 1); document.write("<br />Removed element = " + rem); document.write("<br />Array after removing an element = " + myArr ); </script> </body> </html>
The output:
Array before removing an element = Java,PHP,HTML,jQuery,Eclipse,NetBeans Removed element = jQuery Array after removing an element = Java,PHP,HTML,Eclipse,NetBeans
Remove more than one element
To remove more than one element and in a range, use the splice() method.
Let’s say we have the following array:
var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];
We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:
We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:
myArr.splice(2, 3);
In the following example, we are deleting 3 elements starting from the 3rd position:
<html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing 3 elements = " + myArr ); // removing multiple elements rem = myArr.splice(2, 3); document.write("<br />Array after removing 3 elements = " + myArr ); </script> </body> </html>
The output displays the array after removing 3 elements:
Array before removing 3 elements = Java,PHP,HTML,jQuery,Eclipse,NetBeans Array after removing 3 elements = Java,PHP,NetBeans
ECMAScript introduced to standardize JavaScript. The implementations of ECMAScript include JavaScript, ActionScript, JScript, etc. ECMAScript is a standard for these. It is a trademark scripting language specification.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript. Brendan Eich developed it and the language became an ECMA standard in 1997.
ECMAScript is a standard for JavaScript. The first edition of ECMAScript came in 1997. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard. The 8th edition of ECMAScript is ECMAScript 2017, introduced in June 2017. The full form of ECMA is European Computer Manufacturers Association
The current version is the 9th edition of ECMAScript, which came in the year 2018. The ECMA-262 Specification defined a standard version of the core JavaScript language.
Let’s say the following is our variable declaration of strings:
var val = "e\nx\na\nm\np\nl\ne";
To replace newlines, use the replace() method. The method replaces all occurrences of a character in the given string. The replace(char1, char2) has the following parameters:
Here the g flag on the regular expression to perform a global match. The 2nd parameter is a space (“ “), which we want in place of new line (\n):
val = val.replace(/\n/g, " ");
The following is an example that replace newline with spaces:
<!DOCTYPE html> <html> <body> <script> var val = "e\nx\na\nm\np\nl\ne"; val = val.replace(/\n/g, " "); document.write("After removing new line: "+val); </script> </body> </html>
The output:
After removing new line: e x a m p l e
Library in JavaScript has a function with a leading semicolon:
;(function ) { }
Let us see the different uses of including a leading semicolon:
The purpose to include semicolon is to safely concatenate several JS files into one.
A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.
The leading semicolon in immediately-invoked function expressions prevent errors when appending the file during concatenation. This concat is to a file containing an expression improperly concluded with a semicolon
Let’s see an example. Let’s say we are concatenating two files with self-invoking functions:
(function(){...ONE...})()
(function(){...TWO...})()
(function(){...ONE...})() (function(){...TWO...})()
!(function(){...TWO...})()
(function(){...ONE...})();(function(){...TWO...})()
This helps in preventing any kind of errors when appending the file during concatenation.
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The comma operator in JavaScript evaluates each of its operands. It returns the value of the last operand.
With the usage of comma operator, you can easily add multiple expressions. The syntax:
exp1, exp2, exp3, ……exp
Here, exp1, ex,2 exp3 are the expressions.
Add multiple parameters in a for loop using the comma operator:
for (var a = 0, b = 5; a <= 5; a++, b--)
Use the comma operator in a return statement. Process before returning using comma:
function show() { var x = 0; return (x += 1, x); }
With comma operator, you can declare multiple variables at once. Let’s say you have three variables. To declare and initialize them on new lines, you can declare them in a single line as shown below:
var a = 5, b = 10, c = 30;
You can also use the comma operators to call multiple arguments in a function call. Let’s say you have a function “calculate” and you need to find the multiplication of three numbers. For that, use the comma operators
calculate(33, 47, 79);
JavaScript used previously had the type attribute usage like this:
<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Demo!") //--> </script> </body> </html>
Above, you can see we have set the script language as “javascript” and the type as “text/javascript”.
The usage of type=”text/javascript” was necessary before the introduction of HTML5. But, when HTML5 came, JavaScript became its default language. Therefore, adding “text/javascript” is optional.
To validate decimal numbers in JavaScript, you can use regular expressions for matching with the match() method:
Let’s say we have the following decimal with string representation:
var val = "5.9";
The following regular expression you can use:
var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg );
For validation, we used the above regular expression and test it using the match() method. It gives us whether the given value is decimal or not:
<html> <body> <script> var val = "5.9"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output displays ‘decimal’ since the if statement is true:
Decimal!
Let us see another example with a different input i.e. a number:
<html> <body> <script> var val = "7"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output is ‘not a decimal!’, since the if statement is false:
Not a decimal!
Let us see another example and check for string:
<html> <body> <script> var val = "abc"; var reg = /^[-+]?[0-9]+\.[0-9]+$/; var res = val.match( reg ); if(res) document.write("Decimal!" ); else document.write("Not a decimal!" ); </script> </body> </html>
The output displays ‘not a decimal!’ since the if statement is false:
Not a decimal!
Arrays in JavaScript are used to store multiple values in a single variable. Let us see the two ways to create an array in JavaScript:
Using Array Literal
The easiest way to create an array in JavaScript is with array literal. Here, we have a variable and we are setting multiple values to it in an array:
var cars = ["Saab", "Volvo", "BMW"];
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = ["HR", "Finance", "Operations", "Marketing"]; document.getElementById("myid").innerHTML = department; </script> </body> </html>
The output:
HR,Finance,Operations,Marketing
Using keyword new
With JavaScript, you can also create an array using the new operator:
var department = new Array("HR", "Finance", "Operations", "Marketing");
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = new Array("HR", "Finance", "Operations", "Marketing"); document.getElementById("myid").innerHTML = department; </script> </body> </html>
The output:
HR,Finance,Operations,Marketing
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
Yes, constants do exist in JavaScript. The “const” keyword is used to create constant in JavaScript.
The const variables in JavaScript must be assigned a value when they are declared. Once declared, you cannot change and declare the value of constant again.
For example:
const val = 100;
Another example include:
const PI = 3.14159265359;
With const, you can declare local variables with block scope rather than function scope. Let’ say we have a constant variable “a”. After declaring a value like a constant variable, you can’t assign a new value to it.
Here’s an example wherein we are trying to reassign value to a const variable. As expected an error generates:
// declared a constant variable. const val= 150; // Error, since we try to assign a new value to the constant val = 0;
The following also gives an error since we are trying to change the primitive value:
const PI = 3.14159265359; PI = 3.14;
You cannot even reassign a constant array. Let us see an example for this:
<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> try { const department = ["Finance", "HR", "Marketing", "Operations"]; department = ["Operations", "IT", "Accounting", "Production"]; // error } catch (e) { document.getElementById("myid").innerHTML = e; } </script> </body> </html>
The output displays an error as shown below since we cannot assign to a constant variable:
TypeError: Assignment to constant variable.
To compare two dates in JavaScript, firstly add two date objects and set dates.
Here, our first date is the current date:
To compare two dates in JavaScript, firstly add two date objects and set dates.
Here, our first date is the current date:
var one, two; one = new Date(); two = new Date( "Mar 10, 2017 20:15:10" );
And the second date we have set as past date:
two = new Date( "Mar 10, 2017 20:15:10" );
Now, let us compare the above two dates using the below given code:
<!DOCTYPE html> <html> <body> <script> var one, two; one = new Date(); document.write(one); two = new Date( "Mar 10, 2017 20:15:10" ); document.write("<br>"+two); if (one > two) { document.write("<br>First date is the recent date."); } else { document.write("<br>Second date is the recent date."); } </script> </body> </html>
Let’s say the following is our string with numbers:
var strNum = "only123!";
To fetch the digits from the above string, the following RegExp is used:
/\d/g
Above we have set the g flag to perform global match.
The following is the code:
<html> <head> <title>Regular Expression in JavaScript</title> </head> <body> <script> var strNum = "only123!"; var regExp = /\d/g; document.write("String with numbers: "+strNum) var res = strNum.match(regExp); document.write("<br>Getting Digits = "+res); </script> </body> </html>
The output:
String with numbers: only123! Getting Digits = 1,2,3
The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can also be declared with var, but the usage of var are scoped to the function block level.
Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block.
Example of let
Let us see an example of let. The variable declared in the loop does not redeclare the variable outside the loop:
<!DOCTYPE html> <html> <body> <h3>JavaScript let</h3> <p id="myid"></p> <script> let i = 2; for (let i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays 2 as the variable i value:
Example of var
Let us see the same example using var this time instead let keyword:
<!DOCTYPE html> <html> <body> <h3>JavaScript var</h3> <p id="myid"></p> <script> var i = 2; for (var i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays 10 as the value of variable i:
To search for a string in a string, use the search() method. The method searches a string for a specified value. The returned value is the position of the match. However, -1 is returned if the match isn’t found.
Let’s say we have the following string:
var myStr = "Popular Programming Languages";
We want to search the below string from the above string:
Languages
For that, use the search() method:
var res = myStr.search("Languages");
Let us see the example wherein the string is successfully searched and the result (position) is displayed on button click:
<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "Popular Programming Languages" var res = myStr.search("Languages"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays the position:
Let us now see another example, wherein -1 is returned since the string to be found isn’t there:
<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "This is an example!" var res = myStr.search("demo"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output on button click displays -1:
In the unsigned right shift operator (>>>), the bits shifted on the left are always zero.
The zeros get filled in from the left with the operator. It shifts all bits in a 32-bit number to the right.
The following is an example:
<html> <body> <script> var val1 = -23; var val2 = 2; document.write("val1 >>> val2 = "); res = (val1 >>> val2); document.write(res); </script> </body> </html>
The output:
val1 >>> val2 = 1073741818
Let us see another example wherein we have a positive number. In this case the operator works the same as a signed right shift:
<html> <body> <script> var val1 = 7; var val2 = 2; document.write("val1 >>> val2 = "); res = (val1 >>> val2); document.write(res); </script> </body> </html>
The output:
val1 >>> val2 = 1
Cookies has a plain text record of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It stores information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.
Let us see how we can create a cookie in JavaScript:
The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.
Create a cookie:
document.cookie = "username=Knowledge Hut";
Add an expiry date to the cookie created above:
document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";
To read a cookie in JavaScript:
var a = document.cookie;
The above displays the cookies in name-value form i.e.:
cookie1=value; cookie2=value;
To delete a cookie, you need to just set the cookie to the past date (expire). The date is included using the expires parameter:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Let us see an example that creates a cookie:
<html> <head> <script> <!-- function displayCookie() { if( document.one.dept.value == "" ){ alert("Enter some value!"); return; } val = escape(document.one.dept.value) + ";"; document.cookie="name=" + val; document.write ("Setting Cookie <br> " + "name=" + val ); } //--> </script> </head> <body> <form name="one" action=""> Enter Department: <input type="text" name="dept"/> <input type="button" value="Input Cookie" onclick="displayCookie();"/> </form> </body> </html>
The output displays an input box, wherein we add a value to set as cookie:
On clicking “Input Cookie” above, you can see that we have set the cookie successfully:
The typeof operator is a unary operator in JavaScript. It is used to check the data type of its operand, like a variable is string, numeric, boolean, etc.
Let us see a simple example for number:
<html> <body> <script> var val = 10; document.write(typeof val); </script> </body> </html>
The output displays that it is a number:
Number
Let us now see another example for string:
<html> <body> <script> var val = "Sachin"; document.write(typeof val); </script> </body> </html>
The output displays that it is a string:
String
In the same way, we can check the type of a value entered, which is a boolean:
<html> <body> <script> var val = true; document.write(typeof val); </script> </body> </html>
The output display that the value entered is a boolean:
boolean
As we saw some examples above, here is the list of the values returned by the typeof operator:
Type | String Returned |
---|---|
Number type | Returns “number” |
String type | Returns “string” |
Object type | Returns “object” |
Boolean type | Returns “boolean” |
Null | Returns “null” |
The following are the different ways in which we can include JavaScript code in an HTML file. We can add JavaScript in the same file or an external file:
Java Script in the same file
Add the JavaScript code in the same HTML file using any of the following ways:
In head section
If you want the script to run on some event, then add the JavaScript code in the head section of the HTML file. Let us see an example:
<html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input type="button" onclick="show()" value="Click" /> </body> </html>
In body section
If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example:
<html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html>
JavaScript in an external file
Using the <script> tag you can store the JavaScript code in an external .js extension file. The tag with the “src” attribute allows you to include this js file in your HTML.
If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time.
Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the <script> tag. The src attribute is used to include the external JavaScript file in your HTML:
<script src="myfile.js" ></script>
Let’s say the following is the content of our external JS file “myfile.js”:
function show () { alert("Learning is fun!"); }
The following is our HTML file, wherein we will include the external file “myfile.js”:
<html> <body> <form> <input type="button" value="Click" onclick="show()"/> </form> <script src="show.js"> </script> </body> </html>
Press the button “Click”:
On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function:
The following are the types of pop-up boxes available in JavaScript:
Alert Box
The alert box is for an alert or message to the user. User needs to click “OK”. The alert() method is used to add a message in the alert:
Let us see an example:
<!DOCTYPE html> <html> <body> <h1>Alerts in JavaScript</h1> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output displays an alert on the click of a button:
On clicking the above button, the following alert generates:
Prompt Box
To input a value from the user and display it, use the prompt box. Users need to click “OK” to return the entered input, else click “Cancel” to return null.
Let us see an example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var res; var department = prompt("Enter your Department", "Operations"); if (department == null || department == "") { res = "Prompt cancelled!"; } else { res = "Department is " + department; } document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output first displays the button which you need to click:
On clicking the above button, a prompt box is visible wherein user input is requested:
On clicking “Ok”, the input is displayed on the web page:
Confirm Box
The confirm box is used in JavaScript to take user’s consent or accept something. User need to click “OK” to return true, else click “Cancel” to return false.
Let us see an example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var res; if (confirm("Press a button!")) { res = "OK is pressed!"; } else { res = "Cancel is pressed!"; } document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The following is the output. The button is visible. You need to click it:
On clicking the above button, a confirm box generates that wants users’ consent on clicking the button:
On pressing OK, the following is visible:
To handle exceptions in JavaScript, use the try, catch, throw and finally statements.
The try statement defines a block of code to be tested for errors, whereas the catch statement allows defining a block of code to be executed if an error occurs in the try.
The try block must be followed by either exactly one catch block or one finally block.
Let us see an example of try, catch and finally:
<html> <head> <script> <!-- function show() { var val = 5; try { alert("Value = " + val ); } catch ( e ) { alert("Error = " + e.description ); } finally { alert("Finally block executes!" ); } } //--> </script> </head> <body> <p>Click below:</p> <form> <input type="button" value="Display" onclick="show();" /> </form> </body> </html>
The output on running displays the following button:
On clicking the above button, an alert box is visible:
No error is there. On clicking “OK”, the “finally” statement executes. The alert box in the “finally” generates the following alert:
To return the division remainder, use the Modulus operator in JavaScript.
Let’s say the following are our two variables for which we want the modulus:
var val1 = 20; var val2 = 8;
Now, let us use the % operator to find the remainder:
var res = val1 % val2;
The example finds the division remainder using the Modulus operator:
<!DOCTYPE html> <html> <body> <h2>Remainder</h2> <p id="demo"></p> <script> var val1 = 20; var val2 = 8; var res = val1 % val2; document.getElementById("demo").innerHTML = res; </script> </body> </html>
The output displays the remainder:
The eval() function is used in JavaScript to evaluate or execute an argument. The method evaluates the expression, if the argument is an expression, else for arguments as statements, it executes the statements.
The parameter in the eval(string) function is a string, which can be an expression, variable, statement, or sequence of statements:
eval(string)
Note: Do not call eval() method to evaluate an arithmetic expression
Let’s say we have the following two variables:
var val1 = 20; var val2 = 7;
Now, with a new variable we will perform some calculations with the eval() method:
var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>";
The example demonstrates the role of eval() in JavaScript:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var val1 = 20; var val2 = 7; var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>"; var res = calc1 + calc2; document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays a button, which on pressing generates the following result:
140 119
Let us see another example:
<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() { var val1 = 15; var val2 = 10; var calc1 = eval("30 * 3") + "<br>"; var calc2 = eval("val1 + val2") + "<br>"; var calc3 = eval("5 * val1") + "<br>"; var calc4 = eval("10 + val2") + "<br>"; var res = calc1 + calc2 + calc3 + calc4; document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays a button, which on pressing generates the following result:
90 25 75 20
To increase the size of the text, you need to use the JavaScript big() method. Using it, you can easily display a string in a font size bigger than the normal font.
The following is an example to create a text with big font:
<html> <head> <title>JavaScript big()</title> </head> <body> <script> var myStr = "Demo Text"; document.write("Normal font: "+myStr) document.write("<br>Bigger font: "+myStr.big()); </script> </body> </html>
The output displays normal as well as bigger font using the <big> element:
Cookies has a plain text record of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It is store information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.
Let us see how we can create a cookie in JavaScript:
The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.
Create a cookie:
document.cookie = "username=Knowledge Hut";
Add an expiry date to the cookie create above:
document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";
To read a cookie in JavaScript:
var a = document.cookie;
The above displays the cookies in name-value form i.e.:
cookie1=value; cookie2=value;
To delete a cookie, you need to just set the cookie to the past date. The date is included using the expires parameter:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Let us see an example that creates and set a cookie:
<html> <head> <script> <!-- function displayCookie() { if( document.one.dept.value == "" ){ alert("Enter some value!"); return; } val = escape(document.one.dept.value) + ";"; document.cookie="name=" + val; document.write ("Setting Cookie <br> " + "name=" + val ); } //--> </script> </head> <body> <form name="one" action=""> Enter Department: <input type="text" name="dept"/> <input type="button" value="Input Cookie" onclick="displayCookie();"/> </form> </body> </html>
The output displays an input, wherein we add a value to set as cookie:
On clicking “Input Cookie” above, you can see that we have set the cookie successfully:
The onclick event gets triggered in JavaScript when a user clicks on any of the HTML element such as on click of a button.
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output displays a button:
Event gets triggered when you click on the button to generate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
To join two or more strings, use the JavaScript concat() method. A new string is returned with the joined strings.
The syntax:
string.concat(str1, str2, str3..., strn)
Here, str1, str2, and str3 are the strings you want to join.
Let’s say the following are our two strings to be joined:
var myStr1 = "One"; var myStr2 = "Time!";
Now, use the concat() method to join both the strings:
var res = myStr1.concat(myStr2);
The example demonstrates how to join two strings:
<!DOCTYPE html> <html> <body> <button onclick="show()">Joined Strings</button> <p id="myid"></p> <script> function show() {a var myStr1 = "One"; var myStr2 = "Time!"; var res = myStr1.concat(myStr2); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output:
Let us now see another example wherein we will join three strings. Now we have three strings:
var myStr1 = "Only"; var myStr2 = " One"; var myStr3 = " Time!";
Join three strings with the concat() method but with an extra parameter for the 3rd string:
myStr1.concat(myStr2, myStr3);
The example that joins three strings:
<!DOCTYPE html> <html> <body> <button onclick="show()">Joined Strings</button> <p id="myid"></p> <script> function show() { var myStr1 = "Only"; var myStr2 = " One"; var myStr3 = " Time!"; var res = myStr1.concat(myStr2, myStr3); document.getElementById("myid").innerHTML = res; } </script> </body> </html>
The output displays the result of three strings in a new string on the click of a button:
Let’s say the following is our string with numbers and special characters:
var strNum = "DEMO989#@#@";
The following RegExp is used to get a non-digits:
\D/g
Above we have set the g flag to perform global match.
The following is the code:
<html> <head> <title>Regular Expression in JavaScript</title> </head> <body> <script> var strNum = "DEMO989#@#@"; var regExp = /\D/g; document.write("String with numbers and characters = "+strNum) var res = strNum.match(regExp); document.write("<br>Getting Non-Digits = "+res); </script> </body> </html>
The output displays non-digits:
String with numbers and characters = DEMO989#@#@ Getting Non-Digits = D,E,M,O,#,@,#,@
The trim() method is used to remove whitespace from both sides of a string.
Let’s say we have the following string with leading and trailing whitespace:
var myStr = " Cup of tea! ";
To remove whitespaces, use the trim() method:
myStr.trim( )
The example demonstrates how to remove whitespaces from both the sides of a string in JavaScript:
<!DOCTYPE html> <html> <body> <script> var myStr = " Cup of tea! "; document.writeln("String (after removing leading and trailing whitespace): "+myStr.trim()); </script> </body> </html>
The output displays the same string after removing the leading and trailing whitespace:
String (after removing leading and trailing whitespace): Cup of tea!
Events handlers assist in JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a window also comes under event.
The following are the event handlers in JavaScript:
Event Handers | Triggers |
---|---|
onblur | When the window loses focus |
onchange | When an element change. |
onclick | On a mouse click |
ondblclick | On a mouse double-click |
ondrag | When an element is dragged |
ondragend | At the end of a drag operation |
ondragenter | When an element has been dragged to a valid drop target |
ondragleave | When an element is being dragged over a valid drop target |
ondragover | At the start of a drag operation |
ondragstart | At the start of a drag operation |
ondrop | Dragged element is being dropped |
ondurationchange | When the length of the media is changed |
onerror | When an error occur |
oninput | When an element gets user input |
oninvalid | When an element is invalid |
onkeydown | When a key is pressed |
onkeypress | When a key is pressed and released |
onkeyup | When a key is released |
onmousedown | Triggers when a mouse button is pressed |
onmousemove | Triggers when the mouse pointer moves |
onmouseout | Triggers when the mouse pointer moves out of an element |
onmouseover | Triggers when the mouse pointer moves over an element |
onmouseup | Triggers when a mouse button is released |
onmousewheel | Triggers when the mouse wheel is being rotated |
Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:
<html> <head> <script> <!-- function show() { alert("This is a message!") } //--> </script> </head> <body> <p>Click the below button:</p> <form> <input type="button" onclick="show()" value="Display" /> </form> </body> </html>
The output: Event gets triggered when you click on the button to generate the following alert:
Let us see another example wherein we are displaying the current date and time on click of a button:
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>
The following output generates on the click of a button that we created in the example above:
The “use strict” is a literal expression introduced in ECMAScript version 5. It indicates that the code should be executed in "strict mode", which in turn considered a good practice.
The key use of this mode is if you won’t declare a variable and use it, then an error would be visible. Let us see what we discussed using the following example:
<script> "use strict"; // a is not defined a = 10; </script>
Since, variable “a” is not defined above, the following error would be visible if you will Press F12 for debugging:
a is not defined
The following is not allowed in strict mode with “use strict”:
Case1: It is not allowed to delete a variable in strict mode
"use strict"; // error var a = 10; delete a;
Above generates the following error in strict mode, when you will enable debugging with F12 on web browser:
Error: Deletion of an unqualified identifier in strict mode
Case 2: Using Octal numeric literals are not allowed
<script> "use strict"; // error var a = 012; </script>
Above generates the following error in strict mode, when you will enable debugging with F12 on web browser:
Error: Octal literals are not allowed in strict mode
When data is sent to a web server, it has to be in the form of string. The JSON.stringify() method is used in JavaScript to convert an object to string.
Let’s say we have the following object in JavaScript:
var ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 };
Now use the JSON.stringify() method to convert the above object into string:
var res = JSON.stringify(ob);
Now, display it with innerHTML. Let us see the example:
<!DOCTYPE html> <html> <body> <h2>JSON String</h2> <p id="myid"></p> <script> var ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 }; var res = JSON.stringify(ob); document.getElementById("myid").innerHTML = res; </script> </body> </html>
The output generates the string:
The Math.abs() method is used in JavaScript to find the absolute value of a number.
The following is the parameter of abs(val) method:
The method returns:
Let us see an example to get the absolute value of a negative number:
var val = -9.50;
To get the absolute value:
Math.abs(val);
The entire example:
<!DOCTYPE html> <html> <body> <script> var val = -9.50; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output returns the negative value:
Number: -9.5 Absolute Value: 9.5
Let us see another example for “null” as input:
<!DOCTYPE html> <html> <body> <script> var val = null; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output:
Number: null Absolute Value: 0
Let us see another example to get the absolute value:
<!DOCTYPE html> <html> <body> <script> var val = 15+30+55; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>
The output:
Number: 100 Absolute Value: 100
The NEGATIVE_INFINITE property is a property of the Number Object in JavaScript, which is negative infinity.
The following is the syntax:
Number.NEGATIVE_INFINITY;
The return value is -Infinity. Let us now see an example:
<!DOCTYPE html> <html> <body> <script> var val = 5; document.write(val.NEGATIVE_INFINITY); </script> </body> </html>
The output:
Undefined
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
To display a blink text, use the blink () method in JavaScript. The string blinks using this method.
Note: The blank() method is not part of the standard now and the <blank> element is obsolete. Therefore, it may not work on modern web browsers.
Let us see an example:
<html> <body> <script> var myStr = "Learn!"; var res = myStr.blink(); document.write(res) </script> </body> </html>
The output displays the text and it may or may not blink, since the method is not part of the standard now:
Learn!
To reference an object's properties or methods, use the with keyword.
The syntax:
with (obj){ properties used without the object name and dot }
The “obj” becomes the default object for the duration of the block that follows. Now the object’s properties and methods can be used without even naming the object.
The example demonstrates the usage of with keyword:
<html> <head> <title>JavaScipt with keyword</title> <script> function stock(count){ with(this){ inventory = count; } } function product(pname, category, id){ this.pname = pname; this.category = category; this.id = id; this.inventory = 0; this.stock = stock; } </script> </head> <body> <script> var p = new product("Shirt", "Clothing", 17); p.stock(100); document.write("Product Name : " + p.pname + "<br>"); document.write("Product Category : " + p.category + "<br>"); document.write("Product ID : " + p.id + "<br>"); document.write("Product Inventory : " + p.inventory + "<br>"); </script> </body> </html>
The output:
Product Name : Shirt Product Category : Clothing Product ID : 17 Product Inventory : 100
It is said in JavaScript that almost everything is an object. JavaScript has many native or built-in objects.
Let us see some of them:
Example: Create an object
Let us now see how to create an object in JavaScript. To create an object in JavaScript, use “new” as shown below. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create an object using Object() constructor:
<html> <head> <title>Objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
The output:
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance"; department.id = 005; department.location = "North";
Example: Create a Boolean Object
The Boolean object represents two values, i.e. "true" or "false". Let us now see an example wherein we will create a Boolean object and return the value. We are using Boolean valueOf() method:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>
The output:
Value = true
Here is another example wherein we are returning the string representation of a Boolean value. We are creating a Boolean object first:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>
The output:
String = false
Example: Create a Number Object
The Number object represents numerical date, i.e. integers or floating-point numbers.
Let us now see how to create a Number object:
var val = new Number(25);
Let us now create an object with floating-point value:
var val = new Number(35.90)
An example here is to get the value of the specified Number object. We are creating a Number object:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(35.70); document.write("Value = " + val.valueOf()); </script> </body> </html>
The output:
Value = 35.7
Let us now create another Number object and represent it in String:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(90); document.write("String: " + val.toString()); </script> </body> </html>
The output:
String: 90
Yes, <noscript> element do exist in JavaScript. Use this element to set a message for users if the web browser they are using do not support JavaScript. This is also useful if the scripts have been disabled in the web browser.
The following is an example:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
The JavaScript engine adds a prototype property to the function when a function is created. This prototype property is an object. The objects inherit the properties and methods from their prototype.
Access the function’s prototype property using the following syntax:
functionName.prototype
Here’s an example: <!DOCTYPE html> <html> <body> <h2>Player</h2> <p id="details"></p> <script> function Team(rank, name) { this.rank = rank; this.name = name; } var res = new Team("3", "Jacob"); document.getElementById("details").innerHTML = "The name of the Player is " + res.name; </script> </body> </html>
The output:
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one.
JavaScript Closures
A closure is a function in JavaScript which have access to the parent scope, even after closing the parent function.
Let us see an example:
<!DOCTYPE html> <html> <body> <p>Increment by 5</p> <button type="button" onclick="show()">Count!</button> <p id="myid">0</p> <script> var sum = (function () { var count = 0; return function () {count += 5; return count;} })(); function show(){ document.getElementById("myid").innerHTML = sum(); } </script> </body> </html>
The output:
After clicking “Count” above, the value increments by 5:
In the above example, the following variable is assigned the return value of a function which is self-invoking:
var sum = (function () {
The self-invoking function sets the count to zero:
var count = 0; return function () {count += 5; return count;}
It returns a function expression as you can see above. This makes it a function and can access the count in the parent scope as well. This is what we can call closure in JavaScript.
Anonymous functions
Creating a function without a name is what we call Anonymous functions. Let us see an example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>
The output:
750
Above, we have function without a name:
var res = function (val1, val2, val3) {return val1 * val2 * val3};
To enable JavaScript in Windows, you need to work on “Internet Options” in Windows.
Here are the steps:
Go to “START” on Windows, type “Internet Options” and click on it:
On clicking, the following dialog box would be visible:
Go to “Security” tab now and click “Custom Level”. Now you will reach the “Security Settings” dialog box:
Now under “Active Scripting”, enable “JavaScript” as shown in the following screenshot:
Click “Ok”, then “Apply” one by one on both the dialog boxes to successfully enable JavaScript on Windows.
This is a common yet one of the most tricky JavaScript interview questions and answers for experienced professionals, don't miss this one.
The object properties are variables used internally in the object's methods. These variables can also be globally visible throughout the page. The properties are the values associated with a JavaScript object.
Let us see how to create and access object properties:
<!DOCTYPE html> <html> <body> <h2>Department</h2> <p id="myid"></p> <script> var department = { id: 5, name : "Finance", Location : "North" }; document.getElementById("myid").innerHTML = department.id + " is " + department.name + " department's id."; </script> </body> </html>
The following is the output:
Above we access the object properties as:
objectName.property
As shown above, we used to access object properties. Here, “Department” is our object whereas “name” is our property:
department.name
Global variables are widely used and do not create any security concern.
But Global variables should be avoided in JavaScript because these kinds of variables can be easily overwritten by others scripts. On adding a new variable with the same name can create errors if we are not cautious about its placement. To avoid such confusions, it is a good practice to avoid global variables.
Use closures and avoid the usage of global variables. The process is to work with local variables and wrap the code in closures as shown below:
<!DOCTYPE html> <html> <body> <h2>Department</h2> <p id="myid"></p> <script> var department = { id: 5, name : "Finance", Location : "North" }; document.getElementById("myid").innerHTML = department.id + " is " + department.name + " department's id."; </script> </body> </html>
To find whether the web browser supports JavaScript or not, you can test it on your local system.
Create an HTML file and use the <noscript> tag. Run the file in your browser and if it does not support JavaScript, then the message set under the <noscript> would be visible.
The <noscript> tag is used in JavaScript to allow adding an alternate message if JavaScript is disabled in the web browser. In this way a user can know whether the web browser has JavaScript or not. If it’s not there, then the message added using the <noscript> is visible.
The following is an example:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
Place the JavaScript anywhere within your web page, but it is recommended to include it within the <head> or <body> tag.
The following are the different ways in which we can include JavaScript code in an HTML
In head section
If you want the script to run on some event, then add the JavaScript code in the head section of the HTML file.
Let us see an example:
<html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input type="button" onclick="show()" value="Click" /> </body> </html>
In body section
If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example:
<html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html>
The best way to check if a variable exist in JavaScript is to verify it with null.
Let us see an example:
<html> <body> <script> var a = 4; if(a != null) { document.write("Variable do exist!"); } </script> </body> </html>
The output:
Variable do exist!
Above, we worked on the condition that a variable exist if it is not null. Therefore we checked the value if variable a like this:
if(a != null) { document.write("Variable do exist!"); }
Use CSS and jQuery to replace the default JavaScript alert pop up. Let us first see how to create an alert in JavaScript and how the default looks:
<!DOCTYPE html> <html> <body> <h1>Alerts in JavaScript</h1> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output displays a button, which is to be clicked to generate an alert:
On clicking the above button, the following alert generates:
Let us now see how we can create a fancy alert box using JavaScript library jQuery and CSS:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> function myAlertBox(msg, myYes) { var box = $("#test"); box.find(".msg").text(msg); box.find(".yes").unbind().click(function() { box.hide(); }); box.find(".yes").click(myYes); box.show(); } </script> <style> #test { display: none; background-color: blue; border: 2px solid #aaa; color: white; position: fixed; width: 250px; height: 80px; left: 50%; margin-left: -80px; margin-top: 50px; padding: 10px 10px 10px; box-sizing: border-box; text-align: center; } #test button { background-color: white; display: inline-block; border-radius: 5px; border: 1px solid #aaa; padding: 5px; text-align: center; width: 80px; cursor: pointer; } #confirm .msg { text-align: left; } </style> </head> <body> <div id = "test"> <div class = "message">Welcome to the website!</div> <button class ="yes">OK</button> </div> <h2>Fancy Alert Box</h2> <input type = "button" value = "Display" onclick = "myAlertBox();" /> </body> </html>
Under <style> above, we added the CSS code.
The output displays a button which is to be clicked to generate an alert:
On clicking the above “Display” button, the following alert is visible which we styled. The background color is not blue. The button color and style is also changed:
The <noscript> tag is used in JavaScript to allow adding an alternate message if you disable JavaScript in the web browser. In this way a user can know whether the web browser has JavaScript or not. If it’s not there, then the message added using the <noscript> is visible.
The following is an example that ells itself whether JavaScript is disabled in the web browser or not:
<!DOCTYPE html> <html> <head> <title>HTML noscript</title> </head> <body> <script> <!-- document.write("This is demo text!") --> </script> <noscript> Your browser does not support JavaScript! </noscript> </body> </html>
The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!".
An inline function is assigned to a variable created at runtime. It is assigned to a variable and can be easily reused.
The following code snippet display that inline functions are assigned:
var show = function() { alert ('This is inline!') };
Creating a function without any name is what we call Anonymous functions.
Let us see an example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>
The output:
750
The javascript:void(0) evaluates an expression even if its addition to a web page brings unwanted output.
Use the void(0) to get the undefined primitive value. Here, we are preventing the page from loading on clicking the hyperlink:
<html> <head> <script> <!-- //--> </script> </head> <body> <p>On clicking the below link, nothing will happen...</p> <a href="javascript:void(0)">Try to click me!</a> </body> </html>
The output is displayed below. Nothing happens when the link is clicked:
Get the pixels of the current document scrolled to from the upper left corner of the window, vertically using the pageYOffset property. An example displays the same and returns the pixels:
<!DOCTYPE html> <html> <head> <style> div { height: 1300px; width: 1300px; } </style> </head> <body> <script> function display() { window.scrollBy(200, 200); alert("pageYOffset pixels = " + window.pageYOffset); } </script> <button onclick="display()" style="position:fixed;">Display</button> <br><br><br> <div> </div> </body> </html>
Let’s say the following is your array:
var a = [99, 150, 299, 340, 390, 450, 590, 600];
Now, get the length of the array:
var len = a.length;
Loop until the length of the array is more than 0. Use Math.random() to randomize the elements. Decrement the value of len (length) after every iteration for each element:
while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; }
The following is an example that shuffles an array:
<html> <body> <script> function show(a) { var len = a.length; var t, index; while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; } return a; } var a = [99, 150, 299, 340, 390, 450, 590, 600]; document.write("Array = "+a); document.write("<br>Shuffling the array = "+show(a)); </script> </body> </html>
The output:
Array = 99,150,299,340,390,450,590,600 Shuffling the array = 390,340,150,590,99,450,299,600
JavaScript provides a join() method to join the elements of an array. While joining, you can set the separator as well:
array.join(separator)
Here, separator is the resultant array would be specified by this separator. Comma is the default separator.
The return value is the strings as array elements separated by the separator.
Let us see an example wherein we have the following array:
var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"];
The example to convert array into comma-separated list:
<!DOCTYPE html> <html> <body> <script> var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"]; document.write(products.join()); </script> </body> </html>
The following is the output:
Shoes,Cap,TShirt,Shirt,Trousers
The var and let are used to declare a variable in JavaScript. The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can also be declared with var, but the usage of var are scoped to the function block level.
Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block.
Example of let
Let us see an example of let. The variable declared in the loop does not redeclare the variable outside the loop:
<!DOCTYPE html> <html> <body> <h3>JavaScript let</h3> <p id="myid"></p> <script> let i = 2; for (let i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays the value if i variable as 2:
Example of var
Let us see the same example and place var in place of let to work with variables:
<!DOCTYPE html> <html> <body> <h3>JavaScript var</h3> <p id="myid"></p> <script> var i = 2; for (var i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>
The output displays the value of i variable as 10:
The Number object is for integers, floating-point numbers, etc. Let us now see how to create a Number object:
var val = new Number(10);
Let us now create an object with floating-point value:
var val = new Number(25.90);
An example here is to get the value of the specified Number object. We are creating a Number object:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(25.90); document.write("Value = " + val.valueOf()); </script> </body> </html>
The output:
Value = 25.9
Let us now create another Number object and represent it in String:
<html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(40); document.write("String: " + val.toString()); </script> </body> </html>
The output:
String: 40
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
The length property is used in JavaScript to get the length of a string:
The syntax:
string.length
Let’s say the following is our string:
var myStr = "This is an example!";
Now get the length of the string in a new variable:
var res = myStr.length;
The following is an example that displays the string length:
<html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = "This is an example!"; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>
The output:
Length = 19
Let us now see what we will get when we will try to find the length of an empty string:
<html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = ""; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>
The output displays 0 since it is an empty string:
Length = 0
The document.write() method writes JavaScript code to a document. It also writes HTML expressions.
The syntax:
document.write(expression1, expression2, expression3, ...)
Here, expression1, expression2, expression3 are the expressions to be written to the output stream.
Let us now see an example to write HTML elements with document.write():
<!DOCTYPE html> <html> <body> <script> document.write("<p>John Cena</p>"); </script> </body> </html>
The output:
John Cena
Let us see another example to write text to stream with document.write():
<!DOCTYPE html> <html> <body> <script> document.open(); document.write("<p>Travis Head</p>"); document.close(); </script> </body> </html>
The output:
Travis Head
To display an alert box in JavaScript, use the alert() method. The alert box would have an OK button.
The syntax:
alert(msg)
Here, msg is the text which is to be displayed in the alert box. Shown below under alert():
function show() { alert("This is an alert box!"); }
The following is an example:
<!DOCTYPE html> <html> <body> <p>Below button displays an alert...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>
The output:
On clicking the above button, the following alert generates and the message we added as parameter is visible:
You may be wondering how we can add a multi-line message in an alert box in JavaScript. For that, just use \n as shown below:
<!DOCTYPE html> <html> <body> <p>Below button displays an alert with multi-line content...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is first line!\nThis is next line!"); } </script> </body> </html>
The output:
On clicking the above button, the following alert generates and the multi-line message we added as parameter is visible:
Unfortunately, Boolean Typed array do not exist in JavaScript. The following typed arrays exist in JavaScript: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, etc.
Let us see an example of Int8Array typed array. The Int8Array typed array represents an array of twos-complement 8-bit signed integers.
The following is the syntax:
new Int8Array(); new Int8Array(length); new Int8Array(typedArray);
The following is an example:
<!DOCTYPE html> <html> <body> <script> var val = new Int8Array(5); val[3] = 9; // length of array document.write("Array Length = "+val.length); // displaying array elements document.write("<br>Array elements..."); document.write("<br>"+val[0]); document.write("<br>"+val[1]); document.write("<br>"+val[2]); document.write("<br>"+val[3]); </script> </body> </html>
The output:
Array Length = 5 Array elements... 0 0 0 9
“True” and “False” are the two values in a Boolean object. Let us now see how to create a Boolean object:
var val = new Boolean(false);
Let us now see an example wherein we will create a Boolean object and return the value. We are using Boolean valueOf() method:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>
The output:
Value = true
Here is another example wherein we are returning the string representation of a Boolean value:
<!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>
The output:
String = false
To display the unicode of the character at a specified index in a string with JavaScript, use the charCodeAt() method.
Let us now see the syntax:
string.charCodeAt(index)
Here, “index” is the index of the character we are willing to return.
The method returns the Unicode of the character. However, "NaN" is returned if no character is found at the index we added as the parameter.
The following is an example:
<!DOCTYPE html> <html> <body> <script> var myStr = "Chatting!"; var res = myStr.charCodeAt(0); document.write( "Unicode = " + res.toString() ); </script> </body> </html>
The output displays the returned Unicode of the 1st character, since we added parameter as 0:
Unicode = 67
The following is another example wherein we will find out the Unicode for character at index 2:
<!DOCTYPE html> <html> <body> <script> var myStr = "Hit Wicket!!"; var res = myStr.charCodeAt(2); document.write( "Unicode = " + res.toString() ); </script> </body> </html>
The output displays the returned Unicode of the 3rd character, since we added parameter index as 2:
Unicode = 116
Let us see a condition in which we are finding the character at a position where there is no character:
<!DOCTYPE html> <html> <body> <script> var myStr = "abc"; // 5th character does not exist var res = myStr.charCodeAt(5); // NaN is returned document.write( "Unicode = " + res.toString() ); </script> </body> </html>
Above, “NaN” is returned since there is no character at position 5th:
Unicode = NaN
The Date() method is to be used in JavaScript to get today’s date and time.
The following is the syntax:
Date()
Let us see the example to display the current date and time:
<!DOCTYPE html> <html> <body> <script> var date = Date(); document.write("Date and Time = " + date ); </script> </body> </html>
The output displays today’s date and time:
Date and Time = Fri Dec 14 2018 20:16:22 GMT+0530 (India Standard Time)
Let’s say you need to only fetch the time portion of the date. For that, use the toTimeString() method:
<!DOCTYPE html> <html> <body> <script> var date = new Date(2018, 12, 14, 10, 11, 30); document.write( date.toTimeString() ); </script> </body> </html>
The output displays only the current time:
10:11:30 GMT+0530 (India Standard Time)
The Date.parse() method is used in JavaScript to parse a string representation of date and time.
Let us first see the syntax:
Date.parse(str)
Here, str is the date string.
The method parses the date and returns the number of milliseconds since midnight of January 1, 1970.
Let us see an example now:
<!DOCTYPE html> <html> <body> <script> var res = Date.parse( "Dec 14, 2018 16:45:00" ); document.write( "Number of milliseconds between the date mentioned above and 1970 = " + res ); </script> </body> </html>
The output:
Number of milliseconds between the date mentioned above and 1970 = 1544786100000
To convert a date object to string in JavaScript, use the toLocaleString() method.
The following is the syntax:
Date.toLocaleString();
Create a Date object:
var date = new Date();
Now convert the above date object to string:
date.toLocaleString();
The example demonstrates how to convert Date object to string:
<!DOCTYPE html> <html> <body> <script> var date = new Date(); var res = date.toLocaleString(); document.write(res); </script> </body> </html>
The output:
12/14/2018, 8:25:52 PM
The Math.random() method displays a floating-point pseudo-random number between 0 and 1.
Note: The value is inclusive of 0 and exclusive of 1
The following is an example:
<!DOCTYPE html> <html> <body> <script> var num = Math.random( ); document.write("Random number = " + num ); </script> </body> </html>
The output displays any random number between 0 and 1:
Random number = 0.8085646074894297
When we will run the above program again, a new random value between 0 and 1 will get generated as shown below:
Random number = 0.1117848013962992
To remove the last element from an array in JavaScript, use the pop() method.
The following is the syntax:
array.pop()
Let’s say we have the following array:
var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];
To remove an element, use the pop() method:
var element = arr.pop();
Let us see an example wherein we are removing 5 elements:
The method returns the removed element from the array. In the below example, we have an array and we have removed the last element from the array. With that we have removed 4 more elements from the end one by one using the pop() method:
<!DOCTYPE html> <html> <body> <script> var arr = [20, 11, 44, 39, 88, 48, 89, 47 ]; document.write("Array = "+arr); document.write("<br><br>Removing 5 elements...<br>"); var element = arr.pop(); document.write("Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); var element = arr.pop(); document.write("<br />Popped Element = " + element ); </script> </body> </html>
The output:
Array = 20,11,44,39,88,48,89,47 Removing 5 elements... Popped Element = 47 Popped Element = 89 Popped Element = 48 Popped Element = 88 Popped Element = 39
Yes, we can add one or more element to the front of an array using the unshift() method.
Let us first see the syntax of the unshift() method to understand it further:
array.unshift( e1, e2, e3, ..., eN );
Here, e1, e2, e3, … , en are the elements to be added in the front of the array.
We added the following elements to the array:
var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];
Let’s say we need to add a new element in the front of the above array. For that set the element value as a parameter in the unshift method as shown below:
var len = arr.unshift("5");
The following is an example wherein we are adding an element in the beginning of an array:
<!DOCTYPE html> <html> <body> <script> var arr = [20, 11, 44, 39, 88, 48, 89, 47 ]; document.write("Array = "+arr); // adding element 5 in the front var len = arr.unshift("5"); // displaying the new array document.write("<br>New array = " + arr ); document.write("<br /> Length of the array = " + len ); </script> </body> </html>
The output:
Array = 20,11,44,39,88,48,89,47 New array = 5,20,11,44,39,88,48,89,47 Length of the array = 9
The !! operator is the not operator twice. It is useful in working through the truth value and returns a Boolean value.
Let us see an example:
<!DOCTYPE html> <html> <body> <script> var val1 = "This is an example"; var val2 = !!val1; document.write(val2); </script> </body> </html>
The output:
True
Let us see another example for integer and apply double not to it:
<!DOCTYPE html> <html> <body> <script> var val1 = 10; var val2 = !!val1; document.write(val2); </script> </body> </html>
The output:
True
NaN suggests that the entered value is not a legal number. It is a JavaScript property, which can also be considered as a "Not-a-Number" value.
To determine the entered value is a number or not, you can use the Number.isNaN() method. If the result is “True”, then it would that the given value is not a number, whereas “False” would mean the value is a legal Number.
Let us see an example:
<!DOCTYPE html> <html> <body> <script> var a = "Grill"; document.write(isNaN(a)); </script> </body> </html>
The output displays True since the above value is not a legal number:
True
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 10; document.write(isNaN(a)); </script> </body> </html>
The output since the above value is a legal number:
False
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 0/0; document.write(isNaN(a)); </script> </body> </html>
The output generates True since 0/0 is not a legal number:
True
The “undefined” is used to unset a variable in JavaScript.
Declare and initialize a variable:
]var a = 50;
Now reassign the variable with undefined since we wish to unset it:
a = undefined;
The following is an example:
<!DOCTYPE html> <html> <body> <script> var a = 50; a = undefined; document.write(a); </script> </body> </html>
The output displays undefined:
Undefined
If you are implicitly declaring the variable without var keyword, then use the delete to unset a variable:
<!DOCTYPE html> <html> <body> <script> a = 10; delete a; </script> </body> </html>
The double NOT Bitwise operator is a “double tilde” (~~) operator in JavaScript.
Let’s say we have the following variable:
var val1 = 3.7; var val2;
Now, use the double tilde operator and assign it to another variable:
val2 = ~~val1;
The example to work with double tilde operator:
<!DOCTYPE html> <html> <body> <script> var val1 = 3.7; var val2; val2 = ~~val1; document.write(val2); </script> </body> </html>
The output:
3
You can achieve the same result from Math.floor() in JavaScript, but double tilde is considered faster:
<!DOCTYPE html> <html> <body> <script> var val1 = 3.7; document.write(Math.floor(val1)); </script> </body> </html>
The same output is visible:
3
Generally, in JavaScript we create functions using the function keyword:
var points = [98, 45, 78, 65, 99]; var demo = points.map(function(val) { return val + val; })
Using the Fat arrow function reduces line of code and even avoids you to write the keyword “function” again and again.
The syntax of fat arrow function includes =>, wherein it shows fat arrow:
arg => exp
For multiple arguments:
(arg1 [, arg2]) => exp
Let’s see what you need to do with fat arrow function while implementing the code snippet we saw above:
var points = [98, 45, 78, 65, 99]; var demo = points.map((val) => val+val);
The substr() and substring() methods are simpler, yet they have some differences. The 2nd argument of the substring() method is the index to halt the search, whereas the 2nd parameter of substr() is the maximum length.
Note: We will be taking the same string and the same parameter value for both the functions to make it easier to understand
substr() method
The substr() method returns the characters in a string beginning at the specified location. It goes through the number of characters which is specified by the user.
The parameters of substr(start, len):
Let us see an example.
We have the following string:
var myStr = "Knowledge Hut!";
Now, we will use substr() as discusses above with the parameters to get 5 elements beginning from 3rd index:
myStr.substr(3,5)
The example:
<html> <head> <title>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substr(3,5)); </script> </body> </html>
The output from 3rd index.
5 is the length of elements after beginning with 3rd index:
(3,5): wledg
substring() method
The substring() method returns subset of a string.
The parameters of substring(i1, i2):
Let us see an example.
We have the following string:
var myStr = "Knowledge Hut!";
Now, we will use substring() as discussed above with the parameters to get substring from 3 to 5, since we set the parameter as 3 and 5:
myStr.substring(3,5)
The example:
<html> <head> <title>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substring(3,5)); </script> </body> </html>
The output from substring 3 to 5:
(3,5): wl
A staple in JavaScript technical interview questions and answers, be prepared to answer this using your hands-on experience.
Prototypal inheritance is to add new capabilities to a constructor function using Prototype.
Let’s first understand what are Constructor functions. They are basically JavaScript way to implement the concept of Classes.
Let’s consider the example below, where we have a “Car” constructor function. In it we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel().
let Car = function(model) { this.model = model; this.getModel = function() { return this.model; } } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan');
console.log(maryCar.getModel()); //nissan
Now, the problem is that every time we create a new instance we get a new copy of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing.
We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps.
In JavaScript as you know everything is an Object. Whenever a function is created there are two object one is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.
Every instance created from the function have access to the Prototype object. Now, let’s move our getModel() outside our Constructor function using prototype.
let Car = function(model) { this.model = model; } Car.prototype.getModel = function() { return this.model; } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan'); console.log(maryCar.getModel()); //nissan
We get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log.
JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
Many people think JavaScript is asynchronous because we can do async tasks like setTimeout, callbacks, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs.
The browser have a Call Stack, Browser API and Message Queue and the order of their processing is called event loop.
We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works.
function main() { console.log('A'); setTimeout(function(){ console.log('B'); },0); console.log('C'); } main();
//Output
//A //C //B
The output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution.
The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.
This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from.
Every function in JavaScript have call, apply and bind methods. These methods can be used to set the custom value of “this” to the execution context of the function.
call
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers.
Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; console.log(addNumbers.call(obj, 1, 4, 6)); //14
apply
It is totally similar to call, but the only difference is that we can pass array as the second argument. We will use the same code for apply also. But now we have an arr, to be passed as second argument.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; let arr = [7, 3, 8]; console.log(addNumbers.apply(obj, arr)); //21
bind
Bind works in a bit different way then call and apply. It works by returning a copy of the function. We will take the returned function in bindFunc and then execute it in the next line.
let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; let bindFunc = addNumbers.bind(obj); console.log(bindFunc(7, 3, 8)); //21
There are four solutions to access “this” inside the innerFunc().
Solution 1
Use a “that” variable in cleanRoom() for accessing “this” inside innerFunc(). Basically “that” is nothing but the outer “this”.
const cleanRoom = function(soap) { let that = this; const innerFunc = function(_soap) { console.log(`Cleaning ${that.room} with ${_soap}`) } innerFunc(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 2
Use call method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) { const innerFunc = function(_soap) { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc.call(this, soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 3
Use bind method to use the outer “this” inside the innerFunc().
const cleanRoom = function(soap) { const innerFunc = function(_soap) { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc.bind(this)(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
Solution 4
Use arrow function in the innerFunc(). Arrow functions have special meaning for “this” and it is that, it takes the value of “this” from the enclosing scope and is very useful in this case.
const cleanRoom = function(soap) { const innerFunc = (_soap)=> { console.log(`Cleaning ${this.room } with ${_soap}`) } innerFunc(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic
One of the main use of “call” is to change an array like object to array.
There is an array like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into array, because arrays have a lots of functionality.
Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities.
let sumNumbers = function() { console.log(arguments); } sumNumbers(1, 2, 3, 4);
Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is converted into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the sum of the number of arguments passed to it.
let sumNumbers = function() { const argsToArray = [].slice.call(arguments); console.log(argsToArray); return argsToArray.reduce((acc, curr) => acc + curr); } console.log(sumNumbers(1, 2, 3, 4)); //10 console.log(sumNumbers(1, 2, 3)); //6
The second application of call is in inheritance , using constructor functions.
Consider the below example. Here in the Cat function, we called its parent Mammal using call method with “this” of Cat.
let Mammal = function(legs) { this.legs = legs; } let Cat = function(legs, isDomesticated) { Mammal.call(this, legs); this.isDomesticated = isDomesticated; } let tiger = new Cat(4, false); let homeCat = new Cat(4, true); console.log(tiger); // { legs: 4, isDomesticated: false } console.log(homeCat); // { legs: 4, isDomesticated: true }
One of the practical use of apply is to pass an array to a function, which expects arguments only.
Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding.
let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29
One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor.
Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.
class Foo extends React.Component{ constructor( props ){ super( props ); this.state = { text: '' }
this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.setState({ text: event.target.value }) } render(){ return ( <input type="text" value={this.state.text} onChange={this.handleChange} /> ); } } ReactDOM.render( <Foo />, document.getElementById("app") );
This is one of the most frequently asked JavaScript interview questions and answers for freshers in recent times.
The output logged will be:
undefined Johnny Deep
The first console.log prints undefined because heroIdentity()is been invoked in the global context (i.e., the window object) where the _name property doesn’t exists.
The way to fix it is by binding, it to hero object by using bind.
var heroIdentity = hero.getIdentity.bind(hero);
The output logged will be:
10 2
When inside the method, fn() is called the “this” of the function fn is at window level. So, “this.length” will produce 10.
Now, when arguments[0]() is called, then argument[0] is equivalent to “fn” and function fn is called. But “this” now is the arguments array, which is of length 2 because it contains two arguments (fn, 1). So, “this.length” will produce 2.
The output logged will be: null
The reason is for prototype chaining. The __proto__ of ‘hello’ is the global String.
console.log(('hello').__proto__);
Then the __proto__ of it is the global Object.
console.log(('hello').__proto__.__proto__);
Now, the Object is the final thing from which everything in JavaScript is created and it points to null.
This is one of the most frequently asked JavaScript interview questions and answers for freshers in recent times.
Nested promises are set of promises in which , the result of one promise we call another in the .then statement. It is very useful in practical applications, where the result of fetch from an API endpoint will result in sending the data to another endpoint. Nested promises can also be done with callback functions, but the code get complicated soon.
Let’s look at an example of nested promises. Here we have three functions which return promises- movieTicketQueue, buyPopcorn and happyPartner. Now only the movieTicketQueue is returning resolve() or reject() depending on random number. The other two functions are returning only resolve() for simplicity sake.
Now, when the movieTicketQueue function is run and return a resolve(), then the immediate .then block will be run or else we will go to the .catch block. In the .then we are returning the next buyPopcorn and in its .then we are returning the happyPartner. We are passing the message from one function to other, so it will be appended.
On running the code and getting a resolve, because we random number greater than 0.5, we get below output.
On running the code and getting a reject, because we random number less than 0.5, we get below output.
We can implement the Array.prototype methods by using callbacks and actually this is the way it is implemented in JavaScript internally.
forEach
We are implementing our version of forEach as myEach by having the callback attached to the prototype, which is available to every JS function. Here “this” is equal to the array. So, we are iteration over it using traditional for loop and calling the callback function on each iteration.
map
We are implementing our version of map as myMap, by creating an empty array in our function and then pushing it in the iteration. From inside the push we are calling our callback, so when we are calling it we can use something like Math.round(line 17) to change an individual item or just return it like in line 13.
filter
We are implementing our version of filter as myFilter. The process is quite similar to map, where we create an empty array ad push to it. But as we know that filter goes through the array and gives an subset of elements depending on boolean expression.
Here when we iterate through the array and call the callback in an if statement, and if it’s true we are pushing the item into the array.
Implement your version of Array.prototype methods some, every and reduce in vanilla JavaScript ?
We will be implementing some, every and reduce by using of callbacks, in the same way, we used to implement forEach, map and filter in the previous question.
some
The Array prototype method some returns true if any element of the array fulfils the condition we are testing. Here also like filter, we will have the callback been checked in an if statement in every iteration. This will test our condition and even if one of it pass we return a true and get out of loop. If the iteration is complete, it means not a single element satisfy condition and we return false.
every
It is the opposite of some. The method “every” will return true only if every element passes the test. Here we do a trick in the if statement. We check the opposite of the test, so say if element should be greater than 10, we are checking for less than 10. So, if even one is less than 10 we return false. And if we iterate through whole loop, means all element satisfy the condition so we return true.
reduce
The method reduce is considered the hardest in the Array prototype methods to master. It is because it’s concept is quite different. It takes the whole array and iterate through it and returns a single value. It is useful to do sum/multiply/subtract of all the elements of an array, but is more powerful than that. To do this it have an accumulator, which is used to hold the number in each run. This accumulator will be operated with the current value of the iteration.
Now in our implementation, we first check whether an accumulator was supplied or else make it to undefined. Now inside the loop we update the accumulator variable by using the callback.
Named after Haskell Brooks Curry, currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.
In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.
Here is a simple example to write a simple multiply function and then the function asked in the question with currying.
Currying works because of JavaScript concept of closures. The closure created by the nested functions to retain access to each of the arguments. So inner function which do “return a * b * c * d” have access to all arguments.
Expect to come across this, one of the top JavaScript interview questions for experienced professionals in web development, in your next interviews.
Map and WeakMap are data structures that were introduced in ES6.
Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted.
Let’s find out the reason for Map by analysing a problem with Objects. In the below example, we have an object “x” and another object “a”. Now we are using “a” as a key and push a value to “x”. Now, if we console log “x” the key is shown as [object object], but then also we can extract it’s value by x[a].
But the real problem occurs when we add another object to “x” for key. It over-writes the earlier object. This occurs because in JavaScript we can have only 1 key as an object.
Now we will look at how Maps help. We create Map by the new keyword. And also to add to Map we need use one of its method set.
In the below example the objects “a” and “b” are been added as key successfully.
Notice that the __proto__ object contains Symbol.iterator, so the for..of loop can be used to iterate over it like arrays. The same is not true for Objects.
We iterate over Map using the for..of loop. We get an array of [key, value] for each element in Map. So, we de-structure it into [key, value] pair.
If we add the same object as key as in line 9 for “a”, the Map will over-write the old value of the key.
Also, we can delete an entry by passing it’s key in delete method.
There is one problem with Map and it is that it holds the Map’s key, even if the original key is deleted. That is the reason we use WeakMap. So, WeakMap allows garbage collector to work as it holds a weak reference to its key but Maps doesn’t allow garbage collector to work.
Another difference is that keys of WeakMaps are of type Object only. Primitive data types(Number, String, Boolean, Symbol) can only be used in Maps.
Set and WeakSet are also new data structures introduced in ES6 along with Map and WeakMap. Set are data-types like arrays, but the key feature is that we cannot keep duplicate data. In a nutshell Sets are nothing but unique arrays.
Let consider below example. The way to create a Set is through the constructor function using “new” keyword. We add value to Set by using add method and delete value from Set using delete method.
Notice that it’s __proto__ object have Symbol.iterator like array, which means it is iterable.
There is another method to create a Set. We can pass an iterable like array to the constructor function.
Also, we cannot add duplicates value in a Set. Also we can add values to Set using add in method chaining format. All are shown in below example.
We can use this feature to get unique items from an array containing duplicate items. Notice at Line 3, we are using spread operator inside an array. It is because Set is not exactly array and we are converting it to array.
WeakSets are like WeakMaps and one of key feature is that we cannot have Primitive data-types(Number, String, Boolean, Symbol) as it’s items. So, the below will throw and error.
So, we will add Objects to WeakSet. Also, notice that it’s __proto__ doesn’t have many methods and it is not an iterable.
Symbols are the new primitive data-type introduced in ES6. Symbols is unique and immutable data-type. They are tokens that can be used as unique ids.
Two Symbols are never the same, even if they are declared as same. Consider the below example.
We can also put some value inside the constructor in Symbol, which helps in identifying it. Also, it’s typeof is symbol
We cannot directly concatenate it to a Sting as it will throw an error.
So, we convert a Symbol into a String by using string in-built function toString().
One of the use case of Symbol is to be used as unique keys. We can use them very efficiently in Objects and Maps, where only unique keys are allowed.
A must-know for anyone looking for top JavaScript coding interview questions. This is one of the frequently asked JavaScript questions today.
The concept of Sub-classes and inheritance is like that in other languages like Java and C++. The sub-class can inherit properties from its parent class and can also override or update an existing method.
Let’s consider the below example. We have a Parent class “Mammal” and a Sub-class “Bat” which is inheriting from it. Notice, that we have use the “extends” keyword.
To use the “legs” and “name” variable in “Bat”, we use the “super()” method. Also, notice that we can use update “walk()”, and add additional functionalities.
To understand iterators, we will first look into recently introduced [Symbol.iterator] property in data types.
This indicates whether a data structure is iterable or not. This includes array, strings, Map, Sets and NodeList. Objects doesn’t have a [Symbol.iterator] property.
If we check the __proto__ of an array, we can find the [Symbol.iterator] property.
But it is not the case with Objects as it is not iterable.
Now, iterator are created using the “Symbol.iterator” and can be used to iterate over all data structures which have [Symbol.iterator] property.
Let consider the below example. Here we create an iterator by the syntax at line 3. Now we can iterate over the array using “iterator.next()”. Each run gives and Object which have the “value” and “done”, which specifies whether there is an element. Notice, after the fifth run we get the “value” as undefined and “done” as true.
ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped.
Let’s look at the below example. The generator function have a special syntax with “*”. Also, inside the generator we have “yield” statements. Each “next()”, goes to the next yield statement.
The above example doesn’t shows any advantages of generator and it is same as iterating through an array. But let’s look at next example, where we have an infinite while loop inside an generator.
First look at this normal function. If we run it, it will cause an infinite loop and crash your browser.
But the same type of function with generator doesn’t produce an infinite loop. It pauses every time yield is called and will generator the next value of “i” every-time “next()” is called. So, this function can be used to generate any time “i” and not like in array where we have to give the size of array in advance.
In JavaScript every object is created from a global “Object”(Notice the capital ‘O’). If we look at it in console, it have many properties and create been one of it.
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Consider the below example, where we can create a new object from the existing object and can also add new properties to it or modify an existing property.
Now, let see a practical use of Object.create in Inheritance. In below example we have an Employee function, which have two functions in its Prototype. Then we have another function SalesEmployee and then set it’s Prototype to Employee’s Prototype. We also have a function in the prototype of SalesEmployee
SalesEmployee.prototype = Object.create(Employee.prototype);
We then create an instance of the SalesEmployee as emp1 variable. It have all functions of Employee function and can also use it.
Prototype chain can be explained through below example. Here we have three functions Mammal, Whale and BlueWhale. Each have their own version of print().
We are inheriting from Mammal to Whale by setting Whale’s prototype to be Mammal’s prototype.
Then inhering from Whale to BlueWhale by setting BlueWhale’s prototype to be Whale’s prototype.
Then we have three instances of Mammal, Whale and BlueWhale. On calling the print(), we get the respective console log.
Now, let remove BlueWhale’s print() method and then if we call print() on its instance blueWhale, we get result from Whale’s print().
If we further remove Whale’s print() method and then if we call print() on its instance blueWhale, we get result from Mammal’s print().
So, if you call an method on a Child and the method is not there, it will check in its Parent and if not there then will check in Parent’s parent.
Don't be surprised if this question pops up as one of the top interview questions for JavaScript in your next interview.
To understand inheritance using constructor function, we will see an example containing a Mammal parent function and Human child function. Also, make the Human’s Prototype have a reference of Mammal’s Prototype using Object.create. Human’s Prototype will have all methods of Mammal’s Prototype.
Now, let’s look into “Human” in the console. As you can see it contains “Mammal” sleep and walk function in it’s __proto__.
But we have a major problem because the statement Human.prototype = Object.create(Mammal.prototype) wipes out any Human’s Prototype function and also it’s constructor.
We didn’t declared any Human’s Prototype function, but the constructor was wiped.
So, we solve it by below code. It is using Human.prototype.constructor = Human to set the constructor back in “Human”.
Also, we are declaring Human’s Prototype function after Human.prototype = Object.create(Mammal.prototype)
... ... Human.prototype = Object.create(Mammal.prototype); Human.prototype.constructor = Human; Human.prototype.fly = function() { return 'Flying with Gliders'; }
Let’s now complete the code and create two instances of “Human” as hari and harry. Both can access functions walk, sleep and fly.
Interview Tips for Freshers
The industry is looking for candidates who can start with their work immediately and not the ones who are looking for a training. As a newbie in the IT Industry for a career as UI Developer, it’s good to learn the various UI frameworks like Vue.JS, React.JS, and Angular.js which are Javascript frameworks. To be shortlisted you can also take up some courses on these front-end technologies.
These javascript interview questions for beginners will help you to crack your javascript interview. Be prepared with the best interview questions for javascript and you will be able to pass the Javascript interview easily. All the best!
null (var null)
In JavaScript, null is a reserved identifier, therefore we cannot use it as an identifier in JavaScript. An error can be seen if we will write:
<html> <body> <script> var null; </script> </body> </html>
The following is the error visible when you will press F12 on browser:
SyntaxError: Unexpected token null
The web browser throws an error for “var null” since it is a reserved identifier.
undefined (var undefined)
The undefined is not a reserved identifier, therefore if you will write the following, then no error would be thrown:
<html> <body> <script> var undefined; document.write(undefined); </script> </body> </html>
Even if it is undefined, let us see what would be the output:
Undefined
In JavaScript, you may have seen the function name with a leading plus sign:
+function() { }();
The + is used for forcing the parse to consider whatever follows the leading plus as expression
This is how you can use + perfectly in a function invoked immediately, for example,
+function() { alert("Demo!"); }();
You can also display it as:
(function() { alert("Demo!"); })();
You can also use it like this (Closing parentheses at the end):
(function() { alert("Demo!"); }());
A staple in JavaScript technical interview questions and answers, be prepared to answer this one using your hands-on experience.
The number formatter would allow you to format numbers as the currency you want it to work.
The following is an example for US$ currency. Here we have set the currency as ‘USD’:
<!DOCTYPE html> <html> <body> <p>Average cost of a laptop (US$) </p> <script> var f = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, }); document.write(f.format(500)); </script> </body> </html>
The output:
Let us see another example in Euro. Here we have set the currency as ‘EUR’:
<!DOCTYPE html> <html> <body> <p>Average cost of a laptop (US$) </p> <script> var f = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', minimumFractionDigits: 2, }); document.write(f.format(300)); </script> </body> </html>
The output:
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The leading bang! Is used in anonymous functions:
!function(){ // }();
With that, you can also write it as:
+function(){ // }()
Generally, the leading bang (semi-colon) is used in functions in libraries. Let us see the different uses of including a leading semicolon:
Appending
The leading semicolon in immediately-invoked function expressions prevent errors when appending the file during concatenation. This concat is to a file containing an expression improperly concluded with a semicolon.
Concatenate
The purpose to include semicolon is to safely concatenate several JS files into one.
Preceding Code
A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.
Let’s see an example. Let’s say we are concatenating two files with self-invoking functions:
Function ONE
(function(){...ONE...})()
Function TWO
(function(){...TWO...})()
Now concatenating it will give the following result:
(function(){...ONE...})() (function(){...TWO...})()
Function TWO can have a leading semicolon:
!(function(){...TWO...})()
Now after concatenation:
(function(){...ONE...})();(function(){...TWO...})()
Yes, it is possible to create a custom alert box with CSS and JavaScript library jQuery.
Let us see an example wherein we have styled the alert box, it’s button, background color, border, position, etc.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> function myAlertBox(msg, myYes) { var box = $("#test"); box.find(".msg").text(msg); box.find(".yes").unbind().click(function() { box.hide(); }); box.find(".yes").click(myYes); box.show(); } </script> <style> #test { display: none; background-color: blue; border: 2px solid #aaa; color: white; position: fixed; width: 250px; height: 80px; left: 50%; margin-left: -80px; margin-top: 50px; padding: 10px 10px 10px; box-sizing: border-box; text-align: center; } #test button { background-color: white; display: inline-block; border-radius: 5px; border: 1px solid #aaa; padding: 5px; text-align: center; width: 80px; cursor: pointer; } #confirm .msg { text-align: left; } </style> </head> <body> <div id = "test"> <div class = "message">Welcome to the website!</div> <button class ="yes">OK</button> </div> <h2>Fancy Alert Box</h2> <input type = "button" value = "Display" onclick = "myAlertBox();" /> </body> </html>
The output displays the button which is to be clicked to generate the new custom alert box;
On clicking the above “Display” button, the following alert is visible which we styled:
One of the most frequently posed advanced JavaScript interview questions, be ready for this conceptual question.
The setTimeout() function is used in JavaScript to delay a function call.
For example, if you want to delay the function call by 5 seconds, then you can easily achieve this using the setTimeout() function.
The following is the syntax:
setTimeout(func_name, milliseconds, arg1, arg2, ...)
Here,
The following is an example:
Let’s say we want the function cal to delay by 3 seconds, therefore we will implement the setTimeout( with a parameter as 3000 milliseconds (i.e. 3 seconds):
function display() { setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); }
The example:
<!DOCTYPE html> <html> <body> <button onclick="display()">Click</button> <script> function display() { setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); } </script> <p>Wait for 3 seconds after clicking the button</p> </body> </html>
The output displays a button:
After 3 seconds, the following would be visible since we delayed the execution:
Create a custom object in JavaScript, using the “new”. It is followed by the constructor method Object():
var department = new Object();
Let us see an example to create a custom object in JavaScript:
<html> <head> <title>Custom objects</title> <script> var department = new Object(); department.name = "Finance"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>
The output:
Above, firstly we have created an object:
var department = new Object();
After that properties are assigned:
department.name = "Finance";
department.id = 005;
department.location = "North";
The Array.from() method is used in JavaScript to convert the arguments object to an array.
Let us first see what Array.from() method provides us:
Array.from(obj, mapFunction, thisValue)
Here,
Here, we have a function, which we are calling with some values:
display('q', 'w', 'h', 'm', '20', '66', '35')
The display() function consider arguments and sets using the Array.from() method. With that the sort() method is used to sort the array for our example:
function display(){ var myArgs = Array.from(arguments); return myArgs.sort(); }
The following is an example to convert the arguments object to an array:
<!DOCTYPE html> <html> <body> <script> function display(){ var myArgs = Array.from(arguments); return myArgs.sort(); } document.write(display('q', 'w', 'h', 'm', '20', '66', '35')); </script> </body> </html>
The output:
20,35,66,h,m,q,w
To round a number to specified decimal place in JavaScript, the toFixed() method is to be used.
Let us first see the syntax;
number.toFixed( [digits])
Here, digits is the decimal places to be set. For example, for 1 decimal place:
variable.toFixed(1))
The following is an example to round a number to 2 decimal places in JavaScript:
<html> <head> <title>JavaScript toFixed()</title> </head> <body> <script> var a = 291.78687; document.write("Number = " + a); document.write("<br>Result (2 decimal places) = " + a.toFixed(2)); </script> </body> </html>
The output:
Number = 291.78687 Result (2 decimal places) = 291.79
Let us see another example wherein we will round a number to 3 decimal places in JavaScript:
<html> <head> <title>JavaScript toFixed()</title> </head> <body> <script> var a = 291.78687; document.write("Number = " + a); document.write("<br>Result (3 decimal places) = " + a.toFixed(3)); </script> </body> </html>
The output:
Number = 291.78687 Result (3 decimal places) = 291.787
The parseInt() method parses up to the first non-digit and returns the parsed value, whereas Number() converts the string into a number, which can also be a float.
To learn about the difference between parseInt(string) and Number(string) in JavaScript, let us see an example:
Let’s say we have the following value:
20demo
Using parseInt(string), 20 is returned:
<!DOCTYPE html> <html> <body> <script> document.write(parseInt("20demo")); </script> </body> </html>
The output:
20
Using the Number(string), the same value returns NaN:
<!DOCTYPE html> <html> <body> <script> document.write(Number("20demo")); </script> </body> </html>
The output:
NaN
Let us now workaround for a float value with both Number(string) and parseInt(string):
<!DOCTYPE html> <html> <body> <script> document.write(Number("12.99demo")); document.write("<br>"+parseInt("12.99demo")); </script> </body> </html>
The output:
NaN 12
Let’s say the following are our arrays:
[20, 40, 60] [80, 100, 120]
To merge them, JavaScript provides the Array.concat() method. The return value of this method is a new array with the result of concatenated arrays:
var res = arr1.concat(arr2);
Let us now merge the above two arrays:
<html> <head> <title>Merge JavaScript Arrays</title> </head> <body> <script> var arr1 = [20, 40, 60]; var arr2 = [80, 100, 120]; document.write("Array 1 = " + arr1); document.write("<br>Array 2 = " + arr2 ); var res = arr1.concat(arr2); document.write("<br>Merged Arrays = " + res ); </script> </body> </html>
The output displays the merged arrays:
Array 1 = 20,40,60 Array 2 = 80,100,120 Merged Arrays = 20,40,60,80,100,120
The getMinutes() method is provided by JavaScript to get the current minutes in JavaScript. The minutes are according to local time. We will add minutes to it using the setMinutes() method.
Create a Date object:
var date = new Date();
Now get the current date and time:
// current date and time document.write("Current Date and Time = "+date);
Now, under setMinutes(), get the current minutes using getMinutes() and add the minutes as shown below. We added 10 minutes here:
date.setMinutes(date.getMinutes() + 10 );
The following is an example to add 15 minutes to a date in JavaScript:
<html> <head> <title>JavaScript setMinutes() Method</title> </head> <body> <script> var date = new Date(); // current date and time document.write("Current Date and Time = "+date); date.setMinutes(date.getMinutes() + 15 ); document.write("<br>New Date = "+date); </script> </body> </html>
The output:
Current Date and Time = Sat Dec 15 2018 20:11:14 GMT+0530 (India Standard Time) New Date = Sat Dec 15 2018 20:26:14 GMT+0530 (India Standard Time)
To check whether a value entered is a NaN or not, use the Number.isNaN() method. This method returns true if the value is not a number, else false is returned.
Let’s say the following is our value:
var a = 'z';
To check whether it is a number or not, use isNaN() method:
isNaN(a);
The following is an example that returns true i.e. not a number:
<!DOCTYPE html> <html> <body> <script> var a = 'z'; document.write(isNaN(a)); </script> </body> </html>
The output:
true
Let us see another example:
<!DOCTYPE html> <html> <body> <script> var a = 0/0; document.write(isNaN(a)); </script> </body> </html>
The output generates True since 0/0 is not a legal number:
True
Let us see another example that is a number. Therefore, false is returned:
<!DOCTYPE html> <html> <body> <script> var a = 50; document.write(isNaN(a)); </script> </body> </html>
The output:
false
Advanced Encryption Standard (AES) encrypts the data in the application. To perform AES, the JavaScript library Forge is used.
An example for encryption can be string encrypted to store in the database.
Yes, we can preserve the readability of text using the fontSizeAdjust property. This sets the difference between lowercase and uppercase letters size.
Use the document.forms length property of forms to count the number of forms in a document. Here’s an example for the same:
<!DOCTYPE html> <html> <body> <form> Name: <input type="text" name="my_name" value="demo"> Password: <input type="password" name="pwd" value=""> <input type="submit" value="Submit"> </form> <script> var res = document.forms.length; document.write("<br>Count of forms = "+res); </script> </body> </html>
The output displays the count:
To interact with the browser, the Browser Object Model has some properties and methods. Some examples include, the height and width of the window/ screen.
Some of its methods include:
To find the coordinates of cursor in JavaScript, use event.screenX and event.screenY. In this example, we are display the cursor coordinates relative to the screen:
<!DOCTYPE html> <html> <head> <script> function display(event) { document.write("Coordinate : X = " + event.screenX + "<br>Coordinate : Y = " + event.screenY); } </script> </head> <body> <div onmousedown="display(event)">Display coordinates of cursor...</div> </body> </html>
The columnFill property is used in JavaScript to fill columns. It means you can divide your content in columns like 2 3, 4, columns on a web page. An example is shown below:
<!DOCTYPE html> <html> <body> <p>Create columns...</p> <button onclick="display()">Columns</button> <div id="demo"> Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! </div> <script> function display() { document.getElementById("demo").style.columnCount = "2"; document.getElementById("demo").style.columnFill = "balance"; } </script> </body> </html>
The above text is divided into two columns since we have set columnCount as 2:
To detect a mobile device, let’s say Android device, use the navigator.userAgent.match. Here, we have set it in a function:
Android: function() { return navigator.userAgent.match(/Android/i); },
For iOS:
iOS: function() { return navigator.userAgent.match(/iPhone|iPad/i); },
A staple in advanced JS interview questions with answers, be prepared to answer this using your hands-on experience. This is also one of the top interview questions to ask a JavaScript developer.
The pageBreakAfter property in JavaScript is used set the page-break behavior after an element. Let’s say you need to set if got footer:
function myfunc() { document.getElementById("idFooter").style.pageBreakAfter = "always"; }
The some() method checks if an array element satisfies a test. An example:
<!DOCTYPE html> <html> <body> <script> var val = [20, 28, 45]; function display(a) { return a > 21; } document.write("Are their values greater than 21 in the array = "+val.some(display)); </script> </body> </html>
The output is true i.e. we have tested the array element and checked a condition: elements greater than 21.
JavaScript array every method checks whether the array elements (all) passes the test. A condition is checked for the test. An example here checks for every elements in the array for a condition passed in the function:
<!DOCTYPE html> <html> <body> <script> var val = [128, 29, 28, 45]; function display(a) { return a > 21; } document.write("Are all the values greater than 21 in the array = "+val.every(display)); </script> </body> </html>
The output displays true since the condition is satisfied for all the elements of the array.
The onresize event is executed a JavaScript when the browser window is resized. An example here displays the same:
<!DOCTYPE html> <html> <head> <script> function display() { var a = "Window Width=" + window.outerWidth + ", Window Height=" + window.outerHeight; document.getElementById("myid").innerHTML = a; } </script> </head> <body onresize="display()"> <p>Resize browser window!</p> <p id="myid"> </p> </body> </html>
The above displays the following output when the window is resized:
Resize browser window! Window Width=1366, Window Height=728
The onabort event is executed when the loading of an image is aborted. Use it in an image tag like this:
<img src="demo_image.jpg" onabort="display()">
Here, you can display an alert when the loading of image aborts:
function abortFunc() { alert('Image isn’t loading!'); }
A staple in advanced JS interview questions with answers, be prepared to answer this one using your hands-on experience. This is also one of the top interview questions to ask a JavaScript developer.
You can fill static values in an array using the fill() method in JavaScript. An example is here:
<!DOCTYPE html> <html> <body> <script> var arr = ["abc", "def", "ghi", "jkl"]; document.write("Initial array = "+arr); document.write("<br>Updated array = "+arr.fill("pqr",1,2)); </script> </body> </html>
The output displays that the array is set with static value:
Initial array = abc,def,ghi,jkl Updated array = abc,pqr,ghi,jkl
Use the join() method to join the elements of an array into string with a separator. An example here:
<!DOCTYPE html> <html> <body> <script> var arr = ["abc", "def", "ghi", "jkl"]; document.write("Initial array = "+arr); document.write("<br>Updated array = "+arr.join(" demo ")); </script> </body> </html>
Above, we have joined the elements into a string with a separator.
The output is:
Initial array = abc,def,ghi,jkl Updated array = abc demo def demo ghi demo jkl
This, along with other JavaScript basic interview questions for freshers, is a regular feature in web developer interviews, be ready to tackle it with the approach mentioned below.
Logic errors occur when there is a mistake in the logic. This can lead your script to work inappropriately to give unexpected results.
The blur event triggers when object loses focus. An example here displays that we write a name in the textbox and then when the object loses focus, the text color is changed. This happens since the blur event triggers when the focus ends:
<!DOCTYPE html> <html> <body> <h2>Type your name</h2> <input type="text" onblur="display(this)"> <script> function display(z) { z.style.color = "green"; } </script> </body> </html>
In JavaScript, an onfocus event is triggered when element gets focus. An example here displays that a user types in the textbox and the onfocus event is triggered, allowing the color of the text to change to yellow:
<!DOCTYPE html> <html> <body> <h2>Type your name</h2> <input type="text" onfocus="display(this)"> <script> function display(z) { z.style.color = "yellow"; } </script> </body> </html
When a visitor leaves the web page, then the onpagehide event triggers. The visitor can move to another page or click a link after leaving the current web page. An example here displays an alert box when the user tries to leave the page. This happens since onpagehide event fires when the page is left:
<!DOCTYPE html> <html> <body onpagehide="display()"> <p>Close the page</p> <script> function display() { alert("It was nice having you here!"); } </script> </body> </html>
The oninput event occurs when a value is included in the input box. This is how we can set the oninput event:
<input type="text" id="display" oninput="display()">
Above, the function display() is called when a user begins adding value in the textbox: function display() { var a = document.getElementById("display").value; document.write("Typed: " + a); }
This, along with other JavaScript basic interview questions for freshers, is a regular feature in web developer interviews, be ready to tackle it with the approach mentioned below.
JavaScript is a scripting language for web development. It implements complex things like displaying timely content updates, interactive maps, etc. on a webpage, making the page more lively and interactive. It is widely used in Mobile application development and Game development. JavaScript has become the most popular programming language for web development today. You can understand the importance of JavaScript from the recent reports, JavaScript is currently being used by more than 94 percent of all websites.
JavaScript is a popular product in the languages category and around 10,000 + companies are using the JavaScript software. For companies like Microsoft, Accenture, Google, Fitbit, Shopify and many more, JavaScript is immensely important. As a result, a huge number of aprirants take a JavaScript Course in order to stay ahead of the competition.
Over the last few years, JavaScript has taken over the web development world and became the primary language of choice for many new developers. It is not just because JavaScript provides a great way to make web pages interactive, but also because JavaScript developers have a great demand in the job market. The Employment of web developers is projected to grow 15 percent from 2016 to 2026, much faster than the average for all occupations. Demand will be driven by the growing popularity of mobile devices and e-commerce. JavaScript developers get $ 62,155 per month. This number can be increased when you enroll in the best web development courses.
So, if you are planning to start your career in JavaScript, you need to be well prepared with all the possible JavaScript interview questions which could be asked in a JavaScript interview. These JavaScript Interview Questions will provide you with an in-depth knowledge and help you ace your JavaScript interview.
But how can one crack a tricky JavaScript interview? How to answer the toughest of JavaScript interview questions? Don't worry, these are the questions that bother interviewees, beginners and freshers alike, more than the JavaScript interview questions themselves. These JavaScript interview questions have been designed specially to get you acquainted with the nature of questions that you may come across during your JavaScript interview.
To relieve you of the worry and burden of preparation for your upcoming interviews, we have compiled the above JavaScript interview questions with answers prepared by industry experts. These common interview questions on javascript will help you ace your Javascript Interview.
Candidates aspiring to build a career in frontend/backend web app development can learn about JavaScript from the excellent training available.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.
Get a 1:1 Mentorship call with our Career Advisor
By tapping submit, you agree to KnowledgeHut Privacy Policy and Terms & Conditions