Most asked code snippets in Javascript Interview
Hi awesome people, I hope you are doing fine, let's roll out code snippets
Q1. Guess the Output :
var a =1
var b =’1'console.log(a===b);
console.log(a==b);
take a breath and give a thought what would be the output, think hard before jumping into output
output:
false
true
Reason: In “===” it with compare datatype also, of LHS & RHS and whereas “==” only compare values of LHS and RHS
Q2. Guess the Output :
let’s do with object
var a= {name:”vineet”}
var b={name:”vineet”}console.log(a===b);
console.log(a==b);
take a breath and give a thought what would be the output, think hard before jumping into output
Output :
false
false
Reason: When comparing two objects, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys, and values are not checked, so the content of the object doesn’t matter, the operands both have to reference the same object to return true in comparison.
Q3. Guess the Output :
setTimeout(()=>{
console.log(“Mishra”)
},2000)console.log(“Vineet”)
take a breath and give a thought what would be the output, think hard before jumping into output
Output:
Vineet
Mishra
Reason: This happens due to the event loop of javascript, first it will handle synchronous function then after the completion it will handle asynchronous
Q4. Can you write code for this function: sum(a)(b)©….( n)(). This should return the sum of all the numbers a+b+c+..+n.;:
Solutions :
const sum =(a)=>(b)=>(c)=>(d)=>(e)=>()=>a+b+c+d+e
console.log(sum(1)(2)(3)(4)(5)())
Q5. Explain Closures with snippet?
Solutions: A closure gives you access to an outer function’s scope from an inner function
function Outer(){
function Inner(){
console.log(“hello”)
}
return Inner;}var getValue = Outer
getValue()();
Q6. Guess the output
const arr = [1,2,3,4]
arr.push(5)
take a breath and give a thought what would be the output, think hard before jumping into output
Output: [ 1, 2, 3, 4, 5 ]
Reason: The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned
Q7. Guess the output
const arr = [1,2,3,4]
arr.length =0;
console.log(arr)
take a breath and give a thought what would be the output, think hard before jumping into output
Output : []
Reason: The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned
Q8. How can you call a function as soon as it defines
Solutions:
(function hello()
{ console.log(“hello”)
})();
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as
it is defined. … It is a design pattern which is also known as a Self-Executing Anonymous Function
and contains two major parts: The first is the anonymous function with lexical scope enclosed within
the Grouping Operator ()