JavaScript-Interview-Coding-Examples-V6
JavaScript-Interview-Coding-Examples-V6
function example() {
if (true) {
var message = "Hello, world!";
}
console.log(message); // "Hello, world!"
}
example();
In this example, the variable message is declared
inside an if block, but it's still accessible outside
of the block because of var's function scope.
let x = 1;
x = 2; // OK
console.log(x); // 2
const y = 1;
y = 2; // Error: Assignment to constant variable.
Note that the curly braces and return keyword are optional if the
function only contains one expression. Here's a shorter version of
the same function:
In this example, 1 and "1" are not the same type (one is a
number and one is a string), but == performs type coercion and
converts the string to a number before making the comparison.
=== is the strict equality operator, which means that it does not
perform type coercion when comparing values. This means that it
will only return true if the operands are of the same type and
have the same value. For example:
When using ==, JavaScript will try to convert the operands to the
same type before doing the comparison. This can lead to some
unexpected results. For example:
On the other hand, when using ===, JavaScript does not convert
the operands to the same type. It simply checks if they are the
same type and have the same value. For example:
function outer() {
const name = "Alice";
function inner() {
console.log(name);
}
return inner;
}
const person = {
name: "Alice",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
function greet() {
console.log(`Hello, my name is ${this.name}`);
}
console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 1");
setTimeout(() => {
console.log("Line 2");
}, 1000);
console.log("Line 3");
Note that while the program is waiting for the setTimeout callback
to execute, it is still responsive to user input and other events.
This is because the callback is running in the background, and the
program can continue to execute other lines of code while it waits
for the callback to finish.
promise.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});
function doSomething(callback) {
setTimeout(() => {
callback("done");
}, 1000);
}
doSomething((result) => {
console.log(result);
});
console.log(Array.isArray(arr)); // true
console.log(Array.isArray("hello")); // false