10 JavaScript Questions With Solutions
10 JavaScript Questions With Solutions
Code example:
document.addEventListener('click', function(event) {
if (event.target.matches('.btn')) {
// Handle button click event
}
});
Code example:
function exampleFunction() {
var x = 1;
if (true) {
let y = 2;
const z = [3];
z.push(4);
console.log(z); // Output: [3, 4]
}
console.log(x); // Output: 1
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined
}
exampleFunction();
Code example:
let person = {
name: 'John',
age: 30,
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
}
}
person.sayHello(); // Output: Hello, my name is John
Code example:
let x;
console.log(x); // Output: undefined
let y = null;
console.log(y); // Output: null
Code example:
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
let counter = outer();
counter(); // Output: 1
counter(); // Output: 2
Code example:
function doSomething(callback) {
// Perform some operation
callback();
}
function doSomethingElse() {
console.log('Done!');
}
doSomething(doSomethingElse);
Code example:
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
Code example:
Code example:
function double(arr) {
return arr.map(function(x) {
return x * 2;
});
}
call and apply are similar, but apply takes an array of arguments,
while call takes arguments directly. bind returns a new function
with a bound this value and arguments, but does not immediately
call the function.
Code example:
const person = {
name: 'John',
sayHi: function(greeting) {
console.log(`${greeting}, my name is
${this.name}`);
}
}
const person2 = {
name: 'Jane'
}