JavaScript Interview: A Beginner's Guide - Part 1
"Mastering JavaScript Interview Questions with Handy Cheatsheet - Get Ready to Shine!"
Table of contents
- 💡Q 1. What is Primitive data type in JS?
- 💡Q 2. What is Non-primitive data type in JS?
- 💡Q 3. What is difference between null and undefined data types?
- 💡Q 4.What's the main difference between
- \== and ===?"
- 💡Q 5. Explain the implicit type coercion in javascript.
- 💡Q 6. What is a NaN property in JS?
- 💡Q 7. Explain pass by value and pass by reference in JavaScript.
- 💡Q 8. What is function?
- 💡Q 9. What is HOF?
- 💡Q 10. What is IIFE?
JavaScript is an interesting language to learn but when it comes to an interview lot of the time we do not know how the internal workings of JavaScript code. This is the reason we fail in the interviews. In this article, we will be discussing some of the asked interview questions and trying to answer them.
💡Q 1. What is Primitive data type in JS?
Ans:-Primitive data types are used in various ways in JavaScript. We use them to store and manipulate information.They are the simplest and most fundamental types of data that you can work with. These data types represent individual values and have specific characteristics. There are a few main primitive data types in JavaScript.
Number: This represents both integer and floating-point numbers. For example:
5, 3.14.
String: This represents a sequence of characters, like text. For example:
'Hello, World!'
,'JavaScript is fun'
.Boolean: This represents a logical value – either
true
orfalse
. For example:true
,false
.Undefined: This represents a variable that has been declared but hasn't been assigned a value yet. For example:
let age;
(here,age
isundefined
).Null: This represents an intentional absence of value. It's often used to indicate that a variable doesn't have a value. For example:
let user = null;
.Symbol: This represents a unique and immutable value, often used as object property keys. Symbols are less commonly used compared to other types.
BigInt: This is used for larger integers that can't be represented using the
Number
type. For example:10000000000000000000000000000n
.
💡Q 2. What is Non-primitive data type in JS?
Ans:-Non-primitive data types, also known as reference data types, are a bit more complex. Instead of directly containing the actual data, they store references or addresses to where the data is stored in memory. These data types are more flexible and can hold larger and more complex structures. The main non-primitive data type in JavaScript is the object.
Non-primitive (Reference) Data Types (Object):
Object
:{ name: 'John', age: 30 }
Array
:[1, 2, 3]
Function
:function greet() { console.log('Hello!'); }
Date
:new Date()
RegExp
:/pattern/
The main differences between primitive and non-primitive data types are that primitives are simple, immutable values directly containing the data, while non-primitives are more complex, store references to data, and allow for more elaborate data structures. Understanding these differences helps developers write efficient, organized, and bug-free code."
💡Q 3. What is difference between null and undefined data types?
Ans:- null and undefined both represent the absence of a value, but they do so in slightly different ways.
- undefined: Think of this as a variable that's been declared but hasn't been assigned any value yet. It's like an empty box you haven't put anything in yet. For instance, if you declare a variable name but don't give it a value, its value will be undefined.
let name; // This variable is undefined because we haven't assigned a value.
console.log(name); // Output: undefined
- null: This is more like you deliberately put an empty box there. It's an intentional absence of value. It's like saying, 'Hey, there's nothing in here on purpose.' So, if you set a variable score to null, you're saying that the score is intentionally not available right now.
let score = null; // We intentionally set the score to null.
console.log(score); // Output: null
undefined
means something hasn't been assigned a value yet, whilenull
means intentionally no value is assigned.They're both used to represent absence of value, but
undefined
often shows up automatically, andnull
is usually set by a programmer.
💡Q 4.What's the main difference between
\== and ===?"
Ans:- "The main difference is in how they handle data types during comparison:
\== (Equality Operator): This checks if the values on both sides are equal, but it does type coercion. It means if the data types are different, JavaScript will try to convert one or both values so they can be compared.
\=== (Strict Equality Operator): This checks if the values on both sides are equal and also ensures that their data types are the same. It doesn't perform any type of coercion.
console.log(5 == '5'); // Output: true,
console.log(5 === '5'); // Output: false,
console.log(true == 1); // Output: true,
console.log(true === 1); // Output: false,
console.log(null == undefined); // Output: true,
console.log(null === undefined); // Output: false,
💡Q 5. Explain the implicit type coercion in javascript.
Ans:-Implicit type coercion is a concept in JavaScript where the language automatically converts one data type to another during certain operations, without you explicitly telling it to do so.
Let's consider adding a number and a string:
let number = 5;
let text = '10';
let result = number + text;
console.log(result); // Output: '510'
In this case, JavaScript implicitly converted the number 5 to a string and then concatenated it with the string '10'. This type of coercion happened automatically behind the scenes."
How can you avoid unintended type coercion:-One way is to use the strict equality operator,
===
, which not only checks for equality but also ensures that the data types match. Another approach is to explicitly convert data types using functions likeparseInt()
orparseFloat()
for numbers, orString()
for strings. This way, you have more control over the conversion process."
💡Q 6. What is a NaN property in JS?
Ans:-The term NaN stands for 'Not-a-Number,' and it's a special value in JavaScript that represents the result of an operation that can't produce a valid number.
for example:-
let result = 0 / 0;
console.log(result); // Output: NaN
let result = 'hello' * 5;
console.log(result); // Output: NaN
//Multiplying a string by a number doesn't make sense, so the result is NaN
Checking for
NaN
is a bit tricky because the usual equality operators don't work as expected. Instead, you can use the built-in functionisNaN()
:
console.log(isNaN('hello')); // Output: true console.log(isNaN(5)); // Output: false //You can use conditional statements to check if a value is NaN and handle it accordingly: let value = parseFloat(prompt('Enter a number:')); if (isNaN(value)) { console.log('That\'s not a valid number!'); } else { console.log('You entered:', value); }
💡Q 7. Explain pass by value and pass by reference in JavaScript.
Ans:-Pass by value' means that when you pass a primitive data type (like a number or string) to a function, a copy of the value is made, and the function works with that copy. Any changes you make inside the function don't affect the original value outside the function.
function modifyValue(number) {
number = number * 2;
console.log('Inside function:', number);
}
let myNumber = 5;
modifyValue(myNumber);
console.log('Outside function:', myNumber);
"'Pass by reference' refers to when you pass a non-primitive data type (like an object or array) to a function. Instead of copying the actual data, the function gets a reference or pointer to the original data. Changes made inside the function can affect the original data outside the function."
function modifyArray(arr) {
arr.push(4);
console.log('Inside function:', arr);
}
let myArray = [1, 2, 3];
modifyArray(myArray);
console.log('Outside function:', myArray);
'Pass by value' means a copy of the value is passed to the function, while 'pass by reference' means a reference to the original data is passed. With primitives, changes don't affect the original value outside the function. With non-primitives, changes can affect the original data outside the function, giving the illusion of 'pass by reference
'Strict mode' is a feature in JavaScript that helps you write safer and more reliable code by enforcing stricter rules and preventing certain pitfalls. by using 'strict mode' can catch common coding mistakes and prevent certain behaviors that might lead to bugs or unexpected behavior.
Enabling 'strict mode' is as simple as adding a special directive at the top of your script or function. You add 'use strict'; before any other code. For example:
'use strict';
// Your JavaScript code here
💡Q 8. What is function?
Ans:-In JavaScript, a function is like a block of code that you can give a name to. It's a way to group a set of instructions together so you can reuse them whenever you want.
Here's a simple example of a function that adds two numbers:
function addNumbers(a, b) {
return a + b;
}
let sum = addNumbers(5, 3);
console.log(sum); // Output: 8
In this example, the addNumbers function takes two numbers (a and b) as inputs, adds them together, and returns the sum. When you call the function with addNumbers(5, 3), it returns 8, which you store in the sum variable.
Functions are essential for a few reasons:
Modularity: They allow you to break down your code into manageable pieces, making it easier to understand and maintain.
Reusability: Once you create a function, you can use it multiple times, avoiding repetition and saving time.
Abstraction: Functions let you hide the complex details of how things work. You can use a function without needing to understand its internal logic.
Organization: Functions help organize your code into meaningful blocks, making it easier to navigate and debug.
Collaboration: In larger projects, different team members can work on different functions, making development more efficient."
💡Q 9. What is HOF?
Ans:-A Higher-Order Function is a function that either takes one or more functions as arguments, or it returns a function as its result. In simpler terms, it's a function that operates on other functions.
Let's take the map function, which is a classic example of a Higher-Order Function in JavaScript. It's used with arrays to transform each element using a given function:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
In this example, map takes a function as an argument and applies it to each element in the array."
Another common example is the filter function, which filters elements in an array based on a given condition:
javascriptCopy codeconst numbers = [10, 25, 3, 45, 8, 30];
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // Output: [10, 8, 30]
Here, filter is a Higher-Order Function that takes a filtering function as its argument."
💡Q 10. What is IIFE?
Ans:-An IIFE stands for 'Immediately Invoked Function Expression.' It's a design pattern in JavaScript where you define and execute a function all in one step."
An IIFE is typically written like this:
javascriptCopy code(function() {
// Your code here
})();
//You can pass arguments to an IIFE just like you would with any other function:
(function(name) {
console.log('Hello,', name);
})('Jack');
While the use of IIFEs has decreased with the introduction of block-scoped variables (
let
andconst
) and modules in modern JavaScript, they still have their uses. Especially in cases where you need a private scope or a one-time execution of code, IIFEs can be handy."
Thank You For Reading🤩
If you like this article, please give thumps up👍
Comment down your suggestions😃
Part-2 soon..............