Skip to content

Instantly share code, notes, and snippets.

View Chalarangelo's full-sized avatar
💻
JavaScripting

Angelos Chalaris Chalarangelo

💻
JavaScripting
View GitHub Profile
// An array of objects.
var myFriends = [
{ name: "John", surname: "Smith", age: 52},
{ name: "Sarah", surname: "Smith", age: 49},
{ name: "Michael", surname: "Jones", age: 46},
{ name: "Garry", surname: "Thomas", age: 48}
];
// A simple function to get just the name and
// surname in one string.
// An array of high scores. Notice that some
// of them don't have a name specified.
var highScores = [
{score: 237, name: "Jim"},
{score: 108, name: "Kit"},
{score: 91, name: "Rob"},
{score: 0},
{score: 0}
];
// An array of people.
var myFriends = [
{ name: "John", gender: "male" },
{ name: "Kate", gender: "female" },
{ name: "Mike", gender: "male" },
{ name: "Sophie", gender: "female" },
{ name: "Richard", gender: "male" },
{ name: "Keith", gender: "male" }
];
// Definition of our comparison function.
var sortByWeight = function(x,y){
var xW = x.measurement == "kg" ? x.weight : x.weight * 0.453592;
var yW = y.measurement == "kg" ? y.weight : y.weight * 0.453592;
return xW > yW ? 1 : -1;
}
// Just two slightly different lists of data,
// that need to be sorted based on weight.
var firstList = [
// Create a function.
function f(x){
return x * x;
}
// Use the function.
f(5); // 25
// Create an anonymous function and assign
// it to a variable.
var g = function(x){
function user(username, password){
// Here we use closures to define public functions
// that can access private variables.
return {
getUsername() { return username; },
setUsername(newUsername) {username = newUsername; },
checkPassword(givenPassword) { return password == givenPassword; }
}
}
function someFunction(){
if (true){
// This variable is defined inside these
// curly braces, which means its part of the
// scope of this block and cannot be accessed
// by other parts of someFunction.
let blockVariable = 30;
// However, using the 'var' keyword this variable,
// while defined inside the same block, is part of
// This is a function and it defines its own
// local scope. argumentVariable is part of the
// function's scope, as it is an argument in its
// definition.
function parentFunction(argumentVariable){
// functionVariable and anotherVariable are both
// part of parentFunction's local scope.
var functionVariable = 10;
let anotherVariable = 15;
// This variable is part of the global scope
var globalVariable = 10;
function someFunction(){
// globalVariable is accessible from someFunction,
// as it is part of the global scope
console.log(globalVariable);
}
someFunction(); // Prints 10
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function() { console.log('Registered service worker!'); });
}