A More In-Depth Topic About Syntax With JavaScript

Topic

Hello Everyone!

This is an open topic to discuss how to truly understand what the syntax is saying when you are writing your code. Or another way to look at this topic, is how to truly understand the language when writing it. Even better how to get those Neurons working properly when writting JavaScript Code.

I am creating this topic because again today while trying to study I ran into one of those moments where I questioned myself:

“Why is the syntax written like this and not the way I learned?” Meanwhile my Neurons where operating like a moving train, then came to a stop as I continued to scratch my head in wonder.

Reference: JavaScript Versions: ES6 and Before

Now before we start talking about how people wrote syntax differently back in Netscape Enterprise Server Days or the publication of ECMAScript and how its good practice to learn different types of syntax… Please keep in mind this topic is a way for others including myself to truly understand the language as we are writing and not just following along with a lessons instructions.

Please feel free To share and collaborate your ideas and thoughts with the community!

Format

Please feel free to use this format:

  • Link To Lesson: Use the (Hyperlink) to show the link or (Ctrl + K)

  • What did you see that made you think “why is the syntax written this way?”

  • How did you think it should have been written?

  • Did your code work? If not what was the error?

  • Use the (Preformatted Text) to show your code or (Ctrl + Shift + C)

For The Commenters

  • Please share your thought, opinions and ways you have overcome these hurdles!

Its always good to find new ways to think when writing. It’s even better when you can share your experiences and others can relate.

For the Frozen Neuron's

Remember no question or expression is bad. Sometimes others feel the way we do and they may not know how to express it or feel encouraged to ask.
  • All criticism is great! Good and Bad… It’s up to you, how you interpret the meaning behind the commenter.

  • Finally Stay Focused! Learning to code can become daunting at times. This can create an overwhelming workplace for your brain. So take a break, grab a bite, get a cup of joe or get some rest. Come back stronger ready to excel in your new lesson or project…

2 Likes

Link: The .forEach() Method

What did you see that made you think “why is the syntax written this way?”

So I was working on a lesson today about the .forEach() method and I came across two different ways to write the code. Before I even began to follow the instructions below, I tried to process how the information was being passed in the language when I was reading about the forEach() method. The part that made me pause and think was the arrow function syntax.

Example:

groceries.forEach(groceryItem => console.log(groceryItem));

At first glance my brain was like “why is groceryItem not set as a variable?” It looks like they are trying to place a function in a previous identifier. When I write the short arrow function mine always looks like this:

let myFunction = () =>{
console.log(some text);
}

If you notice they go straight to groceryItem without the let part. They also forget to add an = and () before the short arrow function =>. So my Neurons stopped processing and I began to enter the web for answers. Of course I could’nt find the answer to my brains processing power so I decided to create this topic. I truly want to write this language as if it was my second language and I’m sure there is someone else out there that feels the same way.

How did you think it should have been written?

Reference: Concise Body Arrow Functions

Reference: Callback Function

In JavaScript , a callback function is a function that is passed into another function as an argument. This function can then be invoked during the execution of that higher order function (that it is an argument of). Since, in JavaScript , functions are objects, functions can be passed as arguments.

So I tried to write the code like so:

groceries.forEach(let groceryItem = () =>{
console.log(groceryItem)
});

Did your code work? If not what was the error?

This did not work. Which is when “the train was moving and then came to stop” momenent happen. My head was still trying to process why did this not work.

My Error:

groceries.forEach(let groceryItem = () =>{
^^^
SyntaxError: missing ) after argument list

What happened next after I started looking for answers from the web so my brain could process this was:

“well I can follow the example and move on to the next exercise” the only problem with this is I feel like a part of the language that I was suppose to learn and understand is now missing.

So back to the first question:
why is the syntax written this way?

Example:

groceries.forEach(groceryItem => console.log(groceryItem));

  • Why is the callback function “groceryItem” written without let, =, () when using the .forEach() method or any other method like .map()?

  • Why does the syntax not allow concise body function?

  • How is the variable being declared for the callback function?

  • Is groceryItem now a global variable? It does not appear to be in block scope.

Hope to hear some answers or thoughts.

Either way I hope someone else that is reading this doesn’t feel alone!

-Cheers-

1 Like

This is because .forEach(), .map(), and the like take a nameless function as their argument. That means that the function need to be given a name, as it is only ever used within the .forEach(). That is why you don’t need the let groceryItem= () part. That part defines a function with a name, which means it can be reused.

Also, the groceryItem here

Is a variable which refers to the item of the array that the forEach is on. That means that when you run the following code:

let array1 = ["1", "2", "3", "4", "5"]
array1.forEach(number => console.log(number));

number refers to 1, then 2, then 3, and so on.

I hope this helps!

1 Like

@codeneutrino Yes it did. Mainly because I did not realize you can create a nameless function.

It also makes more sense to me because now I know one can not work without the other. Meaning .forEach() and whatever name you give the callback function are apart of each other. Otherwise the .forEach() statement would not work right? Or does it work with variables that already exist?

The .map() Method

Link: The .map() Method

So I ran across another Neuron Moment only this time the code worked and I was getting an error. As you can see this can become very confusing when your trying to process this stuff in your brain. One minute I think I got it and the next the lessons says I do not.

What did you see that made you think “why is the syntax written this way?”
Just another way to write the syntax. This was after I had to click the view solution button though.

How did you think it should have been written?
First let me show you the step so you can follow along with how I thought it should be written.

Step 1: Add your code under the animals array and before the line console.log(secretMessage.join(''));

Use .map() to create a new array that contains the first character of each string in the animals array. Save the new array to a const variable named secretMessage .

The Console:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below 

My Code With Console:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage = animals.map(message =>{
  console.log(message.charAt(0));
});
// My code above this line ^^^^^^^^^^^^^^^^^^^^^^^
console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below

Did your code work? If not what was the error?
I thought my code worked because the console printed the first character of each string.

Error:

Did you return the first character of each element in your callback?

At this point is when I became a Frozen Neuron and started to re-read the instructions and the lesson. Finally I clicked the “view solution” button and re-ran the console. To my surprise the new code did the exact same thing my original code did.

The View Solution Code:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below

const secretMessage = animals.map(animal => animal[0]);
// The Solution Code Above ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below

const smallNumbers = bigNumbers.map(num => num/100);

console.log(smallNumbers)

So "why is the syntax written this way?"

  • Why did the console show me an error?
  • What part of the question did I miss?
  • Is the code they provided any different from the one I wrote?

There is a very distinct difference between your code, and the solution code. Your code prints a value to the console. The solution code returns a value. console.log() and return are two entirely different things.

If you add a console.log() statement, you’ll get a better idea of what happened with your original code. The .map() method returns a new array. Your code returned an array, but what’s in it?
We can print to see for ourselves:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage = animals.map(message =>{
  console.log(message.charAt(0));
});
// My code above this line ^^^^^^^^^^^^^^^^^^^^^^^
console.log('secret message:', secretMessage); //add this line to shed some light on what is happening
console.log(secretMessage.join(''));
Output:

H
e
l
l
o
W
o
r
l
d
secret message: [ undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined ]

Where did all of those undefined values come from? Well, what is the return value of console.log()?

Answer

undefined

1 Like

@midlindner midlindner

You Are Right! Thank You

I was able to still write my code as I orginially thought. The missing part that made my brain stop working was the fact that I should have returned the value instead of logging it to the console. I must say however the instructions did not lead me to believe either was the case had it been more clear in the first set of instructions I may have not console.logged my result and instead returned my result.

I reset the exersize only to return the value instead of console.log and it worked.

Thanks again midlindner

My New Code In Console:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage = animals.map(message =>{
  return message.charAt(0);
});
//My Code Above ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below
const smallNumbers = bigNumbers.map(num => num/100);

console.log(smallNumbers)```
1 Like

If you haven’t looked at the edit I made (added some additional information) to my original reply, check it out. It may help to understand why console.log() inside the .map() function didn’t yield the expected result.

2 Likes

@midlindner If I could give you double hearts I would! Now this is a powerful tool to use when trying to understand what is going on!

2 Likes

Another Neuron Moment...

Link: The .findIndex() Method

What did you see that made you think “why is the syntax written this way?”

So I was working on a lesson again today only this time everything was going good. Exercise worked great but then I wanted to challenge my self.

In this lesson it ask you to find an elephant and then ask you to find the first index of ‘s’. So I wrote the code to do both and passed. I then thought to myself:

“what was the solutions code since there’s other ways to write it”.

So I reset the lesson and ran the console until it asked me to “view solution”.

It came up with this:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {

  return animal === 'elephant';

});

const startsWithS = animals.findIndex(animal => {

  return animal[0] === 's' ? true : false;

});

So the last part of the solution was Frozen Nueron Moment:

const startsWithS = animals.findIndex(animal => {
return animal[0] === ‘s’ ? true : false;
});

So I googled what does “?” do and why true:false? I ended up finding out why but I also saw some code that looked different from both the way I was learning to write the code and also the way I wrote the code. That’s when I started wondering "why is the syntax written this way"

Lets look at the code in question:

Solution Code: const startsWithS = animals.findIndex(animal => {
return animal[0] === ‘s’ ? true : false;
});

My Code: const animalS = animals.findIndex(animal =>{
if (animal[0] === ‘s’){
return animal;
}
});

Internet Code: const animalZ = animals.findIndex(function(animal){
return animal[0] === ‘s’ ? true : false;
})

Now all three of these codes do the same thing the part that got me to the state of Frozen Nueron was when I saw there is a way to use function in this code, which is what I previously thought I could do before; only this time the “nameless” function is wrapped in round brackets function(animal). So at first glance it looks like either a parameter is being passed or an argument.

So my follow up questions are:

  • How is function allowed to be used in this case?
  • Is the (animal) in round brackets an parameter or an argument?
  • If it is either parameter or argument then how does it also become a “nameless” Function?

Well, it’s an anonymous function. It remains without a name. animal is the parameter. There are several ways to write this same functionality. Here a some examples:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

//Function declaration
function findElephant(animal) {
  return animal === 'elephant';
}

//arrow function
const findElephant1 = animal => {
  return animal === 'elephant';
}

//concise body arrow function
const findElephant2 = animal => animal === 'elephant';

//Now we can use the .findIndex iterator with any of our named functions above:
const foundAnimal = animals.findIndex( parameter => findElephant(parameter));
const foundAnimal1 = animals.findIndex( parameter => findElephant1(parameter));
const foundAnimal2 = animals.findIndex( parameter => findElephant2(parameter));
//The results are the same for all three:
console.log(foundAnimal, foundAnimal1, foundAnimal2);

//OR, we can use the .findIndex iterator with an anonymous function written a few different ways:
const foundAnimal3 = animals.findIndex(function(parameter){
  return parameter === 'elephant';
  }
);

const foundAnimal4 = animals.findIndex( parameter => {
  return parameter === 'elephant';
});

const foundAnimal5 = animals.findIndex( parameter => parameter === 'elephant');

console.log(foundAnimal3, foundAnimal4, foundAnimal5);

Output:

7 7 7
7 7 7

The below syntax is a ternary expression, but really is unnecessary in this case:

This also returns true or false without the ternary expression:

const startsWithS = animals.findIndex(animal => animal[0] === 's');

When we return an expression, the expression is evaluated first, and the result is returned. animilal[0] === 's' will evaluate to either true or false.

1 Like

@midlindner So then at least my brain is on the right track you could say! Thanks again for your feed back. It all makes more sense now knowing it was a parameter.

1 Like