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

@leemcalilly
Copy link

leemcalilly commented Mar 15, 2021

Objects section.

You say, "An object is a key/value pair."

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?

Coming from Ruby, it would be helpful to more clearly explain that a Javascript object is more like a Ruby hash, whereas a Ruby object is more like a Javascript prototype. Is that right?

This is nitpicky, but in your repl illustration you're using the word "cat" In the function name and the "kitty" in the constant name. "Cat" and "Kitty" are basically two words that mean the same thing, but what you're really trying to express is that the constant is a particular cat. "Kitty" doesn't really convey that so maybe the constant name should be "myFavoriteCat" or "myCat" or something like that??

@leemcalilly
Copy link

leemcalilly commented Mar 16, 2021

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?

@leemcalilly
Copy link

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?

@leemcalilly
Copy link

In this section, "Use an object as a function argument" would it be correct to call cat a "pointer"? As in it can be named anything you want because it is just pointing to the object you're passing to the function?

@leemcalilly
Copy link

In the Destructuring section, I feel like there should be a one-sentence description of what "destructuring" is before you dive directly into it.

@leemcalilly
Copy link

I like how you offer "bug" examples. Most tutorials only show you the working version, but showing common errors like this is very helpful to the learner.

@leemcalilly
Copy link

leemcalilly commented Mar 16, 2021

Destructuring in the wild section.

What the hell is a props. You just mention that React might have a props, but it doesn't look like a destructured object (inside the brackets) like the previous example. Why does React use "props". What is props?

Is props just the name of an object like cat, but just a name that React chooses to use? What is more common in React apps? To see props.name or to just destructure the object so you don't even see props. Is there any reason why I need to use props in my react app? Or could I just get the data (from a CMS graphql query for instance) and put it into an object with any name (like cat) or just skip the naming part and destructure it directly? Or is there a good reason to use props with React?

Need more clarity on the React concept of props. I do think it's good to introduce here because that is what you're gonna see a ton of when you start googling code examples, but some more explanation is needed.

@smcalilly
Copy link
Author

smcalilly commented Mar 17, 2021

Is props just the name of an object like cat, but just a name that React chooses to use?

yes

What is more common in React apps? To see props.name or to just destructure the object so you don't even see props.

I like destructuring because it's cleaner.

Is there any reason why I need to use props in my react app?

No, not if you destructure your objects correctly.

Or could I just get the data (from a CMS graphql query for instance) and put it into an object with any name (like cat) or just skip the naming part and destructure it directly? Or is there a good reason to use props with React?

Yes, this is exactly the way. I'll add this to the opinion section. I suppose that's a personal preference thing. Would be cool to somehow incorporate a poll or analysis react code to see if props is used more or less. The argument could be made that it gives a code reader an easy way to grasp that props.name is coming from a parent component. On the other side, it's cleaner when you're just passing name into the component with destructuring, but you don't have that quick cue of props to indicate the data is "passed in via props". So not using props might make a code reader think more, but if your components are small and not too many lines of code (and thus easier to think about), then not using props would be appropriate.

@smcalilly
Copy link
Author

smcalilly commented Mar 17, 2021

I like how you offer "bug" examples. Most tutorials only show you the working version, but showing common errors like this is very helpful to the learner.

that always helps me too, glad to know it works for other folks

@smcalilly
Copy link
Author

In this section, "Use an object as a function argument" would it be correct to call cat a "pointer"? As in it can be named anything you want because it is just pointing to the object you're passing to the function?

yes. the variable is pointing at something in memory, in that section, the function sayNameAndAge is essentially a variable that's pointing in memory to wherever that function lives within the javascript compiler...i need to fact check myself on the technical specifics here, but that's the way i understand it.

@smcalilly
Copy link
Author

smcalilly commented Mar 17, 2021

Coming from Ruby, it would be helpful to more clearly explain that a Javascript object is more like a Ruby hash, whereas a Ruby object is more like a Javascript prototype. Is that right?

yes. when introducing objects, i say, "Ruby has the hash, Python has the dictionary, and Javascript has the object." but i think i need to explain what a prototype too.

i didn't expect this guide to get into that detail, it was really meant to be a way to explain destructuring based on a question you had asked, and the only way i could lead up to that topic was everything that came before it. but if i were to expand this, then i'd need a section on prototypes.

it's a topic i'm not too knowledgeable on. i know enough to where i can work with it if i encounter it. i've kind of avoided it as i learned javascript and other languages because it seemed so confusing compared to ruby or python's oop model. but i've probably reached the point where i can understand it better.

covering this topic depends on what all i want to cover and who the intended audience is. if you're just trying to write some javascript for work, do you think understanding something that deep in the language helps? or does it simply help to have that comparison to ruby or at the very least context about what a prototype is, and how javascript works differently?

@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