Skip to content

Instantly share code, notes, and snippets.

@geocodinglife
Forked from wearethefoos/syntax.md
Created September 10, 2017 04:22
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 geocodinglife/f76b4bd23ff1c901a38f8ec22bd477bd to your computer and use it in GitHub Desktop.
Save geocodinglife/f76b4bd23ff1c901a38f8ec22bd477bd to your computer and use it in GitHub Desktop.
Ruby vs JS vs ES6

Variables

Ruby

Name a value.

color = "red"

JavaScript

Declare a variable (var) before you can assign it a value.

var color = 'red';

// or

var color;
color = 'red';

ES6

Apart from declaring global variables with var, you can declare local variables with let, and constants (variables that do not change after they were assigned) with const.

let color
color = 'red'
color = 'blue'

const red = 'red'
red = 'blue' # error

Functions

Ruby

def say(sentence)
  puts sentence
end

say "Hello"
#=> "Hello"

JavaScript

function say(sentence) {
  console.log(sentence);
}

// or same:

var say = function(sentence) {
  console.log(sentence)
};

say("Hello");
//=> "Hello"

ES6

const say = (sentence) => {
  console.log(sentence)
}

say("Hello")
//=> "Hello"

Hashes vs Objects

Ruby Hash

player = {
  name: "Bram",
  points: 0
}

puts player[:name]
#=> "Bram"

JavaScript Object

var player = {
  name: "Bram",
  points: 0
};

console.log(player.name);
//=> "Bram"

ES6 Objects

Object destruction

const player = {
  name: "Bram",
  points: 0
}

const { name } = player

console.log(name)
//=> "Bram"

Combining vars into Objects

const name = "Bram"
const points = 0

const player = {
  name,
  points
}

console.log(player.name)
//=> "Bram"

Object assign

Object.assign can be used to extend an Object with another Object.

const score = {
  points: 0
}

let player = { name: 'Bram' } // note: const player would give an error below!

Object.assign(player, score)

console.log(player.score)
//=> 0

console.log(player.name)
//=> "Bram"

Object.assign can be used to create new Objects from 2 or more other Objects, if we pass in a new, empty object as the first value ({}).

const score = {
  points: 0
}

const player = { name: 'Bram' } // here const will not give an error, because we're not mutating below!

newPlayer = Object.assign({}, score, player)

console.log(newPlayer.score)
//=> 0

console.log(newPlayer.name)
//=> "Bram"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment