Skip to content

Instantly share code, notes, and snippets.

@smcalilly
Last active March 17, 2021 01:27
Show Gist options
  • Save smcalilly/cf95faf88bae57d8f7e7359474837d71 to your computer and use it in GitHub Desktop.
Save smcalilly/cf95faf88bae57d8f7e7359474837d71 to your computer and use it in GitHub Desktop.
javascript function and object cheatsheet

What is this?

This is Yet Another Javascript Guide: a quick guide to Javascript functions and objects. The intended audience is somebody who knows a language like Ruby or Python and has somehow avoided learning Javascript, yet found themselves working on a Javascript project. This is the Cliff's Notes for Javascript. This is for cramming, for all-nighters, for people who need to get things done.

This guide will demonstrate how to declare functions, pass arguments in functions, and use the arguments inside a function. It will also explain the basics of a Javascript object. Hopefully, this information will help to understand how destructuring works when you want to pass an object into a function. Destructuring is a common pattern in present-day Javascript projects, like React or Gatsby or ExpressJS.

Contents

Define a function that says hello

function sayHello(name) {
  return console.log(`Hello ${name}.`)
}

The function is named sayHello. It can be used like this:

sayHello('Sylvia')

That will print "Hello Sylvia." in a Javascript console. You can see the code execute by visiting this site and clicking "Run" at the top of the page. You can also open up your browser's developer tools and click console, then copy/paste the code into the console like you would a Ruby or Python console.

Javascript functions can be defined several different ways, using different syntax. Here are examples of different syntaxes which do the same thing. This is outside of this guide, but you should at least know this variety exists. (For further reading.)

breaking down sayHello: parameter and argument

The sayHello example function:

  • It has a parameter called name. The parameter can be used as a variable throughout the function.
  • "Sylvia" is passed into the function as an argument. In other words, name carries the value, or passes the message, into the function.

StackOverflow user 0x499602d2 said, "The parameters are the aliases for the values that will be passed to the function. The arguments are the actual values."

Basically, parameter == argument == variable == storing a value and reasoning about code.

A function can accept different types of arguments

For the sayHello function's argument, I'm passing a string with the text "Sylvia". But if I wanted, I could pass any sort of Javascript object or primitive, like:

some examples

string

See the string example above.

number

function sayAge(age) {
  return console.log(`My age is ${age}.`)
}

// prints "My age is 6."
sayAge(7)

Demo

array

function helloFriends(friends) {
  // loop through friends
  friends.forEach(function (friend) {
    // say hello to each friend
    return console.log(`Hello ${friend}.`)
  })
}

const myFriends = ['Sylvia', 'Okie', 'Nacho']

// prints
// Hello Sylvia.
// Hello Okie.
// Hello Nacho.
helloFriends(myFriends)

Demo

multiple arguments

Make a function that accepts multiple arguments:

function sayNameAndAge(name, age) {
  return console.log(`My name is ${name}. I am ${age} years old.`)
}

// prints "My name is Sylvia. I am 6 years old."
sayNameAndAge("Sylvia", 6)

Demo

multiple arguments with a bug

These arguments are positional, which means that flip-flopping the arguments would create a bug:

function sayNameAndAge(name, age) {
  return console.log(`My name is ${name}. I am ${age} years old.`)
}

// prints "My name is 6. I am Sylvia years old."
sayNameAndAge(6, "Sylvia")

Demo

Objects

An object is a key/value pair. The value can hold all sorts of stuff. Ruby has the hash, Python has the dictionary, and Javascript has the object. Here is a more thorough explanation.

In it's most basic form, you can create an object like this:

const kitty = {
  "name": "Sylvia",
  "age": 6
}

You can access the values in an object like this:

const kitty = {
  "name": "Sylvia",
  "age": 6
}

// prints "Sylvia"
console.log(kitty.name)

// prints 6
console.log(kitty.age)

Demo

Use an object as a function argument

Create a function that uses an object inside the function:

function sayNameAndAge(cat) {
  return console.log(`My name is ${cat.name}. I am ${cat.age} years old.`)
}

const kitty = {
  "name": "Sylvia",
  "age": 6
}

// prints "My name is Sylvia. I am 6 years old."
sayNameAndAge(kitty)

Demo

Notice how the object named kitty does not match the expected parameter cat in sayNameAndAge. You can name your object whatever you want and pass it into the function with no problems. You just need to match the object's keys whenever you're accessing them, like cat.name.

Destructuring

Destructuring is a useful way to do this, too. It looks like this:

function sayNameAndAge({ name, age }) {
  return console.log(`My name is ${name}. I am ${age} years old.`)
}

const kitty = {
  "name": "Sylvia",
  "age": 6
}

// prints "My name is Sylvia. I am 6 years old."
sayNameAndAge(kitty)

Demo

The important part is this: sayNameAndAge({ name, age }), where the brackets surround the parameters. The function essentially "unpacks" the object so that you can directly access the variables throughout the function, like this: My name is ${name}. I am ${age} years old..

destructured with a bug

The destructured parameters must match the keys that are in the object. For example:

function sayNameAndAge({ firstName, age }) {
  return console.log(`My name is ${firstName}. I am ${age} years old.`)
}

const kitty = {
  "name": "Sylvia", 
  "age": 6
}

// kitty.name does not match the parameter "firstName" so this has a bug
//
// prints "My name is undefined. I am 6 years old." :( poor kitty!
sayNameAndAge(kitty)

Demo

in the wild

Here's a real world example to see the two different ways of passing an object into a function. A React component might have a props which you use throughout your component:

function Article(props) {
  return (
    <article>
      <h1>{props.title}</h1>
      <p>{props.body}</p>
    <article>
  )
}

Or, you can destructure props so that you don't have to use the props argument in your component:

function Article({ title, body }) {
  return (
    <article>
      <h1>{title}</h1>
      <p>{body}</p>
    <article>
  )
}

Resources

@smcalilly
Copy link
Author

In the array example, is this line friends.forEach(function (friend) { creating a new function or is that referencing the function that it's enclosed in?

yeah, that's creating a new anonymous function for each object as it goes through the loop. each object will be assigned to the variable "friend" when the anonymous function executes. whenever it's done executing, that variable is basically reassigned to the next object because it's scoped within the anonymous function.

i think there could be a section on anonymous functions and callbacks

@smcalilly
Copy link
Author

are all javascript constants (const) objects? Or is it just that an object can be a constant and a constant could be an object or a primitive?

i'm not sure how a constant works in ruby. is that something that is globally scoped? a javascript const isn't global, it can be scoped within functions and objects, etc.

@smcalilly
Copy link
Author

Is an object just one single key/value pair or a "collection" of key/value pairs? Or a collection of "properties"? A property is the single key/value pair?

it can be a "collection" of key/value pairs. so, it can have objects nested within the object and nested arrays and stuff. it can also hold a function as the value in a key/value pair.

@smcalilly
Copy link
Author

Is it possible to make the repl examples interactive in this way where the reader does the typing? Clicking "Run" on your code really doesn't help me learn.

yeah, that would be a cool feature and a step up than what this guide currently is. definitely something i want to figure out.

@smcalilly
Copy link
Author

smcalilly commented Mar 17, 2021

I keep having this problem when I try to play around with getting "Undefined". I created my own repl and tried to recreate the Array example and I get undefined. Why is this happening?

that is because javascript is weird. when you declare something in the console it returns undefined. it's confused me too, but the function should be there and usable.

and re: all the repl notes, good to know. i'll give more context there. and yeah, the console in your browser is similar to the ruby console.

i added a bunch of github issues from these notes. thank you very much. feel free to add anymore issues if you think of them, in this gist's comments or in the issues: https://github.com/smcalilly/javascript-cheat-sheet/issues

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