0

the code is simply, I need to create some fruits and their price and quantities in an array of object like this :

cartTotal ( [
  { name: 'Apple', price: 4, quantity: 2 }, 
  { name: 'Orange', price: 3, quantity: 3 }
]);

    function cartTotal(cartArray) {
        let total = 0;
        
    cartArray.forEach(function(cartItem) {
        total = total + cartItem.price * cartItem.quantity;
          });
        console.log(total);
      }

my first question is why I cannot add '=' on a first line like this:

cartTotal = ( [

but in the other html I can use '=' like:

let todos = [
              {title: 'Get groceries', dueDate: '2021-10-04' },
              {title: 'Wash car', dueDate: '2021-02-03' },
              {title: 'Make dinner', dueDate: '2021-09-04'}
           ]

my second question is, on the 6 lines :

function cartTotal(cartArray) {

why the function name "cartTotal" must equal to array name "cartToal", if I change function's name, it can not work.

2
  • You need to look at simple javascript code samples first. There are plenty of resources online. ex: developer.mozilla.org/en-US/docs/Learn/… Commented Jun 22, 2022 at 18:05
  • The first statement is not a definition of a variable, it's a function call with an array as parameter. The function cartTotal is defined later. Commented Jun 22, 2022 at 18:06

1 Answer 1

1

my first question is why I cannot add '=' on a first line like this

You can do that. It effectively sets the value of cartTotal from being a function to an array. JavaScript functions are hoisted.

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

This is why you can call the function before declaring it.

() can be used as invocation operator or a grouping operator. functionName() calls a function identified as functionName. variable = ([]) sets the value of the variable variable to an array. The value doesn't have to be an array, of course.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.