Home > Net >  I have two questions about array of object in javascript
I have two questions about array of object in javascript

Time:06-23

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.

CodePudding user response:

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.

  • Related