JavaScript Recap for FE-2

Modified on Thu, 20 Apr, 2023 at 4:00 PM

Functions


What are functions in JavaScript?

In JavaScript, a function is a block of reusable code that performs a specific task. You can create functions to do specific tasks, like adding up two numbers or changing the color of a button on a webpage. You give the function a name and tell it what to do when you call it.


So, let's say you want to add up two numbers, 3 and 4. You can create a function called "addNumbers" that takes in two numbers as inputs and adds them together. Then, when you call the function by typing "addNumbers(3, 4)" in your JavaScript code, it will run the code inside the function and return the answer, which is 7.

function addNumbers(num1, num2) {
  Let result = num1 + num2;

  return result;
}






Why do we use functions in JavaScript?

Here are five reasons why we use functions in JavaScript:

  1. Code Reusability: Functions allow us to write a block of code once and reuse it as many times as we want throughout our program, saving time and effort.

  2. Organization: Functions help us break up our code into smaller, more manageable pieces, making our code easier to read, understand, and maintain.

  3. Encapsulation: Functions can hide the complexity of the code and data from the rest of the program, making our code more secure and less prone to errors.

  4. Abstraction: Functions provide a high-level view of our code, allowing us to focus on what the code does rather than how it does it, making it easier to understand.

  5. Separation of Concerns: Functions can separate different concerns or responsibilities of our program, making our code more organized and easier to maintain.






What are the different ways of declaring functions in JavaScript?

There are several ways to declare functions in JavaScript:

  1. Function declaration: This is the most common way to declare a function. It starts with the "function" keyword, followed by the name of the function, parameters (if any), and the code block. Here's an example:

function addNumbers(num1, num2) {
  return num1 + num2;
}


  1. Function expression: This is another way to declare a function, where you assign a function to a variable. Here's an example:

let addNumbers = function(num1, num2) {
  return num1 + num2;
}


  1. Arrow function: This is a newer way to declare a function introduced in ES6. It uses the "=>" syntax to define a function. Here's an example:

let addNumbers = (num1, num2) => {
  return num1 + num2;
}






What is the syntax for an arrow function?

Here's the breakdown of syntax for an arrow function:


Declaration:


  • The ‘const’ keyword is used to declare a constant variable to store the arrow function.

  • ‘functionName’ is the name of the function.

  • ‘(parameters)’ is a comma-separated list of parameters that the function expects to receive.

  • ‘=>’ is the arrow notation used to define an arrow function.



Call:

  • ‘functionName’ is the name of the arrow function to be called.

  • ‘arguments’ is a comma-separated list of values that are passed as arguments to the function.


Body:

  • ‘(parameters)’ is a comma-separated list of parameters that the function expects to receive.

  • ‘=>’ is the arrow notation used to define an arrow function.

  • ‘{}’ braces contain the body of the function where you write the code that you want the function to execute.


Example: 


The above code can also be written more concisely as follows, taking advantage of the fact that arrow functions with a single expression can omit the curly braces and the return keyword:






What is the syntax for an arrow function with a single parameter?

parameter => expression


Example: 


In this example, the arrow function takes a single parameter num and returns the result of doubling it. Since there is only one parameter, the parenthesis are not necessary, but the arrow => is still required to indicate that it is an arrow function. The function is then assigned to the constant variable double and is called with an argument of 5 in the console log, which returns the expected output of 10.





What is the syntax for an arrow function with multiple parameters?

An arrow function can have multiple parameters separated by commas. For example:

(param1, param2) => expression

Example: 

In this example, the function takes two parameters (‘a’ and ‘b’) and returns their sum using the + operator. The const keyword is used to declare a constant variable named sum that references the arrow function. Finally, the console.log() statement is used to output the result of calling the sum() function with arguments 3 and 4.





Can an arrow function have no parameters?

Yes, an arrow function can have no parameters. For example:

 () => expression


Here's an example of an arrow function with no parameters:

In this example, sayHello is an arrow function that takes no parameters. When called, it simply logs the string "Hello!" to the console. The function is assigned to a constant variable sayHello, and then invoked using parentheses ().




When do we use the return keyword in the arrow function?

In an arrow function, if the function body consists of a single expression, the value of that expression is automatically returned without using the "return" keyword. For example:

In the above example, the "add" function uses a single expression to return the sum of two numbers, while the "multiply" function uses the "return" keyword to return the product of two numbers.

It's worth noting that if an arrow function has a block body (i.e., more than one expression or statement), then the "return" keyword must be used to explicitly return a value from the function.




What is the difference between using console.log() inside a function and using return inside a function?

‘console.log()’ and ‘return’ are both used in JavaScript functions, but they serve different purposes.

When we use console.log() inside a function, we're printing a message to the console that we can view in the browser's developer tools. It's useful for debugging purposes, as we can see what's happening inside the function and what values are being passed around.


For example, consider the following function that uses console.log():

When we call add(2, 3), it will print the message "The sum of 2 and 3 is 5" to the console. 

However, this function does not return any value, so if we try to store the result in a variable, it will be undefined: 

On the other hand, when we use return inside a function, we're explicitly stating what value the function should return. This allows us to use the result of the function in other parts of our program.


For example, consider the following function that uses return:

When we call add(2, 3), it will return the value 5, which we can then store in the variable result. This allows us to use the result of the function in other parts of our program, such as in another function or in a conditional statement.


In summary, console.log() is used for printing messages to the console for debugging purposes, while return is used to explicitly state what value a function should return so that it can be used in other parts of our program.





CALLBACKS


What is a callback function?

A callback function is a function that is passed as an argument to another function and is intended to be called when the parent function has completed its task. Callback functions are commonly used in asynchronous programming in JavaScript.





What is the syntax for a callback function?


In the above example, the "greeting" function takes two arguments: a string representing a name, and a callback function. The function then logs a greeting to the console and calls the callback function.


The "sayGoodbye" function is defined separately and is passed as the callback function to the "greeting" function. When the "greeting" function is called with the name "Alice" and the "sayGoodbye" function as its callback, the output to the console is:






How do you pass arguments to a callback function?

You can pass arguments to a callback function by including them as additional arguments in the function call. For example:






Can you pass multiple callback functions to a single function? 

Yes, you can pass multiple callback functions to a single function by including them as additional arguments in the function call. For example:

The myFunction function takes two parameters: callback1 and callback2, both of which are callback functions. Inside myFunction, we call callback1() to execute the first callback function, and then we call callback2() to execute the second callback function.


In this example, myCallback1 and myCallback2 are two separate functions that we defined earlier. These functions simply log a message to the console when called.


Finally, we call myFunction and pass in myCallback1 as the first argument and myCallback2 as the second argument. This means that myCallback1 will be executed first, followed by myCallback2. When we run this code, we should see the following output in the console:


This is because myCallback1 logs "This is callback 1", and myCallback2 logs "This is callback 2", and both of these functions are executed in sequence inside myFunction.





Can you return a value from a callback function?

Yes, you can return a value from a callback function. A callback function is a function that is passed as an argument to another function, which will call it back at some point in the future. When the callback function is called, it can perform some operation and optionally return a value back to the caller.


Here is an example of a callback function that returns a value:

In this example, the myCallbackFunction takes in a value, multiplies it by 2, and returns the result. The myHigherOrderFunction is a higher-order function that takes in a callback function as an argument, calls it with an input value of 5, and then does something with the output.


When myCallbackFunction is called as a callback function inside myHigherOrderFunction, it returns the result of 10, which is then printed to the console by myHigherOrderFunction.






How does the callback function work in the case of setTimeout() method?

setTimeout is a built-in function in JavaScript that is commonly used as an example of a callback function. When we call setTimeout, we pass it two arguments: a callback function and a time delay in milliseconds. The setTimeout function then waits for the specified time delay to elapse and then executes the callback function.


Here is an example of using setTimeout with a callback function:


In this example, we define a function called sayHello that logs the message "Hello!" to the console. We then call setTimeout and pass it two arguments: the sayHello function and a time delay of 1000 milliseconds (i.e., one second). The setTimeout function then waits for one second and then executes the sayHello function as a callback function.


So in this example, sayHello is the callback function that is passed as an argument to setTimeout. The setTimeout function then waits for the specified time delay and then executes the callback function. This is a common pattern for using callback functions in JavaScript.






ARRAY METHODS


What are commonly used array methods in JavaScript?

  1. push() - adds one or more elements to the end of an array and returns the new length of the array.




  1. pop() - removes the last element from an array and returns that element.



  1. shift() - removes the first element from an array and returns that element. This method changes the length of the array.


  1. unshift() - adds one or more elements to the beginning of an array and returns the new length of the array.



  1. forEach() - calls a function for each element in an array.



  1. map() -  creates a new array with the results of calling a function for each element in an array.



  1. filter() - creates a new array with all elements that pass the test implemented by a provided function.



  1. reduce() - method is used to iterate over an array and reduce it to a single value.






What is the difference between the value returned by the callback function and the array method?

In JavaScript, callback functions and array methods work together to perform operations on arrays. The value returned by the callback function and array method can differ depending on the method used.


  1. Filter: 

The filter() method creates a new array with all the elements that pass the test implemented by the provided callback function. 

The callback function returns a boolean value of true or false. If the value is true, the element is included in the new array. If the value is false, the element is excluded. The array method returns a new filtered array.



Example:


  1. Map:

The map() method creates a new array with the results of calling a provided function on every element in the calling array. The callback function returns a new value for each element in the array. The array method returns a new array of the same length as the original array.


Example: 


  1. Reduce:

The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value. The callback function returns a new value for each iteration. The array method returns a single value.


Example: 

const numbers = [12345];

const reducedNumber = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);

console.log(reducedNumber);  // Output: 15



  1. forEach: 

The forEach() method executes a provided function once for each array element. The callback function does not return a value

The array method returns undefined.



Example: 



Here’s a summary of what array method returns vs what callback function returns in case of filter, reduce, map, and forEach: 

Name

Callback Function

Array Method

forEach()

Doesn’t return any value

Undefined

reduce()

Returns new value for each iteration

Single Value

map()

Returns new value for each iteration

Returns a new array of the same length as the original array

filter()

Returns boolean value:

 true or false

Returns new filtered array





What are some of the array methods which can modify the original array?

Array methods such as push(), pop(), shift(), unshift(), splice(), and sort() can modify the original array.




What is the difference between the map() and forEach() methods in JavaScript?

Both map() and forEach() methods iterate over an array, but the map() method returns a new array with the results of calling a provided function on every element in the original array, while the forEach() method simply executes a provided function once for each array element.





What is the difference between the forEach() method and a for loop in JavaScript?

The forEach() method is a built-in method of JavaScript arrays that provides an easy way to loop over an array and execute a function on each element. It's more concise and readable than a for loop, but it doesn't allow you to break out of the loop early like a for loop does.





If there are no elements present in the array,  then what does find and filter return?

If there are no elements present in the array, then in that case:

  • Filter method returns an empty array.

  • Find method returns undefined.


Example: 





If an item isn't present in the array then what does find and filter return?

filter() method will return an empty array if the item is not present in the array, whereas the find() method will return undefined.

In the above example, the filter() method will return an empty array because there are no numbers greater than 5 in the original array. Similarly, the find() method will return undefined because there is no number in the array that is equal to 6.



TERNARY OPERATORS


What are ternary operators and what is its syntax?

In JavaScript, the ternary operator is also a shorthand way of writing an if-else statement. It takes three operands: a condition, a result for the condition being true, and a result for the condition being false.


The syntax of the ternary operator in JavaScript is:



For example:

In this example, the condition is x > y, which evaluates to false because 10 is not greater than 20. Therefore, the expression returns y, which is 20.

The ternary operator can be used to simplify code and make it more concise, especially when you only have a small if-else statement. However, overusing the ternary operator can make your code harder to read and understand, so it's important to use it judiciously.



Can we use the ternary operator to execute multiple statements? 

In JavaScript, the ternary operator can be used to execute multiple statements, but it is not recommended as it can make the code harder to read and understand.


However, if you want to use the ternary operator to execute multiple statements, you can enclose the statements within parentheses and separate them with a comma. Here is an example:

In this example, the ternary operator checks whether ‘a’ is greater than ‘b’. If it is, it executes the statements inside the first parentheses, which include a console.log statement, incrementing ‘a’ by 2, and incrementing ‘b’ by 5. If ‘a’ is not greater than ‘b’, it executes the statements inside the second parentheses, which include a console.log statement, decrementing ‘a’ by 2, and decrementing ‘b’ by 5.


However, it is usually better to use an if-else statement or a separate function to execute multiple statements for the sake of the readability and maintainability of the code.


Is the ternary operator faster than if-else statements?

The performance of the ternary operator and if-else statements is generally the same, and any performance differences are likely to be negligible. It's more important to focus on writing clear and readable code than trying to optimize for performance.





Why using a return statement as the condition of the ternary operator gives an error in javascript?

When you use a return statement inside the condition of a ternary operator in JavaScript, it will result in a syntax error. This is because the syntax of the ternary operator requires that the condition must evaluate to a boolean value, and a return statement does not have a boolean value.


Here's an example of a syntax error that occurs when you try to use a return statement inside the condition of a ternary operator:

In this example, the code is attempting to use two return statements inside the condition of a ternary operator to return a value based on the result of the comparison. However, this is not valid syntax, and the JavaScript engine will throw a syntax error.

To use a ternary operator in JavaScript, the condition must evaluate to a boolean value, and the values returned based on the condition must be valid expressions. If you need to use a return statement in JavaScript, it should be used inside a function, and not inside the condition of a ternary operator.




Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article