JavaScript Developer Interview Questions for Freshers
1.
What are the data types in JavaScript
In JavaScript, data types can be categorized into two main groups: primitive and non-primitive (also known as reference types) data types. Here's an explanation of each:
1. Primitive Data Types:
These are immutable data types that store a single value.
a. Boolean: Represents a logical value, either true or false. It is commonly used for conditions and branching in JavaScript.
b. Number: Represents numeric values, including integers and floating-point numbers.
c. String: Represents a sequence of characters enclosed in single or double quotes. Strings are used to represent textual data.
d. Null: Represents the intentional absence of any object value. It is often assigned to a variable to indicate that it has no value or that the value is unknown.
e. Undefined: Represents an uninitialized or undeclared variable. If a variable is declared but not assigned a value, it will have the value of undefined.
f. Symbol: Represents a unique identifier. Symbols are typically used as keys in objects to avoid naming conflicts.
2. Non-Primitive (Reference) Data Types:
These are mutable data types that store references to memory locations rather than the actual values.
a. Object: Represents a collection of key-value pairs and provides a way to group related data and functionality together. Objects can be created using object literals {}, constructor functions, or the class syntax introduced in ECMAScript 2015.
b. Array: Represents an ordered list of values. Arrays can hold values of any type, and their elements are accessed using numeric indices starting from 0.
c. Function: Represents executable code that can be invoked and performs a specific task. Functions are one of the fundamental building blocks in JavaScript and can be defined using function declarations or function expressions.
Non-primitive data types, such as objects, arrays, and functions, are passed by reference, meaning that when you assign them to a variable or pass them as arguments to functions, you are working with a reference to the original value stored in memory. Primitive data types, on the other hand, are passed by value, meaning that when you assign them to a variable or pass them as arguments, a copy of the value is created.
let isTrue = true;
let isFalse = false;
console.log(isTrue); // Output: true
console.log(isFalse); // Output: false
let count = 10;
let price = 4.99;
console.log(count); // Output: 10
console.log(price); // Output: 4.99
let message = "Hello, world!";
console.log(message); // Output: Hello, world!
let value = null;
console.log(value); // Output: null
let variable;
console.log(variable); // Output: undefined
let id = Symbol("unique");
console.log(id); // Output: Symbol(unique)
let person = {
name: "John",
age: 30,
isAdmin: false
};
console.log(person); // Output: { name: 'John', age: 30, isAdmin: false }
let numbers = [1, 2, 3, 4, 5];
console.log(numbers); // Output: [1, 2, 3, 4, 5]
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
2.
What will be the output of the below code: let obj ={ a: 10, vir : function(){ x(); console.log(this.a); function x(){ console.log(this.a) } } } obj.vir();
The output of the above code for first 'this.a' is '10' and second 'this.a' inside function x is ‘undefined’.
Reason being that ‘this’ keyword when directly used inside an object’s method points to the object itself but in the above code ‘this’ keyword is present inside x() function of the vir() method , so its not being directly used in object’s method vir() , so it would refer to window object and there is no variable ‘a’ in the window object so output will be ‘undefined’.
let obj ={
a: 10,
vir : function(){
x();
console.log(this.a); //output 10
function x(){
console.log(this.a) // undefined
}
}
}
obj.vir();
3.
What will be the output of the below code for (var i= 0; i < 5; i++){ setTimeout(() => console.log(i)); }
Output will be:-
5
5
5
5
5
Reason - some people may think that the output should be 0,1,2,3,4 . But there is a twist here , the arrow function written inside setTimeout does not executes right way , instead it goes in the event queue. So , when the loop iterates from i = 0 till i =4 , all the five console.log(i) statements would go in the event queue , now at the end of iteration the value of i becomes 5 . After this the 5 console.log(i) statements present in the event queue would execute and hence we would see 5 printed 5 times on console.
4.
What will be the output of the below code :- var a = 90; doit(); function doit(){ console.log(a); var a = 10; }
Output of above will be undefined as inside function doit,variable 'a' will be hoisted at the top inside function scope and it will initialised as undefined.
var a = 90;
doit();
function doit(){
console.log(a); // undefined
var a = 10;
}
5.
Explain call(), bind() and apply() in JavaScript
In JavaScript, `call()`, `bind()`, and `apply()` are methods available on functions and are used to manipulate how functions are invoked and bound to a specific context. Here's an explanation of each of these methods:
1. `call()`:
The `call()` method is used to call a function with respect to any object. The `call()` method takes the context object as its first argument, followed by the arguments to be passed to the function.
Syntax: `function.call(context, arg1, arg2, ...)`
Example:
Output:
In the example above, `call()` is used to invoke the `greet()` function with the `person` object as the context. The first argument `person` sets `this` inside the function to refer to the `person` object.
2. `bind()`:
The `bind()` method creates a new function with a specified context and initial arguments, without invoking it immediately. It returns a new function that, when called, has its `this` value set to the provided context and any additional arguments are prepended to the original function's arguments.
Syntax: `function.bind(context, arg1, arg2, ...)`
Example:
Output:
In the example above, `bind()` is used to create a new function `greetPerson` that has its `this` value bound to the `person` object. The resulting function `greetPerson` can be invoked later with the remaining arguments.
3. `apply()`:
The `apply()` method is similar to `call()`, but it takes arguments as an array or an array-like object instead of individual arguments. It is used to invoke a function immediately, specifying the context and an array of arguments to be passed to the function.
Syntax: `function.apply(context, [arg1, arg2, ...])`
Example:
Output:
In the example above, `apply()` is used to invoke the `greet()` function with the `person` object as the context and an array containing the argument `'Bob'`.
To summarize:
- `call()` invokes a function immediately with a specified context and individual arguments.
- `bind()` creates a new function with a specified context and initial arguments, without invoking it immediately.
- `apply()` invokes a function immediately with a specified context and an array of arguments.
These methods provide flexibility in managing the execution context (`this`) and arguments when working with JavaScript functions.
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'Alice'
};
greet.call(person, 'Bob');
Hello, Bob! My name is Alice.
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'Alice'
};
const greetPerson = greet.bind(person);
greetPerson('Bob');
Hello, Bob! My name is Alice.
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'Alice'
};
greet.apply(person, ['Bob']);
Hello, Bob! My name is Alice.
6.
Advantage of using arrow functions
Arrow functions in JavaScript provide several advantages over traditional function expressions. Here are some benefits of using arrow functions:
1. Concise Syntax: Arrow functions have a compact and concise syntax, making the code more readable and reducing the amount of boilerplate code. They are particularly useful for writing shorter and more expressive functions.
2. Lexical `this` Binding: Arrow functions do not have their own `this` value. Instead, they lexically bind the `this` value of the enclosing scope. This means that the `this` value inside an arrow function is automatically inherited from the surrounding context. It eliminates the need to use `bind()`, `call()`, or `apply()` to preserve the `this` value or deal with `this`-related issues.
3. No Arguments Object: Arrow functions do not have their own `arguments` object. Instead, they inherit the `arguments` object from the enclosing scope. This can be beneficial in scenarios where you need to access the arguments passed to an enclosing function.
4. Implicit Return: Arrow functions provide implicit return behavior for concise one-line functions. If the function body consists of a single expression, you can omit the curly braces and the `return` keyword. The result of the expression will be automatically returned.
6. Well-suited for Callbacks: Arrow functions are well-suited for callback functions, such as event handlers or asynchronous operations, where the lexical binding of `this` and the concise syntax can make the code more readable and maintainable.
Here's an example to illustrate some of these advantages:
In the example above, the arrow function `num => num * num` provides a more concise and readable syntax compared to the traditional function expression. It also inherits the `this` value from the surrounding context, which can be useful in certain scenarios.
Overall, arrow functions enhance code readability, simplify `this` handling, and provide a more concise syntax for writing functions, making them a popular choice in modern JavaScript development.
const numbers = [1, 2, 3, 4, 5];
// Traditional function expression
const squared1 = numbers.map(function (num) {
return num * num;
});
// Arrow function
const squared2 = numbers.map(num => num * num);
7.
What is webpack and babel
Webpack and Babel are two popular tools commonly used in modern JavaScript development to enhance the development workflow and optimize the deployment of web applications. Here's a brief explanation of each:
1. Webpack:
Webpack is a module bundler for JavaScript applications. It takes multiple JavaScript modules, along with their dependencies, and bundles them into a single optimized file or multiple files called bundles. Webpack helps manage the dependencies between modules, allowing developers to organize and structure their code in a modular manner.
Key features and benefits of Webpack include:
- Module bundling: Webpack bundles modules together, which improves the loading time of web applications by reducing the number of network requests required to fetch individual files.
- Dependency management: Webpack analyzes the dependencies between modules, allowing developers to use `import` and `export` statements to organize and split code into separate files.
- Loaders: Webpack supports various loaders that enable the transformation of different file types (e.g., JavaScript, CSS, images) during the bundling process. Loaders can apply transformations, such as transpiling newer JavaScript syntax with Babel or applying CSS preprocessing.
- Code splitting: Webpack enables code splitting, which allows for the creation of multiple bundles that can be loaded on-demand, improving application performance by loading only the necessary code for specific routes or features.
- Development server and hot module replacement: Webpack provides a development server that serves the bundled application locally during development. It also supports hot module replacement (HMR), which allows developers to see the changes they make in real-time without reloading the entire page.
2. Babel:
Babel is a popular JavaScript compiler that allows developers to write code using the latest JavaScript syntax (ES6+, JSX, TypeScript) and transpile it into JavaScript that is compatible with older browsers and environments. Babel helps bridge the gap between modern JavaScript features and browser support, enabling developers to use the latest
8.
How can we add an element at the start of a JavaScript array
Method 1 : Using unshift() method
To add an element at the start of a JavaScript array, you can use the `unshift()` method. Here's an example:
In this example, the `unshift()` method is called on the `myArray` array and passed the element `1` as an argument. This adds the element at the beginning of the array. The existing elements are shifted to the right, and the length of the array is increased by one.
Method 2: Using concat() method
Note that the `unshift()` method modifies the original array and returns the new length of the array. If you need a new array without modifying the original one, you can create a new array using the spread operator or the `concat()` method:
Method 3 : Using splice() method
About splice() method :
It takes 3 parameters :
1. The index from where to start
2. Number of elements to remove starting from that index
3. Comma seprated list of the elements to add
const myArray = [2, 3, 4, 5];
myArray.unshift(1); // Add 1 at the start of the array
console.log(myArray); // Output: [1, 2, 3, 4, 5]
const myArray = [2, 3, 4, 5];
const newArray = [1, ...myArray]; // Using spread operator
console.log(newArray); // Output: [1, 2, 3, 4, 5]
// Alternatively, using concat()
const myArray = [2, 3, 4, 5];
const newArray = [1].concat(myArray);
console.log(newArray); // Output: [1, 2, 3, 4, 5]
Let arr = [a,b, c]
arr.splice(0,0,x)
console.log(arr) //output - [x,a,b,c]
9.
How to capitalise all the first letters of a given string
Css way :
Use css property Text-transform with values as capitalize
JS way :
1. Make first character of string as capital
2. Loop over the given characters of string
3. Whenever we find a space i.e " " while looping over the string, We have to capitalize the next letter of string using toUpperCase() method.
Text-transform : capitalize;
function capitalizeStr(str){
let arr = str.split("");
arr[0] = arr[0].toUpperCase();
for(let i in arr){
if(arr[i-1] === " "){
arr[i] = arr[i].toUpperCase();
}
}
return arr.join('');
}
console.log(capitalizeStr('just to test')) //output: Just To Test
10.
Difference between null and undefined
In JavaScript, `null` and `undefined` are two distinct primitive values that represent the absence of a meaningful value. Although they are similar in some ways, they have subtle differences. Here's a breakdown of the differences between `null` and `undefined`:
1. Assignment: `undefined` is a default value assigned to a variable that has been declared but has not been assigned a value. On the other hand, `null` is a value that can be assigned explicitly to a variable by the programmer to indicate the absence of an object or an empty value.
2. Type: `undefined` is a type itself in JavaScript and represents the absence of a value. It is considered a primitive value. On the other hand, `null` is an object type, which means it is an empty object reference.
3. Usage: `undefined` is commonly used to indicate the absence of a value, such as when a variable has not been assigned a value or when a function does not return a value explicitly. `null`, on the other hand, is typically used to indicate the intentional absence of an object or value.
4. Behavior: When you try to access a variable that has been declared but not assigned a value, it will have the value of `undefined`. When a function does not return a value explicitly, it implicitly returns `undefined`. On the other hand, `null` must be assigned explicitly by the programmer and is not assigned automatically.
5. Strict Equality: In JavaScript, `undefined` and `null` are not strictly equal to each other (`undefined === null` evaluates to `false`). They are distinct values with different types.
6. Type Coercion: When performing loose equality comparisons (using `==`), `null` and `undefined` are loosely equal to each other (`null == undefined` evaluates to `true`). However, when using strict equality comparisons (using `===`), they are not equal (`null === undefined` evaluates to `false`).
7. Passing Arguments: If a function parameter is not supplied with an argument, its value will be `undefined`. However, if you explicitly pass `null` as an argument, it will be assigned to that parameter.
In summary, `undefined` represents the absence of a value or an uninitialized variable, while `null` represents the intentional absence of an object or an empty value. They have different types, behaviors, and use cases in JavaScript.