JavaScript Code Based question for core concepts
1.
var a = 3;
var b = {
a: 9,
b: ++a
};
console.log(a + b.a + ++b.b);
Answer
18========================================================================
2.
var a = 3;
var b = {
a: 9,
b: a++
};
console.log(a + b.a + ++b.b);
Answer
17========================================================================
3.
console.log([1] + [])
Answer
1========================================================================
4.
console.log([1] + [1])
Answer
11========================================================================
5.
var a = (2, 3, 5)
console.log(a)
Answer
5========================================================================
6.
typeof(NaN)
Answer
"number"========================================================================
7.
Math.max([ 2,3,45])
Answer
NaN========================================================================
8.
function Operations(input) {
return {
sum: (...args) =>arguments[0] + input }
}
const ops = Operations(0.1)
console.log(ops.sum(1, 2,3))
Answer
0.2========================================================================
9.
function a(){
this.setTimeout(()=>console.log('test a'))
}
const b = ()=>{
this.setTimeout(()=>console.log('test b'))
}
a()
b()
Answer
test a test b========================================================================
10.
function createCounter(){
let count = 0;
function increase(){
count++;
}
let message = Count is ${count}
;
function log(){
console.log(message);
}
return [increase, log];
}
const [increase, log]= createCounter();
increase();
increase();
increase();
log();
Answer
Count is 0 => Increase() is called three times successively, incrementing the count variable each time. After the three calls to increase(), count becomes 3. However, the log() function within createCounter captures the message variable at the time of its creation, which happens before any calls to increase(). Therefore, the message variable inside log() still holds the initial value of Count is 0.========================================================================
11.
(function (a) {
return (function (b){
console.log(a);
})(1)
})(0)
Answer
0========================================================================
12
var number = 10;
var display = function(){
console.log(number);
var number = 20;
}
display()
Answer
undefined========================================================================
13.
const getUser = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: 1, username: "john_doe" });
}, 1000);
});
};
const getPosts = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(["post1", "post2", "post3"]);
}, 6500);
setTimeout(() => {
resolve({ message: "API Timeout" });
}, 2000);
});
};
const displayUserInfo = async () => {
const user = await getUser();
const posts = await getPosts();
return { user, posts };
};
displayUserInfo().then((result) => console.log(result));