Programming Paradigms

Course 2 – Programming with JavaScript quiz answers

Week 3: Programming Paradigms

Meta Front-End Developer Professional Certificate

Complete Coursera Answers & Study Guide

Click to Enroll in Coursera Meta Front-End Professional Certificate

Programming Paradigms INTRODUCTION

This module is part of Coursera’s Meta Front-End Developer Professional Certificate. It focuses on the programming paradigms of functional and object-oriented programming. You will learn the basics of scope in JavaScript, including the differences between var, let and const. Additionally, you’ll explore how to use classes and inheritance to build objects using OOP principles.

Finally, you’ll look at modern features such as spread and rest operators and write code that can manipulate DOM elements as well as handle events. With this knowledge, you will be able to start creating your own dynamic applications with confidence.

Learning Objectives

  • Outline the tenets of the functional programming and object-oriented programming paradigm
  • Describe how scope works in JavaScript
  • List the differences between var, let, and const
  • Use classes and inheritance in OOP in JavaScript
  • Use JSON in JavaScript
  • Build code that manipulates the DOM and handles events
  • Write JavaScript code using more modern features like spread, rest, template strings, and modules

SELF REVIEW: BUILD A FUNCTIONAL PROGRAM

1. Did you complete the Building a functional program exercise?

  • Yes (Correct)
  • No

Correct: Well done on completing the exercise!

2. Were there any parts of the Building a Functional Program exercise that you found difficult to complete?

  • Yes (Correct)
  • No

Correct: If you’ve listed any particular part of the exercise as being difficult to complete, think about why that was the case. What was it that was hard to understand? Pin-pointing the most difficutl concept will help you understand areas that potentially need to be worked on more.

3. Would you say that you are able to explain, in your own words, the difference between the functional programming paradigm and the object-oriented programming paradigm?

  • Yes (Correct)
  • No

Correct: Great! Being able to describe newly-learned concepts in your own words is a reflection of a better understanding of the subject matter.

KNOWLEDGE CHECK: INTRODUCTION TO FUNCTIONAL PROGRAMMING

1. What will print out when the following code runs?

    var globalVar = 77;

    function scopeTest() {
        var localVar = 88;
    }

    console.log(localVar);
  • 77
  • 88
  • null
  • undefined (Correct)

Correct: localVar  is scoped to the function so therefore it is undefined in the global scope.

2. Variables declared using  const  can be reassigned.

  • true
  • false (Correct)

Correct: Variables declared using  const  cannot be redeclared or reassigned.

3. When a function calls itself, this is known as _____________.

  • Recursion (Correct)
  • Looping
  • Higher-order Function

Correct: Recursion is when a function calls itself.

4. What will print out when the following code runs?

    function meal(animal) {
        animal.food = animal.food + 10;
    }

    var dog = {
        food: 10
    };
    meal(dog);
    meal(dog);

    console.log(dog.food);
  • 10
  • 20
  • 30 (Correct)
  • 40

Correct: That’s correct! The food value starts at 10. The meal function is called twice which adds 10 to the food value each time. Therefore, 30 is printed.

5. What value will print out when the following code runs?

    function two() {
        return 2;
    }

    function one() {
        return 1;
    }

    function calculate(initialValue, incrementValue) {
        return initialValue() + incrementValue() + incrementValue();
    }

    console.log(calculate(two, one));
  • 1
  • 2
  • 3
  • 4 (Correct)

Correct: That’s correct! The  two  function is passed as the first parameter to the  calculate  function and the  one  function is passed as the second parameter. Therefore, when the  calculate  function runs, it will call  two() + one() + one() . The result is then 4.

6. In functional programming, the data and functions that work on that data are combined inside objects. 

  • True
  • False (Correct)

Correct: In functional programming, data and functions that operate on it are clearly separated, not combined inside objects.

7. Do you recall these comparison operators == and === ?

  • Yes (Correct)
  • No

Correct: Great!

8. Consider the following code:

 function myDay() {
    console.log('Morning');
    console.log('Afternoon');
    console.log('Evening');
    myDay();
 }
  • Which one of the following best describes what will happen if you run this code?
  • The function will run in an infinite loop. (Correct)
  • The function will only run once.

Correct: The function will run over and over, as there is no condition to stop it.

9. You decide to create a variable within the local scope while scripting a new JavaScript file. Is this variable accessible to code at the global scope level?

  • Yes (Correct)
  • No

Correct: Variables created within the local scope cannot be read by code at the global scope level. They are accessible only to functions located within the local scope. 

10. You are performing an update to some code and you need to create a variable named quantity, which calculates the total number of items. You need this variable to be accessible only inside a for loop. You declare the variable using the let keyword and it is within a for loop that performs the calculation of the total number of items. Does this variable declaration address your needs?

  • Yes (Correct)
  • No

Correct: When you use let and const to declare a variable, it is scoped to the block – even within if statements and loops, like the for or while loops. Therefore, the quantity variable you create will only exist within the for loop. 

11. Which one of the following statements is true when declaring variables using either var, let or const?

  • Variables declared with const must be assigned during declaration. (Correct)
  • Variables declared with var must be assigned during declaration.
  • Variables declared with let must be assigned during declaration.

Correct: Variables declared with const must be assigned during declaration.

SELF REVIEW: BUILDING AN OBJECT-ORIENTED PROGRAM

1. Did you complete the Building an Object-oriented Program exercise?

  • Yes (Correct)
  • No

Correct: Well done on completing the exercise!

2. Were there any parts of the Building an Object-oriented Program exercise that you found difficult to complete?

  • Yes (Correct)
  • No

Correct: If you’ve listed any particular part of the exercise as being difficult to complete, think about why that was the case. What was it that was so hard? Pin-pointing the most difficutl concept will help you understand areas that potentially need to be worked on more.

3. Would you say that you are able to explain, in your own words, how to use classes and inheritance in OOP in JavaScript?

  • Yes (Correct)
  • No

Correct: Great! Being able to describe newly-learned concepts in your own words is a reflection of a better understanding of the subject matter.

KNOWLEDGE CHECK: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING

1. What will print out when the following code runs?

    class Cake {
        constructor(lyr) {
            this.layers = lyr + 1;
        }
    }

    var result = new Cake(1);
    console.log(result.layers);
  • 1
  • 2 (Correct)
  • 3
  • 4

Correct: That’s correct! The Cake object stores its  layers  property as the value of the constructor parameter  lyr  plus one. Therefore, the value of the  layers  property is 2.

2. When a class  extends  another class, this is called ____________.

  • Inheritance (Correct)
  • Extension

Correct: That’s correct! A class inherits from another class using the  extends  keyword. This is called Inheritance.

3. What will print out when the following code runs?

    class Animal {
        constructor(lg) {
            this.legs = lg;
        }
    }

    class Dog extends Animal {
        constructor() {
            super(4);
        }
    }

    var result = new Dog();
    console.log(result.legs);
  • 0
  • undefined
  • null
  • 4 (Correct)

Correct: That’s correct! The Dog constructor passes the value of  4  to the super constructor of Animal. Therefore, the value of the  legs  property is  4 .

4. What will print out when the following code runs?

    class Animal {

    }

    class Cat extends Animal {
      constructor() {
        super();
        this.noise = "meow";
      }
    }

    var result = new Animal();
    console.log(result.noise);
  • undefined (Correct)
  • null
  • “”
  • Meow

Correct: That’s correct! The  noise  property does not exist within the scope of the  Animal  class. Therefore,  undefined  will print.

5. What will print out when the following code runs?

    class Person {
        sayHello() {
            console.log("Hello");
        }
    }

    class Friend extends Person {
        sayHello() {
            console.log("Hey");
        }
    }

    var result = new Friend();
    result.sayHello();
  • Hello
  • Hey (Correct)

Correct: The Friend class overrides the  sayHello  method. Therefore,  Hey  is printed out instead of  Hello  when  sayHello  is called.

6. You are coding in OOP style. Why would you want to use the “this” keyword?

  • To refer to the object itself without specifying the object’s name. (Correct)
  • To declare an object’s methods.

Correct: The “this” keyword is an alias for the name of the object.

7. You are working with classes in JavaScript. Which of the following instructions should you adhere to? Check all that apply.

  • Create an instance of the class using the keyword new and that class’ name, followed by opening and closing parentheses, and optional arguments, based on how the class itself is defined. (Correct)
  • Make sure that the name of your class is lowercase.
  • Add a constructor function to accept your parameters. (Correct)
  • Build your classes using the “class” keyword. (Correct)

Correct: That’s right. For example, if a class named Car doesn’t take any arguments, you’d instantiate it like this: new Car()

Correct: That’s right. The constructor function assigns passed-in parameters to the future object’s properties.

Correct: That’s right. Any class is built using the “class” keyword.

8. True or false? In JavaScript, you can use a prototype object to hold properties that can be shared with various other objects. 

  • True (Correct)
  • False

Correct: The prototype is an object that can have properties to be shared by multiple other objects.

9. True or False. In JavaScript, it’s possible to extract the properties from objects into distinct variables using destructuring.

  • True (Correct)
  • False

Correct: In JavaScript, it’s possible to extract the properties from objects into distinct variables using destructuring.

10. When working with objects, the for-of loop and for-in loop can be used to iterate over the object’s properties. Which of the following statements are correct? Choose all that apply.

  • The for-of loop will iterate over the object’s own properties only when using the Object.keys() method to return an array to loop over. (Correct)
  • The for-of loop will not iterate over the object and its prototype properties. (Correct)
  • The for-in loop will not iterate over the object and its properties.

Correct: The for-of loop will not iterate over the object and its prototype properties.

Correct: The for-of loop will iterate over the object’s own properties only when using the Object.keys() method to return an array to loop over.

11. In what ways can template literals be used to write JavaScript code more efficiently? Check all that apply:

  • You can create multi-line strings. (Correct)
  • You can interpolate variables. (Correct)
  • You can combine strings with less code. (Correct)
  • You can use variables that have not been declared.

Correct! Template literals can be used to create multi-line strings, interpolate variables, and to combine strings with simpler code.

Correct! Template literals can be used to create multi-line strings, interpolate variables, and to combine strings with simpler code.

Correct! Template literals can be used to create multi-line strings, interpolate variables, and to combine strings with simpler code.

SELF REVIEW: ARRAY AND OBJECT ITERATION

1. Did you complete the Array and object iteration exercise?

  • Yes (Correct)
  • No

Correct: Well done on completing the exercise!

2. Were there any parts of the Array and Object Iteration exercise that you found difficult to complete?

  • Yes (Correct)
  • No

Correct: If you’ve listed any particular part of the exercise as being difficult to complete, think about why that was the case. What was it that was so hard? Pin-pointing the most difficult concept will help you understand areas that potentially need to be worked on more.

3. Would you say that you are able to explain, in your own words, how to loop over arrays and objects in JavaScript?

  • Yes (Correct)
  • No

Correct: Great! Being able to describe newly-learned concepts in your own words is a reflection of a better understanding of the subject matter.

 KNOWLEDGE CHECK: ADVANCED JAVASCRIPT FEATURES

1. What will print out when the following code runs?

    const meal = ["soup", "steak", "ice cream"]
    let [starter] = meal;
    console.log(starter);
  • soup (Correct)
  • ice cream
  • steak

Correct: That’s correct! The first item in the  meal  array is de-structured to the  starter  variable. Therefore, the code will print out  soup .

2. The for-of loop works for Object data types.

  • true
  • false (Correct)

Correct: That’s correct! The for-of loop must use an iterable such as arrays.

3. What will print out when the following code runs?

    let food = "Chocolate";
    console.log(`My favourite food is ${food}`);
  • My favourite food is Chocolate (Correct)
  • My favourite food is ${food}

Correct: That’s correct! The template literal will replace  ${food}  with  Chocolate .

4. What values will be stored in the set collection after the following code runs?

    let set = new Set();
    set.add(1);
    set.add(2);
    set.add(3);
    set.add(2);
    set.add(1);
  • 1, 2, 3, 2, 1
  • 1, 2, 3 (Correct)

Correct: That’s correct! A Set only stores unique items.

5. What value will be printed out when the following code runs?

    let obj = {
        key: 1,
        value: 4
    };

    let output = { ...obj };
    output.value -= obj.key;

    console.log(output.value);
  • 1
  • 2
  • 3 (Correct)
  • 4

Correct: That’s correct! The spread operator  …  will copy the properties from  obj . Therefore, when  output  is created, it’s  value  property will be equal to 4. Then 1 is substracted from the  value  property and result is stored back in the  value  property. Therefore, 3 will be printed out.

6. What value will be printed out when the following code runs?

    function count(...basket) {
        console.log(basket.length)
    }

    count(10, 9, 8, 7, 6);
  • 10, 9, 8, 7, 6
  • 1, 2, 3, 4, 5
  • 6
  • 5 (Correct)

Correct: That’s correct! The rest operator  …  allows a function to accept an indefinite amount of parameters. The length property of the  basket  variable will return 5 because there were 5 parameters passed to the method call. Therefore, 5 will be printed out.

7. The spread operator allows you to pass all array elements into a function without having to type them all individually. Is this true or false?

  • True (Correct)
  • False

Correct: The spread operator will include all of the array elements with much less code.

8. The rest operator allows you to take items from an array and use them to create a separate sub-array. True or false?

  • True (Correct)
  • False

Correct: The rest operator can be used to destructure existing array items, rather than typing them out again.

9. Which one of these data structures consists of iterable key-value pairs?

  • Maps (Correct)
  • Arrays
  • Sets
  • Objects

Correct: That’s right! Maps are made up of iterable key value pairs.

SELF REVIEW: CAPTURE DATA

1. Did you complete the Capture Data exercise?

  • Yes (Correct)
  • No

Correct: Well done on completing the exercise!

2. Were there any parts of the Capture Data exercise that you found difficult to complete?

  • Yes (Correct)
  • No

Correct: If you’ve listed any particular part of the exercise as being difficult to complete, think about why that was the case. What were the specific issues you’ve struggled with?

3. Would you say that you are able to explain, in your own words, how to capture event data in JavaScript?

  • Yes (Correct)
  • No

Correct: Great! Being able to describe newly-learned concepts in your own words is a reflection of a better understanding of the subject matter.

KNOWLEDGE CHECK – JAVASCRIPT IN THE BROWSER

1. In the following code, the type attribute can be omitted.

    <script type="text/javascript">
        //Comment
    </script>
  • True (Correct)
  • False

Correct: That’s correct!  type=”text/javascript”  is the implicit value of the  script  tag when it is omitted.

2. What does the  document  variable return in JavaScript?

    console.log(document);
  • The entire body tag of the webpage in the browser’s memory, as a JavaScript object.
  • The entire webpage in the browser’s memory, as a JavaScript object. (Correct)
  • The HTML code of the downloaded webpage, as a JavaScript string.

Correct: That’s correct! The  document  object holds the entire structure of the active webpage in the browser’s memory.

3. What does the following function return?

    getElementById('main-heading')
  • It doesn’t return anything.
  • All elements that have the  class  attribute with a value  main-heading
  • The first element that has the  id  attribute with a value  main-heading (Correct)
  • The last element that has the  id  attribute with a value  main-heading

Correct: The first element with the attribute  id=”main-header”  is returned.

4. After the following code is run, what will happen when the user clicks on a  p  element in the browser?

    document.querySelector('h1').addEventListener('click', 
        function() { 
            console.log('clicked');
        });
  • ‘clicked’ is printed to the console log.
  • Nothing. (Correct)

Correct: That’s correct! The click event listener is registered on h1  elements.

5. What will be printed when the following code runs?

    var result = {
      value: 7
    };
    console.log(JSON.stringify(result));

 {}
  • {value: 7}
  • {“value”: 7} (Correct)

Correct: That’s correct! JSON.stringify will turn the object into a string representation. The property name is wrapped in double quotes in the representation.

6. Which of the following statements about modules in JavaScript are true? Choose all that apply.​ 

  • To use an ES6 module in a browser, you need to set the script type attribute to “module” (Correct)
  • Modules allow for code to be reused and more easily replaced. (Correct)
  • Different module specifications, such asCommonJS, are universally compatible .
  • Modules were added to ECMAScript ES6 specification  (Correct)

Correct. To use an ES6 module in a browser, the script’s type attribute must be set to “module”. 

Correct. Modules were added to JavaScript in version ES6.

Correct. Modules were added to JavaScript in version ES6 and allow for code to be imported, reused and more easily replaced.

7. You can convert a JSON file to a JavaScript object so that you can work with that object’s properties.

  • True (Correct)
  • False

Correct: When working with JSON it is common to convert it back to a JavaScript object to work with its properties. To do this you need to use the global built-in JSON object and its parse method. 

8. True or false? Editing the local DOM of a webpage does not affect the document stored on the webserver.

  • True (Correct)
  • False

Correct: You are correct! The DOM is an in-memory representation of the active HTML document. Any changes made are local and do not affect the document stored on the webserver.

9. Which of the following are JavaScript DOM selectors? Check all that apply.

  • querySelector() (Correct)
  • querySelectorAll() (Correct)
  • getElementById() (Correct)
  • getElementsByClassName() (Correct)
  • setAttribute()

Correct. QuerySelector(), querySelectorAll(), getElementById(), and getElementsByClassName() are JavaScript DOM selectors, while setAttribute() is not a DOM selector.

Correct. QuerySelector(), querySelectorAll(), getElementById(), and getElementsByClassName() are JavaScript DOM selectors, while setAttribute() is not a DOM selector.

Correct. QuerySelector(), querySelectorAll(), getElementById(), and getElementsByClassName() are JavaScript DOM selectors, while setAttribute() is not a DOM selector.

Correct. QuerySelector(), querySelectorAll(), getElementById(), and getElementsByClassName() are JavaScript DOM selectors, while setAttribute() is not a DOM selector.

10. You are using JavaScript code on your website to listen out for events. Which of the following are examples of events that your code can listen out for? Check all that apply.

  • Button click (Correct)
  • Icon tap (Correct)
  • Using the command line software on your computer.

Correct: You are correct. Button click is an example of an event that your code can listen out for.

Correct: You are correct. Icon tap is an example of an event that your code can listen out for.

Coursera Meta Front-End Developer Professional Certificate Answers and Study Guide

Liking our content? Then don’t forget to ad us to your bookmarks so you can find us easily!

Weekly Breakdown | Meta Study Guides | Back to Top

MODULE QUIZ: PROGRAMMING PARADIGMS

1. Variables declared using  ‘let’ can be reassigned.

  • True (Correct)
  • False

Correct: That’s correct! Variables declared using  let  cannot be redeclared but can be reassigned.

2. What will print out when the following code runs?

    function scopeTest() {
        var y = 44;

        console.log(x);
    }

    var x = 33;
    scopeTest();
  • null
  • undefined
  • 33 (Correct)
  • 44

Correct: That’s correct!  x  is defined in the global scope before the  console.log  is called.

3. What will print out when the following code runs?

    class Cake {
        constructor(lyr) {
            this.layers = lyr;
        }

        getLayers() {
            return this.layers;
        }
    }

    class WeddingCake extends Cake {
        constructor() {
            super(2);
        }

        getLayers() {
            return super.getLayers() * 5;
        }
    }

    var result = new WeddingCake();
    console.log(result.getLayers());
  • 0
  • 2
  • 5
  • 10 (Correct)

Correct: That’s correct! The WeddingCake constructor stores the amount of layers as 2. However, WeddingCake overrides the  getLayers()  function to multiple the result by 5. Therefore,  10  is outcome.

4. What will print out when the following code runs?

  • bark
  • growl (Correct)
  • undefined

Correct: That’s correct! The  noise  property is overridden when the Wolf constructor is called.

5. Consider this code snippet: ‘const  [a, b]  =  [1,2,3,4] ‘. What is the value of  b?

  • Undefined
  • 1
  • 2 (Correct)
  • [1,2,3,4]

Correct: That’s correct! The value  b  is assigned the second item value of the array through de-structuring.

6. What value will be printed out when the following code runs?

    function count(...food) {
        console.log(food.length)
    }

    count("Burgers", "Fries", null);
  • 2
  • 3 (Correct)
  • “Burgers”, “Fries”, null XX
  • “Burgers”, “Fries”, undefined

Correct: That’s correct! The rest operator  …  allows a function to accept an indefinite amount of parameters. The length property of the  food  variable will return 3 because there were 3 parameters passed to the method call. The value  null  counts as a parameter. Therefore, 3 will be printed out.

7. Which of the following are JavaScript methods for querying the Document Object Model? Select all that apply.

  • getElementsByClassName (Correct)
  • getElementsById
  • getElementById (Correct)
  • getElementByClassName
  • queryAllSelectors
  • querySelector (Correct)

Correct: That’s correct!  getElementsByClassName  will return all elements with the specified class.

Correct: That’s correct!  getElementById  will return the first matching element with the specified ID.

Correct: That’s correct!  querySelector  will return all elements matching the specified CSS selector.

8. Which of the following methods convert a JavaScript object to and from a JSON string?

  • JSON.parse (Correct)
  • JSON.stringify (Correct)
  • JSON.fromString
  • JSON.toString

Correct: That’s correct!  JSON.parse  will convert a JSON string to a JavaScript object.

Correct: That’s correct!  JSON.stringify  will convert a JavaScript object to a JSON string.

9. What will be the result of running this code? 

 const letter = "a"
 letter = "b"
  • Uncaught TypeError: Assignment to constant variable (Correct)
  • b
  • a
  • Uncaught SyntaxError: Invalid or unexpected token

Correct: That’s correct. You cannot reassign a variable assigned using the const keyword.

10. What is a constructor?

  • A function that is called to create an instance of an object. (Correct)
  • An instance of a class. XX
  • A specific object that has been created using the class name.
  • An object literal 

Programming Paradigms CONCLUSION

This module is about functional programming and the oriented programming paradigm. You will learn what scope is in JavaScript. You’ll explore the differences between var, let and const. And you’ll learn how to use classes and inheritance in object oriented programming. Additionally, you’ll explore how to use write JavaScript using modern features like spread and rest. You will build code that can manipulate the DOM and handle events. And you will use JSON in JavaScript. After completing this module, you will be able to:

Subscribe to our site

Get new content delivered directly to your inbox.

Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!