xxxxxxxxxx
export default function taskBlock(trueOrFalse) {
var task = false;
var task2 = true;
if (trueOrFalse) {
var task = true;
var task2 = false;
}
return [task, task2];
}
xxxxxxxxxx
Within the function, we first declare the name
variable with the var keyword. This means that
the variable gets hoisted (memory space is set
up during the creation phase) with the default
value of undefined, until we actually get to the
line where we define the variable. We haven't defined
the variable yet on the line where we try to log the
name variable, so it still holds the value of undefined.
Variables with the let keyword (and const) are hoisted,
but unlike var, don't get initialized. They are not
accessible before the line we declare (initialize)
them. This is called the "temporal dead zone". When we
try to access the variables before they are declared,
JavaScript throws a ReferenceError.
function sayHi() {
console.log(name);
console.log(age);
var name = 'Lydia';
let age = 21;
}
sayHi();
xxxxxxxxxx
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
var hoistedVariable;
xxxxxxxxxx
/*
Hoisting in JavaScript is a behavior in which a function
or a variable can be used before declaration
*/
// using test before declaring
console.log(test); // undefined
var test;
xxxxxxxxxx
// hoisting is as if your `function fun() {}` was located here.
fun(); // works.
function fun() {}
xxxxxxxxxx
var defaultname = "John";
var name = "rayn";
function doit() {
if(!name){
var name = defaultname;
}
return name;
}
var ourname = doit();
console.log(ourname); //John
// because name inside function will have more priority over outside name variable.
// And, this inside name variable will be declared in memory as undefined due to hoisting.
xxxxxxxxxx
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
xxxxxxxxxx
// accessing class
const p = new Person(); // ReferenceError
// defining class
class Person {
constructor(name) {
this.name = name;
}
}
xxxxxxxxxx
var a = 10;
{
var a = -10;
}
let b = a;
{
let b = -20;
}
console.log(b)