Skip to content

Instantly share code, notes, and snippets.

@anharathoi
Last active May 14, 2019 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anharathoi/3212c1f422107fe9632c025b6ba538d6 to your computer and use it in GitHub Desktop.
Save anharathoi/3212c1f422107fe9632c025b6ba538d6 to your computer and use it in GitHub Desktop.
Introduction to JavaScript

1. What is JavaScript?

  • JavaScript is a programming language to make web pages interactive.

    • HTML contains the structure of a page
    • CSS determines the styling of that page
    • JavaScript determines the interactive elements of that page
  • JavaScript is a client-side scripting language. It used to be considered front-end only, but now it's also a server-side language because of NodeJS.

  • JavaScript conforms to ECMAScript specifications.

  • ECMAScript 5 is fully supported in all modern browsers.

  • Since the release of ES2015(a.k.a ES6), transpiling JavaScript has become very common.

  • Babel is the most widely used transpiler that is used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

  • JavaScript Frameworks: Angular, React, VueJS, ElectroJS, NodeJS etc.

2. Installing Node

  • Node.js makes it possible for you to run JavaScript programs outside of a web browser or on a server. To run a Node.js application on MacOS, install node on your machine:

    MacOS

    brew install node
    

    Windows

    Download NodeJS from here: https://nodejs.org/en/download/

3. JavaScript basics and differences with Ruby

Data types

Ruby JavaScript
Boolean Boolean
Nil Null
- Undefined
Integer Number
Float -
String String
Symbol Symbol (ES6)

Variable declaration and assignment

Ruby

country = "Australia"
city = "Melbourne"
population = 4_443_000_000

# Printing to screen
puts population
p city
print country

JavaScript

var outDated = "This is barely used anymore" // global variable, function scoped

const country = "Australia" // constant variable and block scoped
const city = "Melbourne"
let population = 4443000000 // block scoped

let undefinedVariable

// Printing to screen
console.log(undefinedVariable)
console.log(population)

String Interpolation

Ruby

puts "The population of #{city} is #{population}"

JavaScript

console.log(`The population of ${city} is ${population}`)

Data Structures

Ruby

# Array
cities = ["Melbourne", "Sydney", "Brisbane", "Canberra", "Perth", "Hobart"]

# accessing data in array
puts cities[0]

# Hash
melbourne = {
  name: "Melbourne",
  population: 4443000000,
}

# accessing data in hash
melbourne_population = melbourne[:population]
puts melbourne_population

JavaScript

// Array
let cities = ["Melbourne", "Sydney", "Brisbane", "Canberra", "Perth", "Hobart"]

// accessing data in array
console.log(cities[0])

// Object
const melbourne = {
  name: "Melbourne",
  population: 4443000000,
}

// accessing data in object
let melbPopulation = melbourne.population // will return  4443000000
const melbName = melbourne["name"] // will return "Melbourne"

Control Structures

Ruby - If statement

x = 1
if x > 2
   puts "x is greater than 2"
elsif x <= 2 and x!=0
   puts "x is 1"
else
   puts "I can't guess the number"
end

JavaScript - If statement

// declaring the variables
let time = 15, greeting;

if (time < 10) {
  greeting = "Good morning"; // changing the value
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

Ruby - While loop

i = 0
while i < 5 do
  puts "Hello from ruby while loop"
  i += 1
end

JavaScript - While loop

let i = 0
while( i < 5 ) {
  console.log("Hello from js while loop")
  i++
}

Other control structures in JS:

  • switch statement (similar to case statement in Ruby)
    let fruit = "Banana"
    
    switch(fruit) {
      case "Banana":
        text = "Banana is good!";
        console.log(text)
        break;
      case "Orange":
        text = "I am not a fan of orange.";
        console.log(text)
        break;
      case "Apple":
        text = "How you like them apples?";
        console.log(text)
        break;
      default:
        text = "I have never heard of that fruit...";
        console.log(text)
    }
  • for loop
    const fruits = ["apple", "kiwi", "banana", "orange"]
    
    for(let i = 0; i < fruits.length; i++){
      console.log(fruits[i].toUpperCase())
    }
  • for .. in (useful for iterating through objects)
    let forrestGump = {
      movieid: 356,
      title: "Forrest Gump (1994)",
      number_of_times_rated: 341
    }
    
    for ( let key in forrestGump){
      console.log(`${key}: ${forrestGump[key]}`)
    }
    This is similar to .each method in Ruby hashes
    forrestGump.each do |k, v|
      puts "#{key}: #{value}"
    end

    Click here for more on JavaScript loops


Functions

Ruby

def add(a,b)
  return a + b
end

def say_hello
  puts "Hello from say_hello"
end

# calling a method
say_hello
result = add(5,7) # saving result of add to a variable

# printing the result
puts(result)

Javascript

function add(a,b) {
  return a + b // you have to explicitly return
}

function sayHello() {
  console.log("Hello from sayHello")
}

// calling a function
sayHello()
let result = add(5,6) // saving result of add to a variable

// printing the result
console.log(result)

// ES 6 way of writing the same method ARROW FUNCTIONS
let add = (a,b) => {
  return a + b
}

let res = add(25,6)
console.log(res)

Storing functions in objects

  • Unlike Ruby, you can store functions in objects
     let theShawshank = {
      movieid: 318,
      title: "Shawshank Redemption, The (1994)",
      numberOfTimesRated: 311,
      rate: function(){
        this.numberOfTimesRated ++
      }
    }
    
    theShawshank.rate()
    theShawshank.rate()
    theShawshank.rate()
    
    console.log(theShawshank.numberOfTimesRated) // will return 314
    
    // this ES6 way will work too
    let theShawshank = {
      movieid: 318,
      title: "Shawshank Redemption, The (1994)",
      numberOfTimesRated: 311,
      rate() {
        return this.numberOfTimesRated ++
      }
    }

Classes

Ruby

class Dog
  attr_accessor :name
  def initialize(name)
    @name = name
  end
  def speak
    puts "#{@name} says woof!"
  end
end

# Create a new dog named Rover. Assign him to a rover variable.
rover = Dog.new('Rover')

# Ask Rover to speak

rover.speak # -> "Rover says woof!"

# Change Rover's name to Rover The Great
rover.name = 'Rover The Great'

# Speak again
rover.speak # -> "Rover the great says woof!"

JavaScript

class Dog {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} says woof!`);
  }
}


// Create a new dog named Rover. Assign him to a rover variable
let rover = new Dog('Rover');

// Ask Rover to speak
rover.speak(); // -> "Rover says woof!"

// Change Rover's name to Rover The Great
rover.name = 'Rover The Great';

// Speak again
rover.speak(); // -> "Rover The Great says woof!"

This and Self

Ruby

  • In a class of module definition, self refers to the class or the module.
  • in an instance method, self refers to the object / instance that'll access the method.
    class Cat
      attr_accessor :name
      def initialize(name)
        @name = name
      end
    
      def self.class_method
        puts "Hello from the Class"
      end
    
      def instance_method
        puts "I am #{self.name}"
      end
    
    end
    
    kitty = Cat.new("Kitty")
    
    Cat.class_method # will run the class_method
    
    kitty.instance_method # Will run the instance method where self refers to the "kitty" object itself

Javascript

  • The JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used:

    • In a method, this refers to the owner object.
    • Alone, this refers to the global object.
    • In a function, this refers to the global object.
    • In a function, in strict mode, this is undefined.
      // Whole-script strict mode syntax
        'use strict';
        
        var v = "Hi! I'm a strict mode script!";
    • In an event, this refers to the element that received the event.
  • https://www.w3schools.com/js/js_this.asp

    let kitty = {
      name: "Kitty",
      age: 2,
      printName(){
        console.log(this.name)
      }
    }
    
    kitty.printName() // this will print "kitty"

Challenges

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment