JavaScript Top Questions that every Developer should know
1. What is the use of isNaN function?
isNan function returns true if the argument is not a number; otherwise, it is false..
// Example 1: Checking a string that's not a number console.log(isNaN("John Bear")); // Output: true // Example 2: Checking a string representing a valid number console.log(isNaN("123")); // Output: false // Example 3: Checking a real NaN value console.log(isNaN(NaN)); // Output: true // Example 4: Checking an actual number console.log(isNaN(42)); // Output: false // Example 5: Checking an object (which is not a number) console.log(isNaN({})); // Output: true // Example 6: Checking undefined console.log(isNaN(undefined)); // Output: true // Example 7: Checking null console.log(isNaN(null)); // Output: false
2. What are JavaScript Data Types?
- Number
- String
- Boolean
- Object
- Undefined
// Integer let age = 30; console.log(age); // Output: 30 // Floating-point let height = 5.8; console.log(height); // Output: 5.8
//String: A sequence of characters written in single or double quotes. let greeting = "Hello, world!"; console.log(greeting); // Output: Hello, world! let name = 'Alice'; console.log(name); // Output: Alice
//Boolean: Represents logical values, either true or false let isLoggedIn = true; console.log(isLoggedIn); // Output: true let hasAccess = false; console.log(hasAccess); // Output: false
//Object: Collections of key-value pairs, allowing structured data. // Creating a simple object let person = { name: "John Doe", age: 25, isStudent: true }; console.log(person); // Output: { name: 'John Doe', age: 25, isStudent: true } // Accessing object properties console.log(person.name); // Output: John Doe console.log(person.age); // Output: 25
//Undefined: A variable that hasn't been assigned a value is of the undefined type. let result; // Variable declared but not initialized console.log(result); // Output: undefined // When a variable is not explicitly assigned, its type is 'undefined' let car = {}; console.log(car.model); // Output: undefined
3. Can you break JavaScript Code into several lines ?
Try this Code
document. Write ("This is my first\JS Code \and am Loving it");
4.Wrie a Code to Dynamically add an element into a JS program
Try this Code
//HTML Code const parentDiv = document.getElementById('parent-div'); // Create a new paragraph element const newParagraph = document.createElement('p');
//JS Code // Select the parent element where the new element will be added const parentDiv = document.getElementById('parent-div'); // Create a new paragraph element const newParagraph = document.createElement('p'); // Add some text content to the new paragraph newParagraph.textContent = 'This is a dynamically added paragraph.'; // Append the new paragraph to the parent div parentDiv.appendChild(newParagraph);
5.Can you tell us about undefined and undeclared variables?
Undefined Variables: When a variable is declared but not initialized with a value, its initial value is undefined.Example 1 given below
Undeclared Variables: A variable that has not been declared using let, var, or const is referred to as "undeclared." Accessing an undeclared variable will result in a ReferenceError.Example 2 given below
// Example 1 // Declare a variable without initializing it let declaredButUndefined; console.log(declaredButUndefined); // Output: "undefined" // Variable declared and later assigned a value var initializedLater; initializedLater = 10; console.log(initializedLater); // Output: 10 // A function returning undefined function noReturnValue() {} console.log(noReturnValue()); // Output: "undefined"
//Example 2 try { // Attempt to log an undeclared variable console.log(nonExistentVariable); } catch (error) { console.log(error.message); // Output: "nonExistentVariable is not defined" }
6.What do you know about Global variables in JS ?
Understanding Global Variables
Global variables are variables that can be accessed from any part of the program once declared. They have a global scope and are attached to the global object, which is window in browsers and global in Node.js. In the browser environment, these variables can be accessed using window.variableName.
Declaring Global Variables
Global variables are declared:
- Implicitly (Discouraged): When a variable is used without first being declared with var, let, or const. This can lead to unintended side effects.
- Explicitly: Declared with var outside any function.
- Best Practice It is generally recommended to minimize the use of global variables to avoid conflicts and unintended behavior, as they can be modified by any part of the code. Where possible, limit the scope of variables to blocks or functions.
//Example 1: // No declaration keyword used, becomes global implicitly function implicitGlobalExample() { implicitGlobalVar = "I'm global!"; // Implicit global } implicitGlobalExample(); console.log(implicitGlobalVar); // Output: "I'm global!"
//Example 2: // Declared with `var` outside any function, explicitly global var explicitGlobalVar = "I'm global too!"; function logGlobalVar() { console.log(explicitGlobalVar); // Accessing global variable inside a function } logGlobalVar(); // Output: "I'm global too!" console.log(window.explicitGlobalVar); // Output: "I'm global too!"
7.Do you know how to create a Prompt box ?
What Is a Prompt Box?
A prompt box is a dialog box provided by the browser that allows the user to input text. It's part of the JavaScript window object and is useful for taking simple input from users directly on the page. It returns the user's input as a string or null if the prompt is canceled.
How to Create a Prompt Box
You can create a prompt box using JavaScript's prompt() function. Here's a code example that demonstrates its use:
- Note: Prompt boxes can be useful but are generally considered intrusive since they interrupt the user's experience. For better UX, consider using custom modal dialogs instead.
// Display a prompt box asking for the user's name let userName = prompt("Please enter your name:", "Guest"); // Check if the user clicked "Cancel" (returns null) if (userName !== null) { // Display a welcome message using the user's input console.log(`Hello, ${userName}! Welcome to our site.`); } else { // Handle the case where the user canceled the prompt console.log("No name entered. Welcome, Guest!"); }
8. Do you know the What is the === operator ?
Understanding the === Operator in JavaScript
The === operator, often called the "strict equality" or "triple equals" operator, is used to compare two values for equality while ensuring that both the value and the type are the same.
This is in contrast to the == (double equals) operator, which checks for value equality after performing type coercion.
Key Differences between === and ==:Strict Equality (===): Checks both the type and value.
Loose Equality (==): Converts data types to the same type before comparing the values.
//Try this code
// Example 1: Using `===` (Strict Equality)
let num = 5; let str = "5"; // Strict equality - false, because `num` is a number and `str` is a string console.log(num === str); // Output: false // Strict equality - true, because both are numbers console.log(num === 5); // Output: true // Example 2: Using `==` (Loose Equality) let boolTrue = true; let numOne = 1; // Loose equality - true, because `true` is coerced to 1 console.log(boolTrue == numOne); // Output: true // Loose equality - true, because string "5" is coerced to the number 5 console.log(num == str); // Output: true // Example 3: Comparing objects with `===` let obj1 = {}; let obj2 = {}; // Even though they appear similar, different objects have different references console.log(obj1 === obj2); // Output: false // Identical references - pointing to the same object let obj3 = obj1; console.log(obj1 === obj3); // Output: true
9. Iterate Over an Array
We use the forEach
method to iterate over each element in the fruits
array, logging both the index and the element.
fruits.forEach(function(item, index) { console.log(index, item); });
10. Filter an Array
This program demonstrates filtering the fruits
array to find elements that start with the letter 'B', and logs the result.
const result = fruits.filter(fruit => fruit.startsWith('B')); console.log(result);
11. Merging Two Arrays without Duplicates
This example demonstrates how to combine two arrays into one, ensuring there are no duplicate values in the merged result. The Set object is used for its property of storing unique values, and the spread operator ... is employed to expand both arrays within a new array, which is then converted into a Set to remove duplicates, and back into an array.
const array1 = [1, 2, 3]; const array2 = [2, 3, 4]; const mergedArray = [...new Set([...array1, ...array2])]; console.log(mergedArray);
12. Finding the Intersection of Two Arrays
This code finds the common elements between two arrays, effectively calculating their intersection. The filter() method is used to create a new array containing only the items that exist in both original arrays, determined by the includes() method.
const firstArray = [1, 2, 3, 4]; const secondArray = [2, 4, 6, 8]; const intersection = firstArray.filter(value => secondArray.includes(value)); console.log(intersection); // Output: [2, 4]
13.Removing Falsy Values from an Array
This example filters out all falsy values (e.g., false, null, 0, "", undefined, and NaN) from an array. By passing the Boolean constructor function to the filter() method, it automatically removes all values that are considered falsy in JavaScript, leaving only truthy values.
const mixedArray = [0, "text", false, 4, "", null, undefined, "0"]; const truthyArray = mixedArray.filter(Boolean); console.log(truthyArray); // Output: ["text", 4, "0"]
14.Flattening an Array of Arrays
The flat() method is used to flatten nested arrays into a single array. By specifying the depth level (in this case, 2), it controls how many levels of nesting will be flattened, accommodating arrays with varying degrees of depth.
const nestedArray = [1, [2, 3], [4, [5, 6]]]; const flatArray = nestedArray.flat(2); // Level of depth is 2 console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]
15. Grouping Objects by a Property
This technique uses the reduce() method to organize an array of objects into a structure grouped by a specific property, in this case, name. The accumulator (acc) starts as an empty object, and objects are added into arrays under keys that match their name property, creating a map-like structure.
const people = [ { name: "John", age: 25 }, { name: "Anna", age: 30 }, { name: "John", age: 28 }, ]; const groupedByNames = people.reduce((acc, current) => { (acc[current.name] = acc[current.name] || []).push(current); return acc; }, {}); console.log(groupedByNames);
16. Grouping Objects by a Property
To create a deep copy of an array that includes nested arrays or objects, JSON.stringify() is used to convert the array to a JSON string, and then JSON.parse() is used to parse that string back into a new array. This ensures that changes to the nested elements of the copied array do not affect the original array.
const original = [[1], [2], [3]]; const deepCopy = JSON.parse(JSON.stringify(original)); original[0].push(2); console.log(original); // Output: [[1, 2], [2], [3]] console.log(deepCopy); // Output: [[1], [2], [3]]
17.Sorting an Array of Objects by Property
This example sorts an array of objects based on a numeric property (price) using the sort() method. The callback function provided to sort() dictates the sorting logic, comparing the price property of each object to determine their order.
const items = [ { name: "Banana", price: 1 }, { name: "Apple", price: 2 }, { name: "Orange", price: 1.5 }, ]; items.sort((a, b) => a.price - b.price); console.log(items);
18.Finding the Difference Between Two Arrays
This code snippet finds elements that are in the first array but not in the second, effectively calculating the difference between the two arrays. The filter() method is used with a condition that filters out any elements present in the second array.
const arr1 = [1, 2, 3, 4, 5]; const arr2 = [4, 5, 6, 7]; const difference = arr1.filter(x => !arr2.includes(x)); console.log(difference); // Output: [1, 2, 3]
19. Converting an Array of Objects into a Map
This demonstrates how to transform an array of objects into a Map, where each entry's key is an object's id and the value is the object itself. The Map object provides an efficient way to store key-value pairs and can be more performant for certain operations than an object.
const products = [ { id: 1, name: "Pencil", price: 1.50 }, { id: 2, name: "Notebook", price: 2.50 } ]; const productMap = new Map(products.map(product => [product.id, product])); console.log(productMap);
20.Chunking an Array into Smaller Arrays of a Specific Length
This function splits a large array into smaller "chunks" or sub-arrays of a specified size. It's useful for processing or displaying large datasets in smaller, more manageable pieces. The loop iterates over the original array, slicing it into arrays of chunkSize and pushing these to the chunks array.
const createChunks = (array, chunkSize) => { const chunks = []; for (let i = 0; i < array.length; i += chunkSize) { chunks.push(array.slice(i, i + chunkSize)); } return chunks; }; const data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const chunkedData = createChunks(data, 3); console.log(chunkedData); // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
21. Find the result when this operation takes place
When the code below is executed, 120 will be added to 30, giving 150, this 150 will then be concatenated with 100, giving the result to be as 150100
var num1 = 120; var num2 = 30; var num3 = num1 + num2+ "100"; console.log(num3);
22.What is NULL in JavaScript
Definition: NULL in JavaScript is a primitive value that represents the intentional absence of any object value. It is one of JavaScript's falsy values, often used to signify 'no value' or 'nothing' specifically in the context of expected object references.
//Example let user = null; if (user === null) { console.log("No user data available."); } //In this example, user is explicitly set to null to indicate that there is no user data available at this point in the script.
23.What is DELETE Operator
Definition: The DELETE operator in JavaScript is used to remove a property from an object. It deletes both the value of the property and the property itself. After deletion, the object will no longer contain the deleted property.
//Example let userInfo = { name: "John Doe", age: 30 }; delete userInfo.age; console.log(userInfo); // Output: { name: "John Doe" } //Here, the delete operator removes the age property from the userInfo object. When we log userInfo, the age property is no longer part of the object.
24.Explain Pop-up Box in JavaScript-Alert
Definition:JavaScript supports three main types of pop-up boxes: Alert, Confirm, and Prompt, which can be used to interact with users. Alert Box: An alert box is used to ensure that information gets through to the user. When an alert box pops up, the user must click "OK" to proceed.
//Example alert("Welcome to our website!"); //This alert simply informs the user with a message and an OK button.
25.Explain the Pop-up Box in JavaScript-Confirm
Definition:Confirm Box: A confirm box is used to accept or verify something with the user. It provides an option to either agree (OK) or disagree (Cancel). It returns a boolean; true if the user clicks OK and false if the user clicks Cancel.
//Example if (confirm("Are you sure you want to delete your profile?")) { console.log("Profile deleted."); } else { console.log("Delete canceled."); } //This confirm box asks users if they are sure about deleting their profile, handling the response accordingly..
26.Explain the Pop-up Box in JavaScript-Prompt
Definition:Prompt Box: A prompt box is used to allow the user to input a value before entering a page. It provides a text box for the user input and returns the input value if the user clicks OK and null if the user clicks Cancel.
//Example let userAge = prompt("Please enter your age:", "18"); if (userAge) { console.log("User age is: " + userAge); } else { console.log("User did not enter age."); } //This prompt box requests the user's age and provides a default value (18). The script then handles the response based on whether the user provides their age or not.
27.Explain the Use of void(0)
Definition: The void operator in JavaScript evaluates the expression you pass to it and then returns undefined. The void(0) is a common usage which effectively does nothing but return undefined, ensuring no side effects from the operation. Use Case: void(0) is often used in HTML hyperlink href attributes to prevent the link from doing anything when clicked, other than executing any JavaScript in the onclick handler. It's a way to ensure that the browser doesn't try to navigate away from the current page or reload it.
//Example Click Me! //In this example, clicking the "Click Me!" link will log a message to the console but will not cause the browser to navigate to a different URL or reload the page.
28.How do you Force a Page to Load Another Page
Definition:You can force a web page to redirect to another page using JavaScript by changing the location.href property.
//Example function redirectToHomePage() { location.href = 'https://www.example.com'; } //In this script, calling the redirectToHomePage() function will change the current window's location to 'https://www.example.com', thereby navigating to that URL.
29.Can you define the Data Types of Variables in JavaScript
Definition:YavaScript is a loosely typed or a dynamic language, meaning you don't need to declare the type of a variable ahead of time. JavaScript automatically determines variable types at runtime. The main data types are:
Primitive Types:- String: Represents textual data.
- Number: Represents both integer and floating-point numbers.
- BigInt: Represents integers with arbitrary precision.
- Boolean: Represents a logical entity that can be either true or false.
- Undefined: A variable declared but not assigned a value is of type undefined.
- Null: A special keyword denoting a null value.
- Symbol: A unique and immutable primitive introduced in ES6.
- Object: Represents instances of objects which can be a collection of properties.
- Array: A global object used to construct arrays; high-level, list-like objects.
//try these Examples: let name = "John"; // String let age = 30; // Number let isVerified = false; // Boolean let bigNumber = 1234567890123456789012345678901234567890n; // BigInt let user = { firstName: "Jane", lastName: "Doe" }; // Object let scores = [90, 85, 88, 92]; // Array let uniqueID = Symbol('id'); // Symbol let somethingUndefined; // Undefined let action = null; // Null console.log(typeof name); // "string" console.log(typeof age); // "number" console.log(typeof isVerified); // "boolean" console.log(typeof bigNumber); // "bigint" console.log(typeof user); // "object" console.log(typeof scores); // "object" because Arrays in JavaScript are objects console.log(typeof uniqueID); // "symbol" console.log(typeof somethingUndefined); // "undefined" console.log(typeof action); // "null" but `typeof` incorrectly returns "object"
30.Can you state the Difference Between an Alert Box and a Confirmation Box
Definition: Alert Box:
- An alert box is used to display a message to the user and requires the user to click "OK" to proceed.
- It is generally used for informational purposes to make sure the user reads some important information.
- Syntax: alert(message);
Confirmation Box:
- A confirmation box is used to accept or confirm a user's response from two options, typically "OK" and "Cancel".
- It returns a boolean value: true if the user clicks "OK" and false if the user clicks "Cancel".
- used when the user's confirmation is required before taking an action.
- Syntax: confirm(message);
//Example // Alert box example alert("Welcome to our website!"); // Confirmation box example if (confirm("Do you want to continue?")) { console.log("User clicked OK."); } else { console.log("User clicked Cancel."); }
31. What are Escape Characters
Definition:Escape characters in JavaScript are special characters that perform special actions in text, such as new lines, tabs, quotes, etc. They are prefixed with a backslash (\).
Common Escape Characters:
- \n - New line
- \t - Tab
- \\ - Backslash
- \' - Single quote
- \" - Double quote
//Example let message = "Hello, she said \"Welcome to JavaScript programming!\"\nLet's learn about escape characters."; console.log(message); //This example demonstrates using escape characters to include quotes in a string and to insert a new line.
31.Can you tell us about JavaScript Cookies
Definition:Cookies are data, stored in small text files, on the client's computer. In JavaScript, cookies are used to store data that needs to persist between web sessions.
Common Uses: Storing session information, user preferences, and other data that needs to be maintained even when the browser is closed and reopened.
//Example // Set a cookie document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/"; // Get a cookie function getCookie(name) { let cookies = document.cookie.split('; '); for (let i = 0; i < cookies.length; i++) { let cookiePair = cookies[i].split('='); if (cookiePair[0] === name) { return cookiePair[1]; } } return null; } console.log(getCookie("username")); //This example shows how to set and get a cookie storing a username.