JavaScript Array Interview Questions and Answers contains the list of top 50 array based questions that are frequently asked in interviews. The questions list are divided based on difficulty levels (Basic, Intermediate, and Advanced). This guide covers fundamental concepts, common problems, and practical solutions, helping you master array manipulation techniques and impress interviewers with your knowledge and skills. Ideal for developers preparing for technical interviews.
Many top tech companies like - Google, Meta, Microsoft, Amazon, and Others include JavaScript array questions in their interview processes to assess candidates' problem-solving skills and technical proficiency. Master essential array concepts to enhance your coding skills and impress interviewers.
JavaScript Array Interview Questions and AnswersJavaScript array is a data structure used to store multiple values in a single variable. This article contains a set of questions that are mostly asked during the interviews. There is a detailed answer coupled with code examples which can help you prepare adequately enough.
Our Top 50 JavaScript Array interview questions have been picked strategically so that you can be ready for an interview. These queries will enable you to demonstrate your expertise and impress recruiters from major multinational corporations (MNCs).
JavaScript Array Interview Questions and Answers - Basic Level
1. What is an array in JavaScript? How do you declare an array?
An array in JavaScript is a data structure that allows you to store multiple values in a single variable. Arrays can hold values of any data type, and each value is accessed using an index, with the first index being 0.
JavaScript
// Declaring an array with three elements
let fruits = ['apple', 'banana', 'cherry'];
2. How do you access the elements of an array?
Elements in an array are accessed using their index. The index of the first element is 0, the second element is 1, and so on.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Outputapple
banana
cherry
3. How can you add elements to an array?
Elements can be added to an array using the push
method to add to the end, and the unshift
method to add to the beginning.
JavaScript
let fruits = ['apple', 'banana'];
fruits.push('cherry'); // Adds 'cherry' to the end
console.log(fruits);
fruits.unshift('mango'); // Adds 'mango' to the beginning
console.log(fruits);
Output[ 'apple', 'banana', 'cherry' ]
[ 'mango', 'apple', 'banana', 'cherry' ]
4. How can you remove elements from an array?
Elements can be removed from an array using the pop method to remove from the end, and the shift method to remove from the beginning.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
fruits.pop(); // Removes 'cherry' from the end
console.log(fruits);
fruits.shift(); // Removes 'apple' from the beginning
console.log(fruits);
Output[ 'apple', 'banana' ]
[ 'banana' ]
5. What is length property of an array?
The length property of an array returns the number of elements in the array. It is a dynamic property, which means it automatically updates when the array changes.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length);
6. How do you check if a variable is an array?
To check if a variable is an array, you can use the Array.isArray method. This method returns true if the variable is an array, and false otherwise.
JavaScript
let fruits = ['apple', 'banana'];
console.log(Array.isArray(fruits));
let notAnArray = 'apple';
console.log(Array.isArray(notAnArray));
7. How do you iterate over an array?
You can iterate over an array using a for
loop. This allows you to access each element in the array by its index.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Outputapple
banana
cherry
8. How do you use the forEach method?
The forEach method is used to execute a provided function once for each array element. It takes a callback function as an argument, which is called with each element, its index, and the entire array.
The forEach method does not return a new array and does not modify the original array.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`Fruit at index ${index} is ${fruit}`);
});
OutputFruit at index 0 is apple
Fruit at index 1 is banana
Fruit at index 2 is cherry
9. What is the difference between for...of and for...in loops in arrays?
The for...of loop iterates over the values of an array, whereas the for...in loop iterates over the keys (indexes) of an array. The for...of loop is generally preferred for arrays because it directly accesses the elements, while the for...in loop is more suitable for iterating over object properties.
10. How do you concatenate two arrays?
You can concatenate two arrays using the concat method or the spread operator (...).
The concat method returns a new array that is the combination of the two arrays, while the spread operator allows you to create a new array by spreading the elements of both arrays.
JavaScript
let fruits = ['apple', 'banana'];
let moreFruits = ['cherry', 'mango'];
// Using concat method
let allFruits = fruits.concat(moreFruits);
console.log(allFruits);
// Using spread operator
let allFruits = [...fruits, ...moreFruits];
console.log(allFruits);
1. Explain the map method and provide an example.
The map method creates a new array populated with the results of calling a provided function on every element in the calling array. It does not modify the original array but returns a new array with the transformed values.
The map method is often used for data transformation tasks, such as converting an array of numbers to their squares or extracting specific properties from an array of objects.
2. How does the filter method work?
The filter method creates a new array with all elements that pass the test implemented by the provided function. It calls the function for each element in the array and includes the element in the new array if the function returns true.
The filter method does not modify the original array and is useful for extracting a subset of elements based on certain criteria, such as finding all even numbers or filtering out invalid entries.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
3. Describe the reduce method with an example.
The reduce method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. The reducer function takes two arguments: the accumulator (which accumulates the callback's return values) and the current value (the current element being processed).
The reduce method is commonly used for summing up elements, finding averages, or performing other cumulative operations.
JavaScript
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);
4. What is the purpose of the find method?
The find method returns the value of the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let foundNumber = numbers.find(num => num > 3);
console.log(foundNumber);
5. How do you use the some method?
The some method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let hasEvenNumber = numbers.some(num => num % 2 === 0);
console.log(hasEvenNumber);
6. Explain the every method with an example.
The every method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let allEvenNumbers = numbers.every(num => num % 2 === 0);
console.log(allEvenNumbers)
7. What does the includes method do?
The includes method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
It can also accept a second argument to specify the position in the array at which to begin the search. The includes method is useful for checking the presence of an element in an array.
8. How do you use the indexOf method?
The indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present. It can also accept a second argument to specify the index to start the search from.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana'));
console.log(fruits.indexOf('mango'));
9. What is the slice method used for?
The slice method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
The original array is not modified.
10. Explain the splice method with an example.
The splice method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It modifies the original array and returns an array of the removed elements.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1, 'mango', 'grape');
console.log(fruits);
Output[ 'apple', 'mango', 'grape', 'cherry' ]
11. How do you use the join method?
The join method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. It is useful for creating a string from the elements of an array, such as converting an array of words into a sentence.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
let fruitString = fruits.join(', ');
console.log(fruitString);
Outputapple, banana, cherry
12. What is array destructuring and how does it work?
Array destructuring is a syntax that allows you to unpack values from arrays or properties from objects into distinct variables. It provides a convenient way to extract multiple elements from an array and assign them to variables in a single statement. You can also set default values for the variables in case the array does not contain enough elements.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
let [firstFruit, secondFruit] = fruits;
console.log(firstFruit);
console.log(secondFruit);
let [first, second, third, fourth = 'default'] = fruits;
console.log(fourth)
Outputapple
banana
default
13. How do you copy an array?
You can copy an array using the spread operator (...) or the Array.from method. Both methods create a shallow copy of the original array. The spread operator is concise and widely used, while Array.from is useful when you need to convert array-like objects or iterable objects to arrays.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
// Using spread operator
let fruitsCopy1 = [...fruits];
console.log(fruitsCopy1);
// Using Array.from method
let fruitsCopy2 = Array.from(fruits);
console.log(fruitsCopy2);
Output[ 'apple', 'banana', 'cherry' ]
[ 'apple', 'banana', 'cherry' ]
14. What are array-like objects and how do you convert them to arrays?
Array-like objects are objects that have a length property and indexed elements but do not have array methods like push, pop, etc. Common examples of array-like objects are the arguments object in functions and NodeList objects returned by DOM methods. You can convert array-like objects to arrays using Array.from or the spread operator (...).
15. Explain the flat method.
The flat method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. It is used to flatten nested arrays.
By default, flat flattens one level deep, but you can specify the depth as an argument to flatten deeper levels of nested arrays.
16. How does the flatMap method work?
The flatMap method first maps each element using a mapping function, then flattens the result into a new array. It is similar to map followed by flat with a depth of 1. The flatMap method is useful for scenarios where you need to both transform and flatten an array in a single step.
17. What is the from method and how is it used?
The Array.from method creates a new, shallow-copied Array instance from an array-like or iterable object. It is useful for converting other structures, such as NodeLists, strings, or sets, into arrays. You can also provide a mapping function as the second argument to Array.from to transform each element of the new array.
JavaScript
let string = 'hello';
let stringArray = Array.from(string);
console.log(stringArray);
let set = new Set([1, 2, 3]);
let setArray = Array.from(set);
console.log(setArray);
Output[ 'h', 'e', 'l', 'l', 'o' ]
[ 1, 2, 3 ]
18. Explain the fill method with an example.
The fill method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array length). It returns the modified array. The fill method is useful for initializing an array with a specific value or resetting elements in an existing array.
JavaScript
let numbers = [1, 2, 3, 4];
numbers.fill(0, 2, 4); // Fills with 0 from index 2 to 4 (exclusive)
console.log(numbers);
19. What does the sort method do and how can you customize it?
The sort method sorts the elements of an array in place and returns the sorted array.
By default, it sorts elements as strings in ascending order. This can lead to incorrect results when sorting numbers.
To customize the sort order, you can provide a compare function that defines the sort order. The compare function should return a negative value if the first argument is less than the second, zero if they're equal, and a positive value if the first argument is greater than the second.
20. What is the reverse method and how is it used?
The reverse method reverses the order of the elements in an array in place. The first element becomes the last, and the last element becomes the first. The reverse method modifies the original array and is useful when you need to reverse the order of elements, such as reversing a list of numbers or words.
JavaScript Array Interview Questions and Answers - Advanced Level
1. How do you merge two arrays and remove duplicates?
You can merge two arrays and remove duplicates by using the Set object, which automatically removes duplicate values.
JavaScript
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let mergedArray = [...new Set([...array1, ...array2])];
console.log(mergedArray);
2. Explain the concept of array buffer and typed arrays in JavaScript.
Array buffers are used to represent a generic, fixed-length binary data buffer.
Typed arrays are array-like views of an underlying binary data buffer. They provide a mechanism for accessing raw binary data.
JavaScript
let buffer = new ArrayBuffer(16);
let view = new Uint8Array(buffer);
console.log(view.length);
3. How do you sort an array of objects by a property value?
To sort an array of objects by a property value, you can use the sort method with a compare function that compares the desired property values.
JavaScript
let users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Peter', age: 35 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
Output[
{ name: 'Jane', age: 25 },
{ name: 'John', age: 30 },
{ name: 'Peter', age: 35 }
]
4. What is the difference between deep copy and shallow copy of an array?
A shallow copy of an array copies the array structure but not the objects it contains. Changes to objects in the original array affect the copied array and vice versa.
A deep copy copies the array and all nested objects, so changes to the original array do not affect the copied array.
JavaScript
let original = [{ a: 1 }, { b: 2 }];
let shallowCopy = [...original];
let deepCopy = JSON.parse(JSON.stringify(original));
original[0].a = 10;
console.log(shallowCopy[0].a);
console.log(deepCopy[0].a);
5. How can you find the intersection of two arrays?
The intersection of two arrays can be found by using the filter method to return elements that are present in both arrays.
JavaScript
let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let intersection = array1.filter(value => array2.includes(value));
console.log(intersection);
6. What are sparse arrays and how do they differ from dense arrays?
Sparse arrays have gaps between elements (i.e., some indices are empty), while dense arrays have elements at every index. Sparse arrays consume less memory for the gaps but can have performance implications.
JavaScript
let denseArray = [1, 2, 3];
let sparseArray = [1, , 3];
console.log(denseArray.length);
console.log(sparseArray.length);
console.log(sparseArray[1]);
7. How do you remove duplicates from an array?
Duplicates can be removed from an array using a Set, which automatically removes duplicates.
JavaScript
let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
8. Explain the copyWithin method with an example.
The copyWithin method shallow copies part of an array to another location in the same array, modifying it in place.
JavaScript
let arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr);
9. How can you convert an array to a string?
An array can be converted to a string using the toString or join method.
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.toString());
console.log(fruits.join(', '));
Outputapple,banana,cherry
apple, banana, cherry
10. What are array methods keys(), values(), and entries()?
The keys(), values(), and entries() methods return new Array Iterator objects. keys() returns the keys (indexes), values() returns the values, and entries() returns key-value pairs.
JavaScript
let arr = ['a', 'b', 'c'];
let keys = arr.keys();
let values = arr.values();
let entries = arr.entries();
console.log([...keys]);
console.log([...values]);
console.log([...entries]);
Output[ 0, 1, 2 ]
[ 'a', 'b', 'c' ]
[ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ] ]
11. How do you flatten an array of arrays?
You can flatten an array of arrays using the flat method. By default, flat flattens one level deep, but you can specify the depth as an argument.
JavaScript
let nestedArray = [1, [2, [3, [4, 5]]]];
let flatArray = nestedArray.flat(Infinity);
console.log(flatArray);
12. What is the Array.of method?
The Array.of method creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
JavaScript
let arr1 = Array.of(1, 2, 3);
console.log(arr1);
let arr2 = Array.of('a', 'b', 'c');
console.log(arr2);
Output[ 1, 2, 3 ]
[ 'a', 'b', 'c' ]
13. How do you fill an array with a specific value?
You can fill an array with a specific value using the fill method, which modifies the array in place.
JavaScript
let arr = new Array(5).fill(0);
console.log(arr);
14. Explain how to use the Array.prototype.reduceRight method.
The reduceRight method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
JavaScript
let arr = [1, 2, 3, 4];
let result = arr.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);
15. How can you sort an array of objects by multiple properties?
To sort an array of objects by multiple properties, you can use the sort method with a compare function that first compares one property and, if they are equal, compares another property.
JavaScript
let users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'John', age: 20 }
];
users.sort((a, b) => {
if (a.name === b.name) {
return a.age - b.age;
} else {
return a.name.localeCompare(b.name);
}
});
console.log(users);
Output[
{ name: 'Jane', age: 25 },
{ name: 'John', age: 20 },
{ name: 'John', age: 30 }
]
16. What is a jagged array and how do you create one in JavaScript?
A jagged array (also known as an "array of arrays") is an array whose elements are arrays of varying lengths.
JavaScript
let jaggedArray = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
];
console.log(jaggedArray);
Output[ [ 1, 2, 3 ], [ 4, 5 ], [ 6, 7, 8, 9 ] ]
17. How do you implement a binary search in an array?
A binary search can be implemented on a sorted array to efficiently find the index of a specific element. The algorithm repeatedly divides the search interval in half until the value is found or the interval is empty.
JavaScript
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
let sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(binarySearch(sortedArray, 5));
18. What is the findIndex method and how is it used?
The findIndex method returns the index of the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let index = numbers.findIndex(num => num > 3);
console.log(index);
19. How do you remove falsy values from an array?
Falsy values (false, 0, '', null, undefined, NaN) can be removed from an array using the filter method with a Boolean constructor as the callback.
JavaScript
let mixedArray = [0, 1, false, 2, '', 3, null, 'a', undefined];
let truthyArray = mixedArray.filter(Boolean);
console.log(truthyArray);
20. Explain the Array.prototype.sort method and its limitations.
The sort method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order. This can lead to incorrect results when sorting numbers, so a compare function should be provided for numeric sorting.
JavaScript
let numbers = [10, 2, 30, 4];
numbers.sort(); // Incorrect sorting for numbers
console.log(numbers);
// Correct numeric sorting
numbers.sort((a, b) => a - b);
console.log(numbers);
Output[ 10, 2, 30, 4 ]
[ 2, 4, 10, 30 ]
By understanding and practicing these questions and answers, you'll be well-prepared for a JavaScript array-related interview. Remember to explain your thought process clearly and back up your answers with examples whenever possible.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
11 min read
JavaScript Basics
Introduction to JavaScriptJavaScript is a versatile, dynamically typed programming language that brings life to web pages by making them interactive. It is used for building interactive web applications, supports both client-side and server-side development, and integrates seamlessly with HTML, CSS, and a rich standard libra
4 min read
JavaScript VersionsJavaScript is a popular programming language used by developers all over the world. Itâs a lightweight and easy-to-learn language that can run on both the client-side (in your browser) and the server-side (on the server). JavaScript was created in 1995 by Brendan Eich.In 1997, JavaScript became a st
2 min read
How to Add JavaScript in HTML Document?To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other ev
3 min read
JavaScript SyntaxJavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.Syntaxconsole.log("Basic Print method in JavaScript");Ja
6 min read
JavaScript OutputJavaScript provides different methods to display output, such as console.log(), alert(), document.write(), and manipulating HTML elements directly. Each method has its specific use cases, whether for debugging, user notifications, or dynamically updating web content. Here we will explore various Jav
4 min read
JavaScript CommentsComments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code.1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), JavaScript// A single line comment cons
2 min read
JS Variables & Datatypes
Variables and Datatypes in JavaScriptVariables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.Data TypesVariabl
6 min read
Global and Local variables in JavaScriptIn JavaScript, understanding the difference between global and local variables is important for writing clean, maintainable, and error-free code. Variables can be declared with different scopes, affecting where and how they can be accessed. Global VariablesGlobal variables in JavaScript are those de
4 min read
JavaScript LetThe let keyword is a modern way to declare variables in JavaScript and was introduced in ECMAScript 6 (ES6). Unlike var, let provides block-level scoping. This behaviour helps developers avoid unintended issues caused by variable hoisting and scope leakage that are common with var.Syntaxlet variable
6 min read
JavaScript constThe const keyword in JavaScript is a modern way to declare variables, introduced in (ES6). It is used to declare variables whose values need to remain constant throughout the lifetime of the application.const is block-scoped, similar to let, and is useful for ensuring immutability in your code. Unli
5 min read
JavaScript Var StatementThe var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared.Syntaxvar variable = value;It declares a variable using var, assigns it
7 min read
JS Operators
JavaScript OperatorsJavaScript operators are symbols or keywords used to perform operations on values and variables. They are the building blocks of JavaScript expressions and can manipulate data in various ways.There are various operators supported by JavaScript:1. JavaScript Arithmetic OperatorsArithmetic Operators p
5 min read
Operator precedence in JavaScriptOperator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
2 min read
JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers.JavaScript// Number + Number =>
5 min read
JavaScript Assignment OperatorsAssignment operators are used to assign values to variables in JavaScript.JavaScript// Lets take some variables x = 10 y = 20 x = y ; console.log(x); console.log(y); Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in the table with the description.OPERATOR NAMESH
5 min read
JavaScript Comparison OperatorsJavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. JavaScript// Illustration of (==) operator let x = 5; let y = '5'; // Checking of operands c
5 min read
JavaScript Logical OperatorsLogical operators in JavaScript are used to perform logical operations on values and return either true or false. These operators are commonly used in decision-making statements like if or while loops to control the flow of execution based on conditions.In JavaScript, there are basically three types
5 min read
JavaScript Bitwise OperatorsIn JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
JavaScript Ternary OperatorThe Ternary Operator in JavaScript is a conditional operator that evaluates a condition and returns one of two values based on whether the condition is true or false. It simplifies decision-making in code, making it more concise and readable. Syntaxcondition ? trueExpression : falseExpressionConditi
4 min read
JavaScript Comma OperatorJavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. JavaScriptlet x = (1, 2, 3); console.log(x); Output3 Here is another example to show that all expressions are actually executed.JavaScriptlet a = 1, b = 2, c = 3; l
2 min read
JavaScript Unary OperatorsJavaScript Unary Operators work on a single operand and perform various operations, like incrementing/decrementing, evaluating data type, negation of a value, etc.Unary Plus (+) OperatorThe unary plus (+) converts an operand into a number, if possible. It is commonly used to ensure numerical operati
4 min read
JavaScript in and instanceof operatorsJavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result.JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an e
3 min read
JavaScript String OperatorsJavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
JS Statements
JS Loops
JavaScript LoopsLoops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can u
3 min read
JavaScript For LoopJavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. Syntaxfor (statement 1 ; statement 2 ; statement 3){ code here...}Statement 1: It is the initialization of
4 min read
JavaScript While LoopThe while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true.Syntaxwhile (condition) { Code block to be executed}Here's an example that prints from
3 min read
JavaScript For In LoopThe JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota model: Corolla
3 min read
JavaScript for...of LoopThe JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre
3 min read
JavaScript do...while LoopA do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co
4 min read
JS Perfomance & Debugging
JS Object
Objects in JavascriptAn object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.There are two primary w
4 min read
Introduction to Object Oriented Programming in JavaScriptAs JavaScript is widely used in Web Development, in this article we will explore some of the Object Oriented mechanisms supported by JavaScript to get the most out of it. Some of the common interview questions in JavaScript on OOPS include: How is Object-Oriented Programming implemented in JavaScrip
7 min read
JavaScript ObjectsIn our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail.Creating Objects:In JavaScript, Objects can be created using two
6 min read
Creating objects in JavaScriptAn object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e
5 min read
JavaScript JSON ObjectsJSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
3 min read
JavaScript Object ReferenceJavaScript Objects are the most important data type and form the building blocks for modern JavaScript. The "Object" class represents the JavaScript data types. Objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). It is used to st
4 min read
JS Function
Functions in JavaScriptFunctions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
4 min read
How to write a function in JavaScript ?JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
JavaScript Function CallThe call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
2 min read
Different ways of writing functions in JavaScriptA JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case.Below are the ways of writing functions in JavaScript:Table of
3 min read
Difference between Methods and Functions in JavaScriptGrasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Explain the Different Function States in JavaScriptIn JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. Â In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( )
3 min read
JavaScript Function Complete ReferenceA JavaScript function is a set of statements that takes inputs, performs specific computations, and produces outputs. Essentially, a function performs tasks or computations and then returns the result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Be
3 min read
JS Array
JavaScript ArraysIn JavaScript, an array is an ordered list of values. Each value, known as an element, is assigned a numeric position in the array called its index. The indexing starts at 0, so the first element is at position 0, the second at position 1, and so on. Arrays can hold any type of dataâsuch as numbers,
7 min read
JavaScript Array MethodsTo help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.Javascript Arrays Methods1. JavaScript Array length The length property of an array returns the number of elements i
7 min read
Best-Known JavaScript Array MethodsAn array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements.There are some Basic JavaS
6 min read
Important Array Methods of JavaScriptJavaScript arrays are powerful tools for managing collections of data. They come with a wide range of built-in methods that allow developers to manipulate, transform, and interact with array elements.Some of the most important array methods in JavaScript areTable of Content1. JavaScript push() Metho
7 min read
JavaScript Array ReferenceJavaScript Array is used to store multiple elements in a single variable. It can hold various data types, including numbers, strings, objects, and even other arrays. It is often used when we want to store a list of elements and access them by a single variable.Syntax:const arr = ["Item1", "Item2", "
4 min read