Skip to content

Instantly share code, notes, and snippets.

View lenafaure's full-sized avatar

Lena Faure lenafaure

View GitHub Profile
@lenafaure
lenafaure / access_global_scope.js
Created April 30, 2017 08:32
Access global scope from inside a function
var greeting = "Hi there!"; // global scope
function sayHello() {
console.log(greeting);
}
sayHello(); // Prints "Hi there !"
@lenafaure
lenafaure / var_keyword.js
Created April 30, 2017 08:41
The var keyword and the scope
var myVariable = "Hi, I am a global variable";
function sayHello() {
myVariable = "Hi, I am locally produced!";
console.log(myVariable);
}
console.log(myVariable); // Prints "Hi, I am a global variable"
sayHello(); // Prints "Hi, I am locally produced!"
console.log(myVariable); // Prints "Hi, I am locally produced!"
@lenafaure
lenafaure / local_prevail.js
Created April 30, 2017 08:44
Local variable prevails
var myJob = "Developer";
function showJob() {
var myJob = "Designer";
console.log(myJob);
}
showJob(); // Prints "Designer"
@lenafaure
lenafaure / place_of_function.js
Created April 30, 2017 08:46
Place of function in the code
var myVariable = "global";
printVariable(); // Prints "local"
function printVariable() {
var myVariable = "local";
console.log(myVariable);
}
printVariable(); // Prints "local"
var customer = {
firstName: "John",
lastName: "Doe",
greetCustomer: function(){
// We use "this" instead of repeating "customer"
console.log("Hello again " + this.firstName + " " + this.lastName + "!");
}
}
customer.greetCustomer(); // Prints "Hello again John Doe!"
var customer = {
firstName: "John",
lastName: "Doe",
greetCustomer: function(){
console.log("Hello again " + this.firstName + " " + this.lastName + "!");
},
whatIsMyObject: function() {
console.log(this);
}
}
var customer = {
firstName: "John",
lastName: "Doe",
greetCustomer: function(){
console.log("Hello again " + this.firstName + " " + this.lastName + "!");
},
whatIsMyObject: function() {
console.log(this);
},
address: {
var customer = {
firstName: "John",
lastName: "Doe",
greetCustomer: function(){
console.log("Hello again " + this.firstName + " " + this.lastName + "!");
},
calculateAge: function(currentYear, birthDate){
console.log(this.firstName + " is " + (currentYear - birthDate) + " years old.");
}
}
var customer2 = {
firstName: "Jane",
lastName: "Smith"
}
customer.calculateAge.call(customer2, 2016, 1984); // Prints "Jane is 32 years old"
customer.calculateAge.apply(customer2, [2016, 1984]); // Prints "Jane is 32 years old"
var customer = {
firstName: "John",
lastName: "Doe",
greetCustomer: function(){
console.log("Hello again " + this.firstName + " " + this.lastName + "!");
},
calculateAge: function(currentYear, birthDate){
console.log(this.firstName + " is " + (currentYear - birthDate) + " years old.");
}
}