Join Regular Classroom : Visit ClassroomTech

JavaScript Interview Questions – Beginner Level | Codewindow.in


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

1. What is difference between document.getElementById() and document.querySelector()?

document.getElementById(): Returns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.
element = document.getElementById(id);
document.querySelector(): Returns the first matching Element node within the node’s subtree. If no matching node is found, null is returned.
element = document.querySelector(selectors);
document.querySelectorAll(): Returns a NodeList containing all matching Element nodes within the node’s subtree, or an empty NodeList if no matches are found.
element = document.querySelectorAll(selectors);
Note: querySelector() is more useful when we want to use more complex selectors.


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

2. When to use forEach(), reduce(), map(), foreach() and filter() in JavaScript?

forEach(): It takes a callback function and run that callback function on each element of array one by one.

Basically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them.

var arr = [10, 20, 30];
arr.forEach(function (elem, index){
   console.log(elem + ' comes at ' + index);
})
/*
Output
10 comes at 0
20 comes at 1
30 comes at 2 
*/

filter(): The main difference between forEach() and filter() is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array. 
Note: filter does not update the existing array it will return a new filtered array every time.

var arr = [10, 20, 30]; 
var result = arr.filter(function(elem){
    return elem !== 20;
})
console.log(result)
/*
Output
[10, 30]
*/

map(): map() like filter() & forEach() takes a callback and run it against every element on the array but what makes it unique is it generate a new array based on your existing array.

Like filter(), map() also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array.

var arr = [10, 20, 30];
var mapped = arr.map(function(elem) {
    return elem * 10;
});
console.log(mapped)
/*
Output
[100, 200, 300]
*/

reduce(): reduce() method of the array object is used to reduce the array to one single value.

var arr = [10, 20, 30];
var sum = arr.reduce(function(sum, elem) {
    return sum + elem;
});
console.log(sum); 
// Output: 60

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

3. What are the javascript data types?

There are eight basic data types in JavaScript.
  

Data Types

Description

Example

String

Represents textual data

let str = ‘Hi’, let str2 = “Hello”, let str3 = `Hello World`

Number

An integer or a floating-point number

let num = 3, let num2 = 3.234, let num3 = 3e-2

BigInt

An integer with arbitrary precision

let num = 900719925124740999n, let num = 1n

Boolean

Any of two values: true or false

let flag = true

undefined

A data type whose variable is not initialized

let a;

null

Denotes a null value

let a = null;

Symbol

Data type whose instances are unique and immutable

let value = Symbol(‘hello’);

Object

key-value pairs of collection of data

let student = { };


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

4. What are global variables?

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

msg = “Hello” // var is missing, it becomes global variable

The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

5. What is the difference between == and === operators?

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this,
NaN is not equal to anything, including NaN.
Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined –> false but null==undefined –> true
Examples
0 == false       // true
0 === false    // false
1 == “1”         // true
1 === “1”      // false
null == undefined // true
null === undefined // false
‘0’ == false // true
‘0’ === false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory

C QA

Mostly Asked

DS QA

Mostly Asked

DBMS QA

Mostly Asked

ML QA

Mostly Asked


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

6. What is currying function?

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.

function volume(length) {
  return function(width) {
    return function(height) {
      return height * width * length;
    }
  }
}
volume(2)(3)(4); // 24
/*
Curried functions are great to improve code re-usability and functional composition.
*/

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

7. What is a unary function?

Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.

const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

8. What is a pure function?

Pure functions are functions that accept an input and returns a value without modifying any data outside its scope(Side Effects). Its output or return value must depend on the input/arguments and pure functions must return a value.

Example

function impure(arg) {
    finalR.s = 90
    return arg * finalR.s
}
/* The above function is not a pure function because it modified a state finalR.s outside its scope. */
function pure(arg) {
    return arg * 4
}

Here is a pure function. It didn’t side effect any external state and it returns an output based on the input.
A function must pass two tests to be considered “pure”:
Same inputs always return same outputs
No side-effects

a. Same Input => Same Output
Compare this:
const add = (x, y) => x + y;
add(2, 4); // 6
To this
let x = 2;
const add = (y) => {
x += y;
};
add(4); // x === 6 (the first time)

b. Pure Functions = Consistent Results
The first example returns a value based on the given parameters, regardless of where/when you call it.
If you pass 2 and 4, you’ll always get 6.

Nothing else affects the output.
Benefits
One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.
The pure functions are easier to parallelize
They also makes maintaining and refactoring code much easier.


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

9. What is a first class function?

JavaScript functions are first-class functions meaning functions and objects are treated as the same thing. Functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function “first-class citizens in JavaScript”
Example: Assign a function to a variable. 

//Example: Assign a function to a variable
const message = function() {
   console.log("Hello World!");
}
message(); // Invoke it using the variable
//Example: Pass a function as an Argument
function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");
//Example: Return a function
function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
//Example: Using a variable
const sayHello = function() {
   return function() {
      console.log("Hello!");
   }
}
const myFunc = sayHello();
myFunc();
//Example: Using double parentheses
function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
sayHello()();
// We are using double parentheses ()() to invoke the returned function as well.

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

10. What is the use of setTimeout?

The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let us log a message after 2 seconds using setTimeout method,
setTimeout(function() { console.log(“Good morning”); }, 2000);


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

11. What is the use of setInterval?

The setInterval() method is used to call a function or evaluate an expression at specified intervals (in milliseconds). For example, let us log a message after 2 seconds using setInterval method,

setInterval(function() { console.log(“Good morning”); }, 2000);


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

12. How setTimeout() and setInterval() are different from each other?

//Syntax for setTimeout
function displayMessage() {
    console.log('This message will be displayed only once after 4s!') ;
}
setTimeout(displayMessage, 4000);
//Syntax for setInterval
function displayMessage(){
    console.log('This message will be displayed after every 4s!') ;
}
setInterval(displayMessage, 4000) ;

Usage : setTimeout( function/expression, timeout, param1, param2, … ) ;
where expression/function is the JavaScript code to run after the timeout milliseconds have elapsed. The params are optional.
Usage : setInterval ( function/expression, interval, param1, param2, … );
where expression/function is the JavaScript code to run repeatedly at specified interval of time has elpased .
Main Difference
When you need to invoke a function/expression once after a specified duration use setTimeout() function. But, if you need to invoke a function/expression repeatedly at a specified interval of time, then you should use setInterval() function.


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

13. What is the purpose JSON stringify?

When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.

var userJSON = {'name': 'John', age: 31}
var userString = JSON.stringify(userJSON);
console.log(userString); 
/*
Output: 
{"name":"John","age":31}
*/

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

14. How do you redirect new page in javascript?

In vanilla javascript, you can redirect to a new page using location property of window object. The syntax would be as follows,

function redirect() {
  window.location.href = 'newPage.html';
}

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

15. How do you check whether a string contains a substring?

There are 3 possible ways to check whether a string contains a substring or not,

a) Using includes: ES6 provided String.prototype.includes method to test a string contains a substring

var mainString = “hello”, subString = “hell”;
mainString.includes(subString)

b) Using indexOf: In an ES5 or older environments, you can use String.prototype.indexOf which returns the index of a substring. If the index value is not equal to -1 then it means the substring exist in the main string.

var mainString = “hello”, subString = “hell”;
mainString.indexOf(subString) !== -1

c) Using RegEx: The advanced solution is using Regular expression test method(RegExp.test), which allows for testing for against regular expressions

var mainString = “hello”, regex = “/hell/”;
regex.test(mainString)


Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

16. How do you get the current url with javascript?

You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purpose but this solution has issues in FF.

console.log('location.href', window.location.href); // Returns full URL

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 695

Warning: Undefined array key "icon" in /home/u997094728/domains/codewindow.in/public_html/wp-content/plugins/elementor/includes/widgets/icon-box.php on line 708
Categories
Pages
Recent Posts