10 JS Coding Mistakes
10 JS Coding Mistakes
function myFunction() {
let x = 5;
console.log(x); // Output: 5
myFunction();
console.log(x); // Output: 10
Example:
function myFunction() {
if (true) {
var x = 5;
}
console.log(x); // Output: 5
}
myFunction();
console.log(x); // Output: ReferenceError: x is not
defined
function myFunction() {
if (true) {
let x = 5;
}
console.log(x); // Output: ReferenceError: x is not
defined
}
myFunction();
console.log(x); // Output: ReferenceError: x is not
defined
myFunction(function() {
console.log('Callback executed after 1 second');
});
function myFunction() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Promise resolved after 1 second');
}, 1000);
});
}
myFunction().then(function(result) {
console.log(result);
});
function myFunction() {
var x = 1; // x is declared in the function scope
if (true) {
To properly scope variables, you can use the "let" and "const"
keywords introduced in ES6.
To properly scope variables, you can use the let and const
keywords introduced in ES6. Here's an example:
function myFunction() {
let x = 1; // x is declared in the function scope
if (true) {
let x = 2; // x is now 2, but it's only in the
block scope
}
console.log(x); // Output: 1
}
myFunction();