You can do it directly after the variables are declared and initialized, or after the function declaration. I will try to give you a brief simplified explanation.
The javascript engine runs your code in two phases. The creation and the execution phase.
In the creation phase it will search for all declarations, and set those in memory. For variable declarations it will store the variable, but set the initial value to undefined
. For function declarations it will store the function and all its code into memory. This is why a function declaration can be called before it is declared in the code.
In the execution phase it will start to run your code line by line. When it comes across a line that sets a value to variable, it will replace the default undefined
value with the value that is on the right side of the assignment operator =
.
I am not sure where you are in learning JavaScript, but you can create functions in various ways, typically as function declarations, function expressions, anonymous function, and arrow functions (which are a variant of anonymous).
Side note: Function declarations are hoisted while all others are not.
The examples below are both valid.
let address1 = new Address('Beach Resort str', 'Phuket', 254520);
let address2 = new Address('Beach Resort str', 'Phuket', 254520);
let isSame = areSame(address1, address2);
function areSame(address1, address2) {
return address1 === address2;
}
let address1 = new Address('Beach Resort str', 'Phuket', 254520);
let address2 = new Address('Beach Resort str', 'Phuket', 254520);
function areSame(address1, address2) {
return address1 === address2;
}
let isSame = areSame(address1, address2);