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.
- Define a function that says hello
- A function can accept different types of arguments
- Objects
- Resources
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.)
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.
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:
function sayAge(age) {
return console.log(`My age is ${age}.`)
}
// prints "My age is 6."
sayAge(7)
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)
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)
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")
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)
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)
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 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)
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.
.
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)
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>
)
}
- Chapters 1 - 6 of Eloquent JavaScript.
- javascript.info for learning ES6 and for reference.
- MDN docs for reference.
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:
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:
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.