Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created May 13, 2019 00:55
Show Gist options
  • Save rodloboz/7073a33f01864e27c60337ccff7a8a3d to your computer and use it in GitHub Desktop.
Save rodloboz/7073a33f01864e27c60337ccff7a8a3d to your computer and use it in GitHub Desktop.
JS 101
console.log("Hello, world!")
"Hello" // String
'Hello' // String
4 // Number
3.14 // Number
true // Boolean
console.log(typeof('Hello'));
// Base 10: 0 1 2 3 4 5 6 7 8 9
// The base argument
let number = Number.parseInt("42", 10)
console.log(number);
// Parsing a string of letters return NaN
console.log(Number.parseInt("kjhfahf"))
null // represents absence of/empty value
undefined // a variable that has been declared
// without an assigned value
let name;
console.log(name);
// Js assigns undefined to var
puts "Hello, world!"
"Hello" # String
'Hello' # String
4 # Integer
3.14 # Float
true # Boolean / TrueClass FalseClass
puts "Hello".class
puts "42".to_i
puts "hfkhfkj".to_i
nil # Nil class
# represents absence of/empty value
name = "rUi"
puts name.downcase
puts name.upcase
puts name.capitalize
// Array CRUD
// Create
let rappers = ['Jay Z'];
console.log(rappers)
// Read
console.log(rappers[0]);
// Update
rappers.push('Eminem');
rappers.push('Nas');
console.log(rappers);
rappers[1] = 'Nicky Minaj';
console.log(rappers);
// Delete
// Second argument is the number of elements
// to delete - it's optional
rappers.splice(-1, 2);
console.log(rappers);
const beatles = ['John', 'Paul', 'Ringo', 'George'];
// ES6 Syntax
beatles.forEach((beatle) => {
console.log(beatle.toUpperCase());
});
# Array CRUD
# Create
rappers = ['Jay Z']
p rappers
# Read
p rappers[0]
# Update
rappers << 'Eminem'
rappers.push('Nas')
p rappers
rappers[1] = 'Nicki Minaj'
p rappers
# Delete
rappers.delete_at(1)
p rappers
beatles = %w[John Paul Ringo George]
beatles.each do |beatle|
puts beatle.upcase
end
// Objects: Key-Value Pairs
// Naming convention: lowerCamelCase
let student = {
firstName: "John",
lastName: "Smith"
};
console.log(typeof(student));
// Read
console.log(student.firstName);
console.log(student['lastName']);
// Update
student.firstName = 'Susan';
// student.age = 24
student['age'] = 24
console.log(student);
// Delete
delete(student.age);
console.log(student);
Object.keys(student).forEach((key) => {
console.log(`The value of ${key} is ${student[key]}`);
});
# Hashes CRUD => JS Objects
# Create
# Naming convention: snake_case
# Classes in Ruby: UpperCamelCase
student = {
first_name: "John",
last_name: "Smith"
}
# Read
puts student[:first_name]
# Update
student[:first_name] = "Susan"
student[:age] = 24
puts student
# Delete
student.delete(:age)
puts student
student.each do |key, value|
puts "The value of #{key} is #{value}"
end
// Old JavaScript
// var counter;
// ES6 Syntax
let counter;
counter = 12;
// counter = counter + 1;
counter += 1;
console.log(counter);
const age = 30;
// Not possible to reassing constants
// age += 1;
const names = ['John', 'Miles'];
names.push('Maria');
console.log(names);
const name = 'Rui';
console.log(name.toLowerCase());
console.log(name.toUpperCase());
counter = 12
# counter = counter + 1
counter += 1
puts counter
firstName = 'Rui';
lastName = 'Freitas';
// Old JS
const sentence = firstName.toUpperCase() + ' ' + lastName.toUpperCase();
// ES6 Template literals
const newSentence = `${firstName.toUpperCase()} ${lastName.toUpperCase()}`;
console.log(newSentence);
first_name = "rui"
last_name = "freitas"
puts "#{first_name.upcase} #{last_name.upcase}"
const age = 17;
if (age >= 18) {
console.log('You can vote');
} else {
console.log(`You're too young, Go home!`);
}
const raining = true;
const accessory = raining ? 'umbrella' : 'sunglasses';
console.log(accessory);
// JS does type coercion
const digit = "0"
if (digit === 0) {
console.log('Zero');
} else if (digit === 1) {
console.log('One');
} else {
console.log('I don\'t know this digit, sorry!');
}
age = 17
if age >= 18
puts "You can vote"
else
puts "You're too young. Go home!"
end
raining = true
accessory = raining ? "umbrella" : "sunglasses"
puts accessory
digit = "0"
if digit == 0
puts "Zero"
elsif digit == 1
puts "One"
else
puts "I don't know this digit, sorry!"
end
// Old JS
// Js functions don't have implicit returns
function greeting(name = 'Stanger') {
return `Hello, ${name}!`;
};
console.log(greeting());
console.log(greeting('Mike'));
// ES6 Syntax
const newGreeting = (name = 'Stanger') => {
return `Hello, ${name}!`;
};
console.log(newGreeting());
console.log(newGreeting('Susan'));
// const square = (number) => {
// return number * number;
// };
const square = number => number * number;
console.log(square(2));
const capitalize = (string) => {
firstLetter = string[0].toUpperCase();
console.log('firstLetter value:', firstLetter);
restOfTheString = string.substring(1).toLowerCase();
return `${firstLetter}${restOfTheString}`;
};
console.log(capitalize('wORLd'));
# Ruby methods have implicit returns
def greeting(name = "Stranger")
"Hello, #{name}!"
end
puts greeting
puts greeting("Mike")
def myCapitalize(string)
first_letter = string[0].upcase
# Debugging...
# p first_letter
# byebug
rest_of_the_string = string[1, string.length - 1].downcase
"#{first_letter}#{rest_of_the_string}"
end
puts myCapitalize("wORLd") # => "World"

Some links to bear in mind:

JS/EcmaScript Documentation https://developer.mozilla.org/

Some everyday examples/snippets https://codetogo.io

Do not forgets:

  • Use === or !== for comparison
  • Open and close parentheses/curlyBraces/squareBrackets, or you'll miss some of them
  • Use const and let and don't use var
  • Use arrow function (() => {}) and not the old function methods (while there might be some use cases, let's stick with the arrow for now!)
  • Use Backticks (`) for interpolation with ${variable} to 'print' the variable value

Digging deeper

What exactly is node.js? https://medium.freecodecamp.org/what-exactly-is-node-js-ae36e97449f5

Differences and similarities between ull and undefined: https://codeburst.io/javascript-null-vs-undefined-20f955215a2

Parsing Integers: Base or Radix https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

https://en.wikipedia.org/wiki/Radix

https://stackoverflow.com/questions/31126364/javascript-converting-decimal-to-binary/31126398

The following examples all return NaN:

parseInt("546", 2); // Digits are not valid for binary representations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment