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 Feb 4, 2021

Feedback from 2-4-21

Intro
Intro was very clear and made me feel like I understood exactly the intended audience. Helps that I'm guessing you had me in mind when writing this.


Say Hello

Love the link to the repl that had the code already loaded in. Very nice example. I tried running it in my browser and got confused. Here's a screenshot of the error I was getting:

Screen Shot 2021-02-04 at 10 37 20 AM

So, this sentence is much more vague to a noob than you might realize:
"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."

My error was I stupidly didn't realize I had to call the function with the name "Sylvia" in it. I thought I could just run the function and manually insert the variable. I think a step-by-step in really obvious illustration of how to start using the console in the browser at a very basic level would be good to add here. (Be happy to add it.)

Also, the first two ways in your repl of defining a function make sense, but then introducing a "const" and an "arrow" function I think need to be explained at that point. I've seen lots of these arrow functions and don't know what they mean. I don't think it's too much to introduce at first, it's just breaking down every part of this first example and explaining every little detail in the most basic terms so that all of the code in your first example is understood before moving on.

Also I think this needs to be addressed at this point. Here's a quote from the tutorial you link to:

"It is easy to confuse the function declaration and function expression. They look very similar but produce functions with different properties."

That has def caused me a lot of confusion so far.


Re: Multiple ways of defining a function
This is so crucial to a noob it deserves it's on headline and section:

"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.)"

The code examples in the repl need to go directly in the body of the page.

Also, would like to know what YOUR opinion on the syntax you prefer to use at this point in 2021. Is there a React/ES6 style that makes the most sense to you? If so, tell me and why. For instance, I have thought way too much about when to use single vs. double quotes in Ruby, but for good reason.

Questions at this point:

  • Do you say "declaring" a function? Is that another way of saying, "defining" a function?
  • What is the difference between function and a constant?
    • at this point I'm imagining that a function is a like a ruby block that accepts parameters (aka arguments) and a constant is what? In ruby a constant is usually just used for things like a string for a global variable such as PRODUCTION_DOMAIN = "google.com", etc.

That's all the time I have for JS study this morning, but I will work my way through this and provide notes. Maybe you could make this a repo that you can share with me in Github and I can send you pull requests for edits? That would actually be a great way for me to work through this.

@smcalilly
Copy link
Author

i'm gonna move this to a github repo so you can comment if you still want to. got distracted by other stuff...

  • do all lee's notes

my notes:

  • add "opinions" section (arrow function vs function declaration, single quotes vs double, no semicolon; etc)
  • maybe add section about if statements...could be it's own document
  • expand the last section about working with objects to show how to do stuff with arrays (that could be its own document too)

@leemcalilly
Copy link

leemcalilly commented Mar 15, 2021

When you introduce the concept of an object I found it helpful to play around with sayHello in the repl to when following along the Mozilla article you link to. Might want to add a real illustration here where the reader runs object.getPrototypeOf(sayHello) and sayHello.prototype. That drove home what a prototype is for me. It's like a template for an object. A prototype is like a "class" in Ruby I think. At least it seems like the same concept as something like say_hello.class which if you went far enough up the chain ruby you'd arrive at method the same way sayHello.prototype returns function

@leemcalilly
Copy link

leemcalilly commented Mar 15, 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? Need to make this clear whatever code I need to have first so I can copy and paste your examples. Same thing happened in my browser console when I tried to copy / paste the "sayHello" example.

I guess I'm expecting it to work like a Ruby console where I can define a method in the console and then use it in the same console session. Do I have to save the function into a file in the Repl to then be able to use it? 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.

Screen Shot 2021-03-15 at 12 31 58 PM

@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