javascriptCopy code
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 10;
javascriptCopy code
console.log(b); // ReferenceError: Cannot access 'b' before initialization
const b = 20;
javascriptCopy code
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched after 2 seconds.');
}, 2000);
}
fetchData(data => console.log(data));
javascriptCopy code
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data fetched after 2 seconds.');
}, 2000);
});
}
fetchData().then(data => console.log(data));
javascriptCopy code
async function fetchAndDisplayData() {
const data = await fetchData();
console.log(data);
}
fetchAndDisplayData();
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data fetched after 2 seconds.');
}, 2000);
});
}
javascriptCopy code
function testVar() {
if (true) {
var x = 10;
}
console.log(x); // 10
}
testVar();
javascriptCopy code
function testLetConst() {
if (true) {
let y = 10;
const z = 20;
}
console.log(y, z); // ReferenceError: y is not defined
}
testLetConst();
javascriptCopy code
function hoistingExample() {
console.log(v); // undefined
var v = 50;
}
hoistingExample();
javascriptCopy code
function outerFunction() {
let outerVariable = 'I am outside!';
return function innerFunction() {
console.log(outerVariable);
};
}
const closureFunction = outerFunction();
closureFunction(); // 'I am outside!'
javascriptCopy code
function counter() {
let count = 0;
return function() {
return count++;
};
}
const myCounter = counter();
console.log(myCounter()); // 0
console.log(myCounter()); // 1
javascriptCopy code
function createPerson() {
let name = 'John Doe';
return {
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
}
};
}
const person = createPerson();
console.log(person.getName()); // 'John Doe'
person.setName('Jane Smith');
console.log(person.getName()); // 'Jane Smith'
javascriptCopy code
document.getElementById('myButton').addEventListener('click', (function() {
let count = 0;
return function() {
count++;
console.log(`Button clicked ${count} times.`);
};
})());