Salesforce Certified JavaScript Developer I · Lesson 7

Choosing the Best Function Implementation

Six rules decide which function form fits. Free to watch, with a free slide PDF and practice questions.

Chapters

  1. 0:00 Choosing the Best Function Implementation
  2. 0:33 Quick recap: JSON in, JSON out
  3. 1:16 Six rules decide which function form fits
  4. 1:53 One table holds the whole lesson
  5. 2:58 A function declaration is callable before its line
  6. 3:42 Calling early: each form fails differently
  7. 4:28 A regular function sets this when it is called
  8. 5:15 An arrow function takes this from where it is defined
  9. 6:12 An arrow function is the wrong shape for a method
  10. 6:49 call and apply set this once; bind fixes it
  11. 7:44 Arrow functions give up four things
  12. 8:16 A default fires only for missing or undefined
  13. 9:01 A default array is fresh on every call
  14. 9:43 A rest parameter gives you a real array
  15. 10:28 A closure keeps its outer variables alive
  16. 11:17 Callbacks in a var loop all see the final value
  17. 12:06 Functions are values you can pass around
  18. 12:50 Six terms to say in your own words
  19. 13:36 Refactor it, then run it in Node
  20. 14:55 Eight questions, closed book
  21. 15:52 A developer runs the following code. What is logged?
  22. 16:46 ["Guest",null,""]
  23. 17:46 Five requirements, five forms
  24. 18:27 Now test it, then move to object fundamentals

Test yourself on choosing the best function implementation

Practice questions for this lesson come with a full explanation of why each answer is right or wrong, and link back to the exact moment in the video.

Take the free diagnostic

Transcript

Read the full lesson text

Choosing the Best Function Implementation 0:00

Welcome to module two, lesson one: choosing the best function implementation. This module is called Objects, Functions, and Classes, and it carries twenty five percent of the exam. In this lesson we choose between function forms. There is the classic function keyword, the arrow function, and the rest parameter, and each one fits a different requirement. The exam asks which one fits. By the end, you will be able to read a business requirement, pick the function form that fits, and predict what it does.

Quick recap: JSON in, JSON out 0:33

Before we start, a quick recap from the last lesson of module one: json in, json out. First, "json dot parse" turns text into a value, and invalid json throws a "syntax error". Second, "json dot stringify" drops undefined and functions inside objects, and it throws on circular references. Third, a replacer, the "to json" method, or a reviver shapes what goes out and what comes back. And fourth, "structured clone" makes a deep copy, while the json round trip loses functions. Today, module two begins with functions. Given a requirement, which form fits?

Six rules decide which function form fits 1:16

This domain is twenty five percent of the exam, and this lesson is where it starts. The lesson boils down to six rules, held in one summary table of four rows. First, declarations hoist. Second, this and arrow functions. Third, call, apply, and bind. Fourth, default and rest parameters. Fifth, closures. And sixth, callbacks. Rules one, two, and four produce most of the questions, so we slow down there. We will also cover the limits of arrow functions, and the loop closure trap.

One table holds the whole lesson 1:53

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Hoisting. The rule is that declarations work before their line. The trap is that a var expression gives a "type error". The safe habit is a declaration, to call early. The word this. The rule is that a regular function sets this at call time, and an arrow function inherits it. The trap is an arrow function as a method. The safe habit is method shorthand. Parameters. The rule is that defaults fire on undefined, and rest is an array. The trap is that null keeps null. The safe habit is rest, not arguments. Closures. The rule is that a function keeps its outer variables. The trap is that var loop callbacks share one. The safe habit is let, or a factory. One practical rule: match the function form to the requirement before you write the body.

A function declaration is callable before its line 2:58

Rule one. A function declaration is callable before its line. Look at the code. We call "say hi" on the first line, and it returns hi. The function is defined below the call, and it still works. Why? A function declaration is hoisted with its body to the top of its scope. JavaScript has already seen it before the first line runs. A function expression is different. It is a function assigned to a variable, or passed as a value. Expressions are not hoisted, so they are not usable before their assignment line. They are convenient as arguments to other functions, though. The exam point: to call a function above its definition, use a function declaration.

Calling early: each form fails differently 3:42

Now the trap. Each form fails differently when you call it early. Read each row, then check the reason. The function declaration works, because it is hoisted with its body. A var function expression gives a "type error". The variable f exists, but it is undefined, and undefined is not a function. A const function expression gives a "reference error", because of the temporal dead zone. The name cannot be read before its line. A var arrow function is a "type error" too, the same as a var expression. And a const arrow function is a "reference error", the same as a const expression. The exam point: a var or const function expression, arrow functions included, is not usable before its assignment line runs.

A regular function sets this when it is called 4:28

Rule two. A regular function sets this when it is called. Look at the code. We define a user object with a name, Ana, and a method called "hello" that returns this dot name. Calling user dot hello gives Ana, because the call has user in front of the dot. Now we copy the method into a variable called loose, and call it. There is nothing in front of the dot, so this is not user. So a call like obj dot method makes this be obj. A standalone call gives the global object, or undefined in strict mode. The same function can see a different this on each call. Method shorthand is the right form for object methods. The exam point: for a regular function, ask how it was called, not where it was written.

An arrow function takes this from where it is defined 5:15

Now the other half of rule two. An arrow function takes this from where it is defined. Look at the code. A counter object has a count of ten, and a method called "later". Inside it, "set timeout" runs two callbacks. The first is a regular function. Its this is not counter, because the timer calls it with no object in front, so it does not log ten. The second is an arrow function. It has no own this, so it uses the this of the method around it, which is counter. It logs ten. So an arrow function has no own this; it inherits from the surrounding scope. How it is invoked never changes that this. The typical fit is a callback inside a method or a constructor, such as with "set timeout". A regular function callback runs with its own, different this. The exam point: use an arrow function for callbacks that must keep the surrounding this.

An arrow function is the wrong shape for a method 6:12

Here is the trap. The wrong shortcut says, arrow functions are just shorter methods. The correct exam test says, methods and constructors use a regular function or method shorthand. Look at the code. The panel has watts of four hundred. The property bad is an arrow function returning this dot watts. But an arrow function takes this from where it was defined, which is outside the object, so this is not panel. The property good uses method shorthand, and returns four hundred. The practical rule: arrow as a callback, method shorthand as a method.

call and apply set this once; bind fixes it 6:49

Rule three. Call and apply set this once; bind fixes it. Look at the code. The function who returns this dot n. Who dot call, with an object where n is one, returns one. Who dot apply, with n equal to two, returns two. Both run the function right now, with the this you give them. Next, who dot bind, with n equal to three, returns a new function, b. Calling b returns three. And even b dot call with n equal to nine still returns three, because the first bind wins. So call and apply set this for one invocation. Bind returns a new function with this fixed. Binding a bound function again has no effect. And none of them can change an arrow function's this. The exam point: to pass a method as a callback with this fixed, pass obj dot method dot bind, of obj.

Arrow functions give up four things 7:44

Arrow functions are compact, but they give up four things. Look at the code. Make is an arrow function. Calling it with new throws a "type error", and its prototype is undefined. First, no own this: it is inherited. Second, no own arguments object. Third, no prototype, and they cannot be generators. Fourth, calling one with new throws a "type error", as we just saw. The exam point: arrow functions are not for constructors or methods.

A default fires only for missing or undefined 8:16

Rule four. A default fires only for a missing or undefined argument. Look at the code. The function label has a parameter text with the default none. Calling label with no argument gives none. Passing undefined also gives none. But passing null gives null, and passing an empty string gives an empty string. Those are real values, so the default stays out of the way. So a default is used when no value, or undefined, is passed. Null and the empty string do not trigger it. Defaults are evaluated at call time. So an empty array default is a new array on every call. The exam point: passing null to a parameter with a default keeps null.

A default array is fresh on every call 9:01

Here is the next trap, and it comes straight from that last point. The wrong shortcut says, the default array is shared between calls. The correct exam test says, the default expression runs again at every call. Look at the code. The function tag takes x and a seen array that defaults to empty. It pushes x and returns seen. Tag of one gives an array holding just one. Tag of two gives an array holding just two, not one and two, because the second call got a brand new array. Contrast that with an array created once outside the function, which would be shared. The practical rule: defaults are safe for arrays and objects, because nothing is shared.

A rest parameter gives you a real array 9:43

The second half of rule four is the rest parameter, and it gives you a real array. Look at the code. The function sum takes a rest parameter called nums, and it reduces them to a total. Sum of one, two, three returns six. Now the old way. The function old reads arguments dot map, and that is undefined, because arguments is not a real array. You write a rest parameter as dot dot dot args. There is one per function, and it must be last. It cannot have a default value. It is a real array, so sort and map work. And arguments is not a real array. The exam point: for a variable number of arguments, use a rest parameter, not arguments.

A closure keeps its outer variables alive 10:28

Rule five. A closure keeps its outer variables alive. Look at the code. The function "make counter" declares count as zero, and returns an arrow function that increments it. We call "make counter" once and store the result as next. Calling next gives one, then two. But outside, count is a "reference error". The variable is hidden, and only the returned function can reach it. A closure is a function bundled with its surrounding state. One is created every time a function is created. A factory returns functions that share a hidden variable. That is private state. And each call to the factory makes new state. The exam point: when outside code must not change a value directly, use a factory with a local variable.

Callbacks in a var loop all see the final value 11:17

Here is the classic closure trap. The wrong shortcut says, each callback remembers its own i. The correct exam test says, with var there is one i. Let makes one per iteration. Look at the code. We declare an empty array, then loop with var i from zero to two, and push an arrow function that returns i. After the loop, i is three. Mapping over the functions and calling each one gives three, three, three. All three callbacks share the one variable. Change the loop to let, and each iteration gets its own i, so you get zero, one, two. Closures capture the variable, not its value at that moment. The practical rule: use let or const in the loop, or build each callback in a factory function.

Functions are values you can pass around 12:06

Rule six. Functions are values you can pass around. Look at the code. We write our own function map. It takes a function f and an array a, loops over the array, and pushes f of each item into a new array. Then we call it with an arrow that squares a number, and the array one, two, three. We get one, four, nine. A function can be passed as an argument to another function. A function expression is convenient for that. An arrow keeps the surrounding this. And bind fixes this when you pass a method. The practical rule: to run a function later, pass it; do not call it. If you add parentheses, you run it now and pass its result instead.

Six terms to say in your own words 12:50

Let's lock in the vocabulary. Here are six terms to say in your own words. A function declaration is written with the function keyword and a name, and it is hoisted with its body. A function expression is a function used as a value, and it is not hoisted. An arrow function has a lexical this, no own arguments, and it is not a constructor. A default parameter is used when the argument is missing or undefined. A rest parameter is dot dot dot args: the last parameter, and a real array. And a closure is a function plus its surrounding lexical environment. Pause the video now. Cover each card and explain the term aloud, then try it.

Refactor it, then run it in Node 13:36

Now the proof stage, starting with a lab. Refactor the old code, then run it in Node. Look at the before code. It keeps a global total with var. The function "add all" takes three parameters, and it fills in missing arguments by hand with or zero. Then it returns the running total. Now the after code. The function "make total" takes a start that defaults to zero. It keeps total in a local variable, which makes a closure. It returns an arrow function that takes a rest parameter, adds all the numbers, and returns the new total. Then we create add with a start of ten. Your task: predict three results before you run it. Add of one and two, add of four, and make total with no argument, then called with five. Take three minutes on your own, and write down your predictions. Then state which form you chose and why: closure for private state, default for the start, rest for any count. Now the answers. Add of one and two gives thirteen. Add of four gives seventeen, because the state carries over. And make total with no argument, called with five, gives five, because the default start is zero. A wrong prediction is the lesson. Go back to the slide that explains it.

Eight questions, closed book 14:55

Self check: eight questions, closed book. Answer out loud, then I will reveal each one. One. Can you call a function declaration above its line? Yes, it works. Two. What happens if you call a var function expression early? A "type error". Three. What about a const arrow function called early? A "reference error". Four. Where does an arrow function get this? From where it is defined. Five. Bind a function twice: which this wins? The first bind. Six. Does a default fire for null? No, null stays. Seven. Is a rest parameter a real array? Yes. And eight. What do closures in a var loop of three give? Three, three, three. How many did you get? Anything you missed, go back to its slide.

A developer runs the following code. What is logged? 15:52

Time for a practice question, taken from the question bank. This is a predict question. Pause the video and trace each call before you read the options. A developer runs the code shown. What is logged? The function greet takes a name that defaults to Guest, and we log the json string of an array of three calls: greet with undefined, greet with null, and greet with an empty string. Option A: Guest, Guest, Guest. Option B: Guest, Guest, and an empty string. Option C: Guest, null, and an empty string. Option D: Guest, null, Guest. This question combines the default parameter rule with the json output from the last lesson. Work through the three calls one at a time. Pause now, and I will give you the answer on the next slide.

["Guest",null,""] 16:46

The answer is C. Guest, null, and an empty string. Here is why. Greet with undefined uses the default, so it returns Guest. Greet with null passes null, because a default fires only for undefined, so it returns null. And greet with an empty string returns the empty string, which is a real value. In the json output, null stays null. Now the wrong options. A says Guest, Guest, Guest. That treats null and the empty string as missing, but they are real values. B says Guest, Guest, and an empty string. That treats null as missing, but null does not trigger the default. D says Guest, null, Guest. That treats the empty string as missing, but the empty string does not trigger the default either. Every wrong option misreads when a default fires. The takeaway: a default parameter fires only for a missing or undefined argument.

Five requirements, five forms 17:46

Let's consolidate. Five requirements, five forms. Call early: use a function declaration. Var and const expressions are not usable early. Methods: use method shorthand. Arrows inherit this and cannot be constructors. Callbacks: an arrow keeps this, and bind fixes this. The first bind wins. Parameters: defaults fire on undefined only. Use rest, not arguments. And state: use a closure factory, and use let in loops. Remember: read the requirement, then pick the form. If you can say these five cards from memory, you've got the lesson.

Now test it, then move to object fundamentals 18:27

That completes lesson one of module two. Now test it, then move on to object fundamentals. The flow is: read it, predict it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Object Fundamentals in JavaScript, we look at object literals, destructuring, spread, and freezing. See you there.